/*!
 * Packery PACKAGED v1.0.6
 * bin-packing layout library
 * http://packery.metafizzy.co
 *
 * Commercial use requires one-time purchase of a commercial license
 * http://packery.metafizzy.co/license.html
 *
 * Non-commercial use is licensed under the MIT License
 *
 * Copyright 2013 Metafizzy
 */

(function(t){"use strict";function e(t){return RegExp("(^|\\s+)"+t+"(\\s+|$)")}function i(t,e){var i=n(t,e)?r:o;i(t,e)}var n,o,r;"classList"in document.documentElement?(n=function(t,e){return t.classList.contains(e)},o=function(t,e){t.classList.add(e)},r=function(t,e){t.classList.remove(e)}):(n=function(t,i){return e(i).test(t.className)},o=function(t,e){n(t,e)||(t.className=t.className+" "+e)},r=function(t,i){t.className=t.className.replace(e(i)," ")});var s={hasClass:n,addClass:o,removeClass:r,toggleClass:i,has:n,add:o,remove:r,toggle:i};"function"==typeof define&&define.amd?define(s):t.classie=s})(window),function(t){"use strict";var e=document.documentElement,i=function(){};e.addEventListener?i=function(t,e,i){t.addEventListener(e,i,!1)}:e.attachEvent&&(i=function(e,i,n){e[i+n]=n.handleEvent?function(){var e=t.event;e.target=e.target||e.srcElement,n.handleEvent.call(n,e)}:function(){var i=t.event;i.target=i.target||i.srcElement,n.call(e,i)},e.attachEvent("on"+i,e[i+n])});var n=function(){};e.removeEventListener?n=function(t,e,i){t.removeEventListener(e,i,!1)}:e.detachEvent&&(n=function(t,e,i){t.detachEvent("on"+e,t[e+i]);try{delete t[e+i]}catch(n){t[e+i]=void 0}});var o={bind:i,unbind:n};"function"==typeof define&&define.amd?define(o):t.eventie=o}(this),function(t){"use strict";function e(t){"function"==typeof t&&(e.isReady?t():r.push(t))}function i(t){var i="readystatechange"===t.type&&"complete"!==o.readyState;if(!e.isReady&&!i){e.isReady=!0;for(var n=0,s=r.length;s>n;n++){var a=r[n];a()}}}function n(n){return n.bind(o,"DOMContentLoaded",i),n.bind(o,"readystatechange",i),n.bind(t,"load",i),e}var o=t.document,r=[];e.isReady=!1,"function"==typeof define&&define.amd?define(["eventie"],n):t.docReady=n(t.eventie)}(this),function(t){"use strict";function e(){}function i(t,e){if(o)return e.indexOf(t);for(var i=e.length;i--;)if(e[i]===t)return i;return-1}var n=e.prototype,o=Array.prototype.indexOf?!0:!1;n._getEvents=function(){return this._events||(this._events={})},n.getListeners=function(t){var e,i,n=this._getEvents();if("object"==typeof t){e={};for(i in n)n.hasOwnProperty(i)&&t.test(i)&&(e[i]=n[i])}else e=n[t]||(n[t]=[]);return e},n.getListenersAsObject=function(t){var e,i=this.getListeners(t);return i instanceof Array&&(e={},e[t]=i),e||i},n.addListener=function(t,e){var n,o=this.getListenersAsObject(t);for(n in o)o.hasOwnProperty(n)&&-1===i(e,o[n])&&o[n].push(e);return this},n.on=n.addListener,n.defineEvent=function(t){return this.getListeners(t),this},n.defineEvents=function(t){for(var e=0;t.length>e;e+=1)this.defineEvent(t[e]);return this},n.removeListener=function(t,e){var n,o,r=this.getListenersAsObject(t);for(o in r)r.hasOwnProperty(o)&&(n=i(e,r[o]),-1!==n&&r[o].splice(n,1));return this},n.off=n.removeListener,n.addListeners=function(t,e){return this.manipulateListeners(!1,t,e)},n.removeListeners=function(t,e){return this.manipulateListeners(!0,t,e)},n.manipulateListeners=function(t,e,i){var n,o,r=t?this.removeListener:this.addListener,s=t?this.removeListeners:this.addListeners;if("object"!=typeof e||e instanceof RegExp)for(n=i.length;n--;)r.call(this,e,i[n]);else for(n in e)e.hasOwnProperty(n)&&(o=e[n])&&("function"==typeof o?r.call(this,n,o):s.call(this,n,o));return this},n.removeEvent=function(t){var e,i=typeof t,n=this._getEvents();if("string"===i)delete n[t];else if("object"===i)for(e in n)n.hasOwnProperty(e)&&t.test(e)&&delete n[e];else delete this._events;return this},n.emitEvent=function(t,e){var i,n,o,r=this.getListenersAsObject(t);for(n in r)if(r.hasOwnProperty(n))for(i=r[n].length;i--;)o=e?r[n][i].apply(null,e):r[n][i](),o===!0&&this.removeListener(t,r[n][i]);return this},n.trigger=n.emitEvent,n.emit=function(t){var e=Array.prototype.slice.call(arguments,1);return this.emitEvent(t,e)},"function"==typeof define&&define.amd?define(function(){return e}):t.EventEmitter=e}(this),function(t){"use strict";function e(t){if(t){if("string"==typeof n[t])return t;t=t.charAt(0).toUpperCase()+t.slice(1);for(var e,o=0,r=i.length;r>o;o++)if(e=i[o]+t,"string"==typeof n[e])return e}}var i="Webkit Moz ms Ms O".split(" "),n=document.documentElement.style;"function"==typeof define&&define.amd?define(function(){return e}):t.getStyleProperty=e}(window),function(t){"use strict";function e(t){var e=parseFloat(t),i=-1===t.indexOf("%")&&!isNaN(e);return i&&e}function i(){for(var t={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0},e=0,i=s.length;i>e;e++){var n=s[e];t[n]=0}return t}function n(t){function n(t){if("object"==typeof t&&t.nodeType){var n=r(t);if("none"===n.display)return i();var h={};h.width=t.offsetWidth,h.height=t.offsetHeight;for(var p=h.isBorderBox=!(!a||!n[a]||"border-box"!==n[a]),c=0,u=s.length;u>c;c++){var d=s[c],l=n[d],f=parseFloat(l);h[d]=isNaN(f)?0:f}var m=h.paddingLeft+h.paddingRight,y=h.paddingTop+h.paddingBottom,g=h.marginLeft+h.marginRight,v=h.marginTop+h.marginBottom,x=h.borderLeftWidth+h.borderRightWidth,E=h.borderTopWidth+h.borderBottomWidth,w=p&&o,S=e(n.width);S!==!1&&(h.width=S+(w?0:m+x));var b=e(n.height);return b!==!1&&(h.height=b+(w?0:y+E)),h.innerWidth=h.width-(m+x),h.innerHeight=h.height-(y+E),h.outerWidth=h.width+g,h.outerHeight=h.height+v,h}}var o,a=t("boxSizing");return function(){if(a){var t=document.createElement("div");t.style.width="200px",t.style.padding="1px 2px 3px 4px",t.style.borderStyle="solid",t.style.borderWidth="1px 2px 3px 4px",t.style[a]="border-box";var i=document.body||document.documentElement;i.appendChild(t);var n=r(t);o=200===e(n.width),i.removeChild(t)}}(),n}var o=document.defaultView,r=o&&o.getComputedStyle?function(t){return o.getComputedStyle(t,null)}:function(t){return t.currentStyle},s=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"];"function"==typeof define&&define.amd?define(["get-style-property"],n):t.getSize=n(t.getStyleProperty)}(window),function(t){"use strict";function e(){}function i(t){function i(e){e.prototype.option||(e.prototype.option=function(e){t.isPlainObject(e)&&(this.options=t.extend(!0,this.options,e))})}function o(e,i){t.fn[e]=function(o){if("string"==typeof o){for(var s=n.call(arguments,1),a=0,h=this.length;h>a;a++){var p=this[a],c=t.data(p,e);if(c)if(t.isFunction(c[o])&&"_"!==o.charAt(0)){var u=c[o].apply(c,s);if(void 0!==u)return u}else r("no such method '"+o+"' for "+e+" instance");else r("cannot call methods on "+e+" prior to initialization; "+"attempted to call '"+o+"'")}return this}return this.each(function(){var n=t.data(this,e);n?(n.option(o),n._init()):(n=new i(this,o),t.data(this,e,n))})}}if(t){var r="undefined"==typeof console?e:function(t){console.error(t)};t.bridget=function(t,e){i(e),o(t,e)}}}var n=Array.prototype.slice;"function"==typeof define&&define.amd?define(["jquery"],i):i(t.jQuery)}(window),function(t,e){"use strict";function i(t,e){return t[a](e)}function n(t){if(!t.parentNode){var e=document.createDocumentFragment();e.appendChild(t)}}function o(t,e){n(t);for(var i=t.parentNode.querySelectorAll(e),o=0,r=i.length;r>o;o++)if(i[o]===t)return!0;return!1}function r(t,e){return n(t),i(t,e)}var s,a=function(){if(e.matchesSelector)return"matchesSelector";for(var t=["webkit","moz","ms","o"],i=0,n=t.length;n>i;i++){var o=t[i],r=o+"MatchesSelector";if(e[r])return r}}();if(a){var h=document.createElement("div"),p=i(h,"div");s=p?i:r}else s=o;"function"==typeof define&&define.amd?define(function(){return s}):window.matchesSelector=s}(this,Element.prototype),function(t){"use strict";function e(t){for(var i in e.defaults)this[i]=e.defaults[i];for(i in t)this[i]=t[i]}var i=t.Packery=function(){};i.Rect=e,e.defaults={x:0,y:0,width:0,height:0},e.prototype.contains=function(t){var e=t.width||0,i=t.height||0;return this.x<=t.x&&this.y<=t.y&&this.x+this.width>=t.x+e&&this.y+this.height>=t.y+i},e.prototype.overlaps=function(t){var e=this.x+this.width,i=this.y+this.height,n=t.x+t.width,o=t.y+t.height;return n>this.x&&e>t.x&&o>this.y&&i>t.y},e.prototype.getMaximalFreeRects=function(t){if(!this.overlaps(t))return!1;var i,n=[],o=this.x+this.width,r=this.y+this.height,s=t.x+t.width,a=t.y+t.height;return this.y<t.y&&(i=new e({x:this.x,y:this.y,width:this.width,height:t.y-this.y}),n.push(i)),o>s&&(i=new e({x:s,y:this.y,width:o-s,height:this.height}),n.push(i)),r>a&&(i=new e({x:this.x,y:a,width:this.width,height:r-a}),n.push(i)),this.x<t.x&&(i=new e({x:this.x,y:this.y,width:t.x-this.x,height:this.height}),n.push(i)),n},e.prototype.canFit=function(t){return this.width>=t.width&&this.height>=t.height}}(window),function(t){"use strict";function e(t,e){this.width=t||0,this.height=e||0,this.reset()}var i=t.Packery,n=i.Rect;e.prototype.reset=function(){this.spaces=[],this.newSpaces=[];var t=new n({x:0,y:0,width:this.width,height:this.height});this.spaces.push(t)},e.prototype.pack=function(t){for(var e=0,i=this.spaces.length;i>e;e++){var n=this.spaces[e];if(n.canFit(t)){this.placeInSpace(t,n);break}}},e.prototype.placeInSpace=function(t,e){t.x=e.x,t.y=e.y,this.placed(t)},e.prototype.placed=function(t){for(var i=[],n=0,o=this.spaces.length;o>n;n++){var r=this.spaces[n],s=r.getMaximalFreeRects(t);s?i.push.apply(i,s):i.push(r)}this.spaces=i,e.mergeRects(this.spaces),this.spaces.sort(e.spaceSorterTopLeft)},e.mergeRects=function(t){for(var e=0,i=t.length;i>e;e++){var n=t[e];if(n){var o=t.slice(0);o.splice(e,1);for(var r=0,s=0,a=o.length;a>s;s++){var h=o[s],p=e>s?0:1;n.contains(h)&&(t.splice(s+p-r,1),r++)}}}return t},e.spaceSorterTopLeft=function(t,e){return t.y-e.y||t.x-e.x},e.spaceSorterLeftTop=function(t,e){return t.x-e.x||t.y-e.y},i.Packer=e}(window),function(t){"use strict";function e(t,e){for(var i in e)t[i]=e[i];return t}function i(t,e){this.element=t,this.packery=e,this.position={x:0,y:0},this.rect=new o,this.placeRect=new o,this.element.style.position="absolute"}var n=t.Packery,o=n.Rect,r=t.getSize,s=t.getStyleProperty,a=t.EventEmitter,h=document.defaultView,p=h&&h.getComputedStyle?function(t){return h.getComputedStyle(t,null)}:function(t){return t.currentStyle},c=s("transition"),u=s("transform"),d=c&&u,l=!!s("perspective"),f={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"otransitionend",transition:"transitionend"}[c],m={WebkitTransform:"-webkit-transform",MozTransform:"-moz-transform",OTransform:"-o-transform",transform:"transform"}[u];e(i.prototype,a.prototype),i.prototype.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},i.prototype.getSize=function(){this.size=r(this.element)},i.prototype.css=function(t){var e=this.element.style;for(var i in t)e[i]=t[i]},i.prototype.getPosition=function(){var t=p(this.element),e=parseInt(t.left,10),i=parseInt(t.top,10);e=isNaN(e)?0:e,i=isNaN(i)?0:i;var n=this.packery.elementSize;e-=n.paddingLeft,i-=n.paddingTop,this.position.x=e,this.position.y=i};var y=l?function(t,e){return"translate3d( "+t+"px, "+e+"px, 0)"}:function(t,e){return"translate( "+t+"px, "+e+"px)"};i.prototype._transitionTo=function(t,e){this.getPosition();var i=this.position.x,n=this.position.y,o=parseInt(t,10),r=parseInt(e,10),s=o===this.position.x&&r===this.position.y;if(this.setPosition(t,e),s&&!this.isTransitioning)return this.layoutPosition(),void 0;var a=t-i,h=e-n,p={};p[m]=y(a,h),this.transition(p,this.layoutPosition)},i.prototype.goTo=function(t,e){this.setPosition(t,e),this.layoutPosition()},i.prototype.moveTo=d?i.prototype._transitionTo:i.prototype.goTo,i.prototype.setPosition=function(t,e){this.position.x=parseInt(t,10),this.position.y=parseInt(e,10)},i.prototype.layoutPosition=function(){var t=this.packery.elementSize;this.css({left:this.position.x+t.paddingLeft+"px",top:this.position.y+t.paddingTop+"px"}),this.emitEvent("layout",[this])},i.prototype._nonTransition=function(t,e){this.css(t),e&&e.call(this)},i.prototype._transition=function(t,e){this.transitionStyle=t;var i=[];for(var n in t)i.push(n);var o={};o[c+"Property"]=i.join(","),o[c+"Duration"]=this.packery.options.transitionDuration,this.element.addEventListener(f,this,!1),e&&this.on("transitionEnd",function(t){return e.call(t),!0}),this.css(o),this.css(t),this.isTransitioning=!0},i.prototype.transition=i.prototype[c?"_transition":"_nonTransition"],i.prototype.onwebkitTransitionEnd=function(t){this.ontransitionend(t)},i.prototype.onotransitionend=function(t){this.ontransitionend(t)},i.prototype.ontransitionend=function(t){if(t.target===this.element){this.onTransitionEnd&&(this.onTransitionEnd(),delete this.onTransitionEnd),this.removeTransitionStyles();var e={};for(var i in this.transitionStyle)e[i]="";this.css(e),this.element.removeEventListener(f,this,!1),delete this.transitionStyle,this.isTransitioning=!1,this.emitEvent("transitionEnd",[this])}},i.prototype.removeTransitionStyles=function(){var t={};t[c+"Property"]="",t[c+"Duration"]="",this.css(t)},i.prototype.remove=function(){var t={opacity:0};t[m]="scale(0.001)",this.transition(t,this.removeElem)},i.prototype.removeElem=function(){this.element.parentNode.removeChild(this.element),this.emitEvent("remove",[this])},i.prototype.reveal=c?function(){var t={opacity:0};t[m]="scale(0.001)",this.css(t);var e=this.element.offsetHeight,i={opacity:1};i[m]="scale(1)",this.transition(i),e=null}:function(){},i.prototype.destroy=function(){this.css({position:"",left:"",top:""})},i.prototype.dragStart=function(){this.getPosition(),this.removeTransitionStyles(),this.isTransitioning&&u&&(this.element.style[u]="none"),this.getSize(),this.isPlacing=!0,this.needsPositioning=!1,this.positionPlaceRect(this.position.x,this.position.y),this.isTransitioning=!1,this.didDrag=!1},i.prototype.dragMove=function(t,e){this.didDrag=!0;var i=this.packery.elementSize;t-=i.paddingLeft,e-=i.paddingTop,this.positionPlaceRect(t,e)},i.prototype.dragStop=function(){this.getPosition();var t=this.position.x!==this.placeRect.x,e=this.position.y!==this.placeRect.y;this.needsPositioning=t||e,this.didDrag=!1},i.prototype.positionPlaceRect=function(t,e,i){this.placeRect.x=this.getPlaceRectCoord(t,!0),this.placeRect.y=this.getPlaceRectCoord(e,!1,i)},i.prototype.getPlaceRectCoord=function(t,e,i){var n=e?"Width":"Height",o=this.size["outer"+n],r=this.packery[e?"columnWidth":"rowHeight"],s=this.packery.elementSize["inner"+n];e||(s=Math.max(s,this.packery.maxY),this.packery.rowHeight||(s-=this.packery.gutter));var a;if(r){r+=this.packery.gutter,s+=e?this.packery.gutter:0,t=Math.round(t/r);var h=Math[e?"floor":"ceil"](s/r);h-=Math.ceil(o/r),a=h}else a=s-o;return t=i?t:Math.min(t,a),t*=r||1,Math.max(0,t)},i.prototype.copyPlaceRectPosition=function(){this.rect.x=this.placeRect.x,this.rect.y=this.placeRect.y},n.Item=i}(window),function(t){"use strict";function e(t,e){for(var i in e)t[i]=e[i];return t}function i(t){var e=[];if("number"==typeof t.length)for(var i=0,n=t.length;n>i;i++)e.push(t[i]);else e.push(t);return e}function n(t,i){if(!t||!g(t))return m&&m.error("bad Packery element: "+t),void 0;this.element=t,this.options=e({},this.options),e(this.options,i);var n=++x;this.element.packeryGUID=n,E[n]=this,this._create(),this.options.isInitLayout&&this.layout()}var o=t.Packery,r=o.Rect,s=o.Packer,a=o.Item,h=t.classie,p=t.docReady,c=t.EventEmitter,u=t.eventie,d=t.getSize,l=t.matchesSelector,f=t.document,m=t.console,y=t.jQuery,g="object"==typeof HTMLElement?function(t){return t instanceof HTMLElement}:function(t){return t&&"object"==typeof t&&1===t.nodeType&&"string"==typeof t.nodeName},v=Array.prototype.indexOf?function(t,e){return t.indexOf(e)}:function(t,e){for(var i=0,n=t.length;n>i;i++)if(t[i]===e)return i;return-1},x=0,E={};e(n.prototype,c.prototype),n.prototype.options={containerStyle:{position:"relative"},isInitLayout:!0,isResizeBound:!0,transitionDuration:"0.4s"},n.prototype._create=function(){this.packer=new s,this.reloadItems(),this.stampedElements=[],this.stamp(this.options.stamped);var t=this.options.containerStyle;e(this.element.style,t),this.options.isResizeBound&&this.bindResize();var i=this;this.handleDraggabilly={dragStart:function(t){i.itemDragStart(t.element)},dragMove:function(t){i.itemDragMove(t.element,t.position.x,t.position.y)},dragEnd:function(t){i.itemDragEnd(t.element)}},this.handleUIDraggable={start:function(t){i.itemDragStart(t.currentTarget)},drag:function(t,e){i.itemDragMove(t.currentTarget,e.position.left,e.position.top)},stop:function(t){i.itemDragEnd(t.currentTarget)}}},n.prototype.reloadItems=function(){this.items=this._getItems(this.element.children)},n.prototype._getItems=function(t){for(var e=this._filterFindItemElements(t),i=[],n=0,o=e.length;o>n;n++){var r=e[n],s=new a(r,this);i.push(s)}return i},n.prototype._filterFindItemElements=function(t){t=i(t);var e=this.options.itemSelector;if(!e)return t;for(var n=[],o=0,r=t.length;r>o;o++){var s=t[o];l(s,e)&&n.push(s);for(var a=s.querySelectorAll(e),h=0,p=a.length;p>h;h++)n.push(a[h])}return n},n.prototype.getItemElements=function(){for(var t=[],e=0,i=this.items.length;i>e;e++)t.push(this.items[e].element);return t},n.prototype.layout=function(){this._prelayout();var t=void 0!==this.options.isLayoutInstant?this.options.isLayoutInstant:!this._isLayoutInited;this.layoutItems(this.items,t),this._isLayoutInited=!0},n.prototype._init=n.prototype.layout,n.prototype._prelayout=function(){this.elementSize=d(this.element),this._getMeasurements(),this.packer.width=this.elementSize.innerWidth+this.gutter,this.packer.height=Number.POSITIVE_INFINITY,this.packer.reset(),this.maxY=0,this.placeStampedElements()},n.prototype._getMeasurements=function(){this._getMeasurement("columnWidth","width"),this._getMeasurement("rowHeight","height"),this._getMeasurement("gutter","width")},n.prototype._getMeasurement=function(t,e){var i,n=this.options[t];n?("string"==typeof n?i=this.element.querySelector(n):g(n)&&(i=n),this[t]=i?d(i)[e]:n):this[t]=0},n.prototype.layoutItems=function(t,e){var i=this._getLayoutItems(t);if(i&&i.length){this._itemsOn(i,"layout",function(){this.emitEvent("layoutComplete",[this,i])});for(var n=0,o=i.length;o>n;n++){var r=i[n];this._packItem(r),this._layoutItem(r,e)}}else this.emitEvent("layoutComplete",[this,[]]);var s=this.elementSize,a=this.maxY-this.gutter;s.isBorderBox&&(a+=s.paddingBottom+s.paddingTop+s.borderTopWidth+s.borderBottomWidth),a=Math.max(a,0),this.element.style.height=a+"px"},n.prototype._getLayoutItems=function(t){for(var e=[],i=0,n=t.length;n>i;i++){var o=t[i];o.isIgnored||e.push(o)}return e},n.prototype._packItem=function(t){this._setRectSize(t.element,t.rect),this.packer.pack(t.rect),this._setMaxY(t.rect)},n.prototype._setMaxY=function(t){this.maxY=Math.max(t.y+t.height,this.maxY)},n.prototype._setRectSize=function(t,e){var i=d(t),n=i.outerWidth,o=i.outerHeight,r=this.columnWidth+this.gutter,s=this.rowHeight+this.gutter;n=this.columnWidth?Math.ceil(n/r)*r:n+this.gutter,o=this.rowHeight?Math.ceil(o/s)*s:o+this.gutter,e.width=Math.min(n,this.packer.width),e.height=o},n.prototype._layoutItem=function(t,e){var i=t.rect;e?t.goTo(i.x,i.y):t.moveTo(i.x,i.y)},n.prototype._itemsOn=function(t,e,i){function n(){return o++,o===r&&i.call(s),!0}for(var o=0,r=t.length,s=this,a=0,h=t.length;h>a;a++){var p=t[a];p.on(e,n)}},n.prototype.stamp=function(t){if(t){"string"==typeof t&&(t=this.element.querySelectorAll(t)),t=i(t),this.stampedElements.push.apply(this.stampedElements,t);for(var e=0,n=t.length;n>e;e++){var o=t[e];this.ignore(o)}}},n.prototype.unstamp=function(t){if(t){t=i(t);for(var e=0,n=t.length;n>e;e++){var o=t[e],r=v(this.stampedElements,o);-1!==r&&this.stampedElements.splice(r,1),this.unignore(o)}}},n.prototype.placeStampedElements=function(){if(this.stampedElements&&this.stampedElements.length){this._getBounds();for(var t=0,e=this.stampedElements.length;e>t;t++){var i=this.stampedElements[t];this.placeStamp(i)}}},n.prototype._getBounds=function(){var t=this.element.getBoundingClientRect();this._boundingLeft=t.left+this.elementSize.paddingLeft,this._boundingTop=t.top+this.elementSize.paddingTop},n.prototype.placeStamp=function(t){var e,i=this.getItem(t);e=i&&i.isPlacing?i.placeRect:this._getElementOffsetRect(t),this._setRectSize(t,e),this.packer.placed(e),this._setMaxY(e)},n.prototype._getElementOffsetRect=function(t){var e=t.getBoundingClientRect(),i=new r({x:e.left-this._boundingLeft,y:e.top-this._boundingTop});return i.x-=this.elementSize.borderLeftWidth,i.y-=this.elementSize.borderTopWidth,i},n.prototype.handleEvent=function(t){var e="on"+t.type;this[e]&&this[e](t)},n.prototype.bindResize=function(){this.isResizeBound||(u.bind(t,"resize",this),this.isResizeBound=!0)},n.prototype.unbindResize=function(){u.unbind(t,"resize",this),this.isResizeBound=!1},n.prototype.onresize=function(){function t(){e.resize()}this.resizeTimeout&&clearTimeout(this.resizeTimeout);var e=this;this.resizeTimeout=setTimeout(t,100)},n.prototype.resize=function(){var t=d(this.element),e=this.elementSize&&t;e&&t.innerWidth===this.elementSize.innerWidth||(this.layout(),delete this.resizeTimeout)},n.prototype.addItems=function(t){var e=this._getItems(t);if(e.length)return this.items.push.apply(this.items,e),e},n.prototype.appended=function(t){var e=this.addItems(t);e.length&&(this.layoutItems(e,!0),this.reveal(e))},n.prototype.prepended=function(t){var e=this._getItems(t);if(e.length){var i=this.items.slice(0);this.items=e.concat(i),this._prelayout(),this.layoutItems(e,!0),this.reveal(e),this.layoutItems(i)}},n.prototype.reveal=function(t){if(t&&t.length)for(var e=0,i=t.length;i>e;e++){var n=t[e];n.reveal()}},n.prototype.getItem=function(t){for(var e=0,i=this.items.length;i>e;e++){var n=this.items[e];if(n.element===t)return n}},n.prototype.getItems=function(t){if(t&&t.length){for(var e=[],i=0,n=t.length;n>i;i++){var o=t[i],r=this.getItem(o);r&&e.push(r)}return e}},n.prototype.remove=function(t){t=i(t);var e=this.getItems(t);this._itemsOn(e,"remove",function(){this.emitEvent("removeComplete",[this,e])});for(var n=0,o=e.length;o>n;n++){var r=e[n];r.remove();var s=v(this.items,r);this.items.splice(s,1)}},n.prototype.ignore=function(t){var e=this.getItem(t);e&&(e.isIgnored=!0)},n.prototype.unignore=function(t){var e=this.getItem(t);e&&delete e.isIgnored},n.prototype.sortItemsByPosition=function(){this.items.sort(function(t,e){return t.position.y-e.position.y||t.position.x-e.position.x})},n.prototype.fit=function(t,e,i){function n(){s++,2===s&&r.emitEvent("fitComplete",[r,o])}var o=this.getItem(t);if(o){this._getMeasurements(),this.stamp(o.element),o.getSize(),o.isPlacing=!0,e=void 0===e?o.rect.x:e,i=void 0===i?o.rect.y:i,o.positionPlaceRect(e,i,!0);var r=this,s=0;o.on("layout",function(){return n(),!0}),this.on("layoutComplete",function(){return n(),!0}),o.moveTo(o.placeRect.x,o.placeRect.y),this.layout(),this.unstamp(o.element),this.sortItemsByPosition(),o.isPlacing=!1,o.copyPlaceRectPosition()}},n.prototype.itemDragStart=function(t){this.stamp(t);var e=this.getItem(t);e&&e.dragStart()},n.prototype.itemDragMove=function(t,e,i){function n(){r.layout(),delete r.dragTimeout}var o=this.getItem(t);o&&o.dragMove(e,i);var r=this;this.clearDragTimeout(),this.dragTimeout=setTimeout(n,40)},n.prototype.clearDragTimeout=function(){this.dragTimeout&&clearTimeout(this.dragTimeout)},n.prototype.itemDragEnd=function(t){function e(){return s++,s!==r?!0:(n&&(h.remove(n.element,"is-positioning-post-drag"),n.isPlacing=!1,n.copyPlaceRectPosition()),a.unstamp(t),a.sortItemsByPosition(),n&&o&&a.emitEvent("dragItemPositioned",[a,n]),!0)}var i,n=this.getItem(t);if(n&&(i=n.didDrag,n.dragStop()),!n||!i&&!n.needsPositioning)return this.unstamp(t),void 0;h.add(n.element,"is-positioning-post-drag");var o=n.needsPositioning,r=o?2:1,s=0,a=this;o?(n.on("layout",e),n.moveTo(n.placeRect.x,n.placeRect.y)):n&&n.copyPlaceRectPosition(),this.clearDragTimeout(),this.on("layoutComplete",e),this.layout()},n.prototype.bindDraggabillyEvents=function(t){t.on("dragStart",this.handleDraggabilly.dragStart),t.on("dragMove",this.handleDraggabilly.dragMove),t.on("dragEnd",this.handleDraggabilly.dragEnd)},n.prototype.bindUIDraggableEvents=function(t){t.on("dragstart",this.handleUIDraggable.start).on("drag",this.handleUIDraggable.drag).on("dragstop",this.handleUIDraggable.stop)},n.prototype.destroy=function(){this.element.style.position="",this.element.style.height="",delete this.element.packeryGUID;for(var t=0,e=this.items.length;e>t;t++){var i=this.items[t];i.destroy()}this.unbindResize()},n.data=function(t){var e=t.packeryGUID;return e&&E[e]},p(function(){for(var t=f.querySelectorAll(".js-packery"),e=0,i=t.length;i>e;e++){var o,r=t[e],s=r.getAttribute("data-packery-options");try{o=s&&JSON.parse(s)}catch(a){m&&m.error("Error parsing data-packery-options on "+r.nodeName.toLowerCase()+(r.id?"#"+r.id:"")+": "+a);continue}var h=new n(r,o);y&&y.data(r,"packery",h)}}),y&&y.bridget&&y.bridget("packery",n),n.Rect=r,n.Packer=s,n.Item=a,t.Packery=n}(window);


keep keep keep replace keep keep keep keep keep

.content-view-container {
position: relative;
height: 100%;
width: 100%;
}

// ## Tag Selector UI

/*global window, document, $ */
(function () {
    "use strict";

    var suggestions,
        categoryOffset,
        existingTags = [], // This will be replaced by an API return.
        keys = {
            UP: 38,
            DOWN: 40,
            ESC: 27,
            ENTER: 13,
            COMMA: 188,
            BACKSPACE: 8
        };

    function findTerms(searchTerm, array) {
        searchTerm = searchTerm.toUpperCase();
        return $.map(array, function (item) {
            var match = item.toUpperCase().indexOf(searchTerm) !== -1;
            return match ? item : null;
        });
    }

    function showSuggestions($target, searchTerm) {
        suggestions.show();
        var results = findTerms(searchTerm, existingTags),
            pos = $target.position(),
            styles = {
                left: pos.left
            },
            maxSuggestions = 5, // Limit the suggestions number
            results_length = results.length,
            i,
            suggest;

        suggestions.css(styles);
        suggestions.html("");

        if (results_length < maxSuggestions) {
            maxSuggestions = results_length;
        }
        for (i = 0; i < maxSuggestions; i += 1) {
            suggestions.append("
" + results[i] + "
");
        }

        suggest = $('ul.suggestions li a:contains("' + searchTerm + '")');

        suggest.each(function () {
            var src_str = $(this).html(),
                term = searchTerm,
                pattern;

            term = term.replace(/(\s+)/, "(<[^>]+>)*$1(<[^>]+>)*");
            pattern = new RegExp("(" + term + ")", "i");

            src_str = src_str.replace(pattern, "$1");
            /*jslint regexp: true */ // - would like to remove this
            src_str = src_str.replace(/([^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/, "$1$2$4");

            $(this).html(src_str);
        });
    }

    function handleTagKeyup(e) {
        var $target = $(e.currentTarget),
            searchTerm = $.trim($target.val()).toLowerCase(),
            category,
            populator;

        if (e.keyCode === keys.UP) {
            e.preventDefault();
            if (suggestions.is(":visible")) {
                if (suggestions.children(".selected").length === 0) {
                    suggestions.find("li:last-child").addClass('selected');
                } else {
                    suggestions.children(".selected").removeClass('selected').prev().addClass('selected');
                }
            }
        } else if (e.keyCode === keys.DOWN) {
            e.preventDefault();
            if (suggestions.is(":visible")) {
                if (suggestions.children(".selected").length === 0) {
                    suggestions.find("li:first-child").addClass('selected');
                } else {
                    suggestions.children(".selected").removeClass('selected').next().addClass('selected');
                }
            }
        } else if (e.keyCode === keys.ESC) {
            suggestions.hide();
        } else if ((e.keyCode === keys.ENTER || e.keyCode === keys.COMMA) && searchTerm) {
            // Submit tag using enter or comma key
            e.preventDefault();
            if (suggestions.is(":visible") && suggestions.children(".selected").length !== 0) {

                if ($('.category:containsExact("' + suggestions.children(".selected").text() + '")').length === 0) {

                    category = $('' + suggestions.children(".selected").text() + '');
                    if ($target.data('populate')) {

                        populator = $($target.data('populate'));
                        populator.append(category);
                    }
                }
                suggestions.hide();
            } else {
                if (e.keyCode === keys.COMMA) {
                    searchTerm = searchTerm.replace(",", "");
                }  // Remove comma from string if comma is uses to submit.
                if ($('.category:containsExact("' + searchTerm + '")').length === 0) {
                    category = $('' + searchTerm + '');
                    if ($target.data('populate')) {
                        populator = $($target.data('populate'));
                        populator.append(category);
                    }
                }
            }
            $target.val('').focus();
            searchTerm = ""; // Used to reset search term
            suggestions.hide();
        }

        if (e.keyCode === keys.UP || e.keyCode === keys.DOWN) {
            return false;
        }

        if (searchTerm) {
            showSuggestions($target, searchTerm);
        } else {
            suggestions.hide();
        }
    }

    function handleTagKeyDown(e) {
        var $target = $(e.currentTarget),
            populator,
            lastBlock;
        // Delete character tiggers on Keydown, so needed to check on that event rather than Keyup.
        if (e.keyCode === keys.BACKSPACE && !$target.val()) {
            populator = $($target.data('populate'));
            lastBlock = populator.find('.category').last();
            lastBlock.remove();
        }
    }

    function handleSuggestionClick(e) {
        var $target = $(e.currentTarget),
            category = $('' + $(e.currentTarget).text() + ''),
            populator;

        if ($target.parent().data('populate')) {
            populator = $($target.parent().data('populate'));
            populator.append(category);
            suggestions.hide();
            $('[data-input-behaviour="tag"]').val('').focus();
        }
    }

    function handleCategoryClick(e) {
        $(e.currentTarget).remove();
    }

    function handleClickOff(e) {
        if (window.matchMedia('(max-width: 650px)').matches) {
            e.preventDefault();
            $('body').toggleClass('off-canvas');
        }
    }

    $(document).ready(function () {
        suggestions = $("ul.suggestions").hide(); // Initnialise suggestions overlay

        if ($('.category-input').length) {
            categoryOffset = $('.category-input').offset().left;
            $('.category-blocks').css({'left': categoryOffset + 'px'});
        }

        $('[data-input-behaviour="tag"]')
            .on('keyup', handleTagKeyup)
            .on('keydown', handleTagKeyDown);
        $('ul.suggestions').on('click', "li", handleSuggestionClick);
        $('.categories').on('click', ".category", handleCategoryClick);
        $('[data-off-canvas]').on('click', handleClickOff);
    });

}());


keep keep keep replace replace replace replace replace keep keep keep keep keep

position: relative;
width: 100%;
height: 100%;

/*
 * These styles control elements specific to the post editor screen
 * used for publishing content with Ghost.
 *
 * Table of Contents:
 *
 * Editor / Preview
 * Post Preview Content
 * Full Screen Mode
 * Publish Bar
 * CodeMirror
 */

/* =============================================================================
   Editor / Preview
   ============================================================================= */

.editor {

	// The main post title
	.entry-title {
		@extend %box;
		height: 35px;
		padding: 10px 15px;
		margin-bottom: 15px;
		position:relative;

		@include breakpoint($mobile) {
			box-shadow: none;
		}

		input {
			border: 0;
			margin: 0;
			padding:0;
			font-size: 2em;
			font-weight: 300;
			width: 100%;
			&:focus {
				outline: 0;
			}
		}

	}

    .entry-container {
        position: relative;
        height: -webkit-calc(100% - 70px);
        height: -moz-calc(100% - 70px);
        height: calc(100% - 70px);
    }

	// The two content panel wrappers, positioned left/right
	.entry-markdown { left:0; border-right:$lightbrown 2px solid; }
	.entry-preview { right:0; border-left:$lightbrown 2px solid; }

	// The visual styles for both panels
	.entry-markdown, .entry-preview {
		@include box-sizing(border-box);
		width: 50%;
		padding: 15px;
		position: absolute;
		bottom:40px; // height of the publish bar
		top:0px; // height of the post title + margin
		background: #fff;
		box-shadow: $shadow;

		@include breakpoint($mobile) {
			box-shadow: none;
		}

		// Convert all content areas to small boxes
		@include breakpoint($netbook) {
			top:40px;
			left:0;
			right:0;
			width:100%;
			border:none;
			z-index:100;
			min-height:380px;
			.markdown, .entry-preview-content {
				height:50px;
				overflow: hidden;
			}
		}

		.floatingheader {

			// Turn headers into tabs which act as links
			// both headers set to grey/inactive colour
			@include breakpoint($netbook) {
			    cursor:pointer;
			    width:50%;
			    border-right:$lightbrown 2px solid;
			    color:#fff;
			    font-weight: normal;
			    background:$brown;
			    position:absolute;
			    top:-40px;
			    left:0;
			    box-shadow: rgba(0,0,0,0.1) 0 -2px 3px inset;

			    a {
			        color:#fff;
			    }
			}

			a {
			    color: $brown;
			}

			.markdown-help {
			    @include icon($i-question, '', lighten($brown, 15%));
			    float:right;

			    &:hover {
			        @include icon($i-question, '', $brown)
			    }
			}

			.entry-word-count {
			    float:right;
			}

		}

		// Give the tab with the .active class the highest z-index
		&.active {
			z-index: 200;
		}

		// Restore the normal height of the .active tab (inactive tab stays small, hidden behind)
		&.active .markdown,
		&.active .entry-preview-content {
			height:auto;
			overflow: auto;
		}

		// Restore the white bg of the currently .active tab, remove hand cursor from currently active tab
		&.active header {
			@include breakpoint($netbook) {
				cursor:auto;
				color: $brown;
				background:#fff;
				box-shadow: none;
				a {
					color: $brown;
				}
			}
		}

		// Hide markdown icon + wordcount when we hit mobile
		@include breakpoint($mobile) {
			.markdown-help,
			.entry-word-count {
				display: none;
			}
		}

	}

	.entry-markdown-content {

		textarea {
			border: 0;
			width: 100%;
			height: 100%;
			max-width: 100%;
			margin: 0;
			padding: 0;
			position:absolute;
			top: 0;
			right:0;
			bottom:0;
			left:0;

			&:focus {
				outline: 0;
			}
		}

		.CodeMirror {
			height: auto;
			position:absolute;
			top:0;
			left:0;
			right:0;
			bottom:0;
			font-family: $font-family-mono;
			font-size:1.1em;
			line-height:1.2em;
			color: lighten($darkgrey, 30%);

			.CodeMirror-focused,
			.CodeMirror-selected {
			    color: $darkgrey;
			    background: lighten($blue, 20%);
			    text-shadow: none;
			}

			::selection {
			    color: $darkgrey;
			    background: lighten($blue, 20%);
			    text-shadow: none;
			}
		}

		.CodeMirror-lines {
			padding: 65px 0 40px 0; /* Vertical padding around content */
			@include breakpoint($netbook) {padding-top: 25px;}
			@include breakpoint($mobile) {padding: 15px 0;}
		}
		.CodeMirror pre {
		 	padding: 0 40px; /* Horizontal padding of content */
		 	@include breakpoint($mobile) {padding: 0 15px;}
		}

		.cm-header {
			color:#000;
			font-size: 1.4em;
			line-height: 1.4em;
		}

		.cm-string,
		.cm-link,
		.cm-comment,
		.cm-quote {color:#000;}

	}

	.entry-preview {
		// Align the tab of entry-preview on the right
		.floatingheader {
			@include breakpoint($netbook) {
				right:0;
				left:auto;
				border-right:none;
				border-left:$lightbrown 2px solid;
			}
		}

		.entry-preview-content {
			position:absolute;
			top:0;
			right:0;
			bottom:0;
			left:0;
			padding: 60px 40px 40px 40px;
			overflow: auto;

			// Tweak padding for smaller screens
			@include breakpoint($netbook) {padding-top: 20px;}
			@include breakpoint($mobile) {padding: 15px;}
		}

	}

	// Special case, when scrolling, add shadows to content headers.
	.scrolling {

		.floatingheader {
			@include breakpoint($netbook) {
	            box-shadow: none;
	        }

	        &::before,
	        &::after {
	        	@include breakpoint($netbook) {display:none;}
	        }
		}
		.CodeMirror-scroll,
		.entry-preview-content {
			@include breakpoint($netbook) {
				box-shadow: 0 5px 5px rgba(0,0,0,0.05) inset;
			}
		}
	}

}//.editor

/* =============================================================================
   Post Preview Content
   ============================================================================= */

// The styles for the actual content inside the preview
// TODO: These should just be defaults, overridden by editor.hbs in theme dir
.entry-preview-content,
.content-preview-content {
	font-size:1.15em;
	line-height: 1.5em;

	a {
		color: $blue;
		text-decoration: underline;
	}
	p {
		text-indent: 0;
		margin: 1.2em 0 1.6em;
		&:first-child {
			margin-top:0;
		}
	}
	h1 {
		font-size: 3em;
	}
	h2 {
		font-size: 2.2em;
	}
	h3 {
		font-size: 1.8em;
	}
	.btn {
		text-decoration: none;
		color: $grey;
	}
	.img-placeholder {
		border: 5px dashed $grey;
		height: 100px;
		position: relative;
		span {
			display: block;
			height: 30px;
			position: absolute;
			margin-top: -15px;
			top: 50%;
			width: 100%;
			text-align: center;
		}
	}

	img {
		width: 100%;
		height: auto;
	}
}

/* =============================================================================
   Full Screen Mode
   ============================================================================= */

body.zen {
	background: lighten($lightbrown, 3%);
	#usermenu {display:none;}
	#global-header, #publish-bar {
		opacity: 0;
		height:0;
		overflow: hidden;
		@include transition(all 0.5s ease-out);
	}

	main {top: 15px;@include transition(all 0.5s ease-out);}
	.entry-markdown, .entry-preview {bottom:0;@include transition(all 0.5s ease-out);}

}

/* =============================================================================
   Publish Bar
   ============================================================================= */

#publish-bar {
	@include box-sizing(border-box);
	height:40px;
	padding: 0;
	color: $midgrey;
	background: darken($darkgrey, 4%);
	position: fixed;
	bottom: 0;
	left:0;
	right:0;
	z-index:900;
	box-shadow: 0 -2px 8px rgba(0,0,0,0.2);

	@include breakpoint($netbook) {font-weight:normal;}

	button {
		min-height: 30px;
		height: 30px;
		line-height: 12px;
		padding: 0 10px;
		margin-top: 5px;
		border-top:rgba(255,255,255,0.4) 1px solid;
	}

	.button-link { border-top: none; }

	.options {
		width:30px;
		min-height: 30px;
		height: 30px;
		margin-top:5px;
		box-shadow: rgba(255,255,255,0.4) 0 1px 0 inset;

		&.up:hover {
            @include icon($i-chevron-down) {
                margin-top:-5px;
                @include transform(rotate(540deg));
                @include transition(transform 0.6s ease);
            };
        }
	}

	.splitbutton-save{
		.button-save{
			@include transition(width 0.25s ease);
		}

		.editor-options{
			@extend %menu;
	    	@extend %menu-right;
	    	bottom: 140%;
	    	right: -3%;

	    	a{
	    		font-size: 14px;
	    	}
		}
	}
}

#entry-categories {
	position: absolute;
	top:0;
	left:0;
	right: 165px;
	bottom:0;
	text-transform: none;
	padding: 10px 0 0 0;
}

.category-label {
	display: block;
	float:left;
	@include icon($i-tag);
	padding:1px 8px 0 8px;
	@include transition;

	&:hover {
		cursor:pointer;
		color: $lightgrey;
	}
}

.category-input {
	display: inline-block;
	color: $lightgrey;
	font-weight: 300;
	background: transparent;
	border: none;

	&:focus {outline:none;}
}

.category {
	@include icon-after($i-x, 8px, $darkgrey) {
		margin-left:4px;
		vertical-align:5%;
		text-shadow: rgba(255,255,255,0.15) 0 1px 0;
		@include transition;
	}
	display: block;
	float: left;
	margin-right: 5px;
	padding: 0 5px;
	color: $lightgrey;
	background: lighten($grey, 15%);
	border-radius: $rounded;
	box-shadow:
		rgba(255,255,255,0.2) 0 1px 0 inset,
		#000 0 1px 3px;

	&:hover {
		cursor: pointer;
		@include icon-after($i-x, 8px, $lightgrey) {text-shadow: none;}

	}
}

.suggestions {
  @extend %menu;
  bottom: 100%;

  li.selected{
    background: $blue;
    box-shadow:
        rgba(255,255,255,0.2) 0 1px 0 inset,
        rgba(0,0,0,0.5) 0 1px 5px;
  }

  mark{
    background: none;
    color: white;
    font-weight: bold;
  }
}

#entry-settings {
	@include icon($i-settings, 1.1em){vertical-align:0;};
	@include box-sizing(border-box);
	display:inline-block;
	padding: 0 10px;
	line-height: 1.8em;
	color: $midgrey;
	@include transition;

	&:hover {
		color: $lightgrey;
	}
}

#entry-settings-menu {
	position: absolute;
    bottom:50px;
    right:-5px;
}

#entry-actions {
	margin-right:6px;
	position: relative;
}

#entry-actions-menu {
    position: absolute;
    bottom:50px;
    right:-5px;
}

/* =============================================================================
   CodeMirror
   ============================================================================= */

.CodeMirror {
    /* Set height, width, borders, and global font properties here */
    font-family: monospace;
    height: 300px;
}

.CodeMirror-scroll {
    /* Set scrolling behaviour here */
    overflow: auto;
}

/* PADDING */

.CodeMirror-lines {
    padding: 4px 0; /* Vertical padding around content */
}

.CodeMirror pre {
    padding: 0 4px; /* Horizontal padding of content */
}

.CodeMirror-scrollbar-filler {
    background-color: white; /* The little square between H and V scrollbars */
}

/* GUTTER */

.CodeMirror-gutters {
    border-right: 1px solid #ddd;
    background-color: #f7f7f7;
}

/* CURSOR */

.CodeMirror div.CodeMirror-cursor {
    border-left: 1px solid black;
    z-index: 3;
}
/* Shown when moving in bi-directional text */
.CodeMirror div.CodeMirror-secondarycursor {
    border-left: 1px solid silver;
}

.cm-tab { display: inline-block; }

/* DEFAULT THEME */

.cm-s-default .cm-keyword {color: #708;}
.cm-s-default .cm-atom {color: #219;}
.cm-s-default .cm-number {color: #164;}
.cm-s-default .cm-def {color: #00f;}
.cm-s-default .cm-variable {color: black;}
.cm-s-default .cm-variable-2 {color: #05a;}
.cm-s-default .cm-variable-3 {color: #085;}
.cm-s-default .cm-property {color: black;}
.cm-s-default .cm-operator {color: black;}
.cm-s-default .cm-comment {color: #a50;}
.cm-s-default .cm-string {color: #a11;}
.cm-s-default .cm-string-2 {color: #f50;}
.cm-s-default .cm-meta {color: #555;}
.cm-s-default .cm-error {color: #f00;}
.cm-s-default .cm-qualifier {color: #555;}
.cm-s-default .cm-builtin {color: #30a;}
.cm-s-default .cm-bracket {color: #997;}
.cm-s-default .cm-tag {color: #170;}
.cm-s-default .cm-attribute {color: #00c;}
.cm-s-default .cm-header {color: blue;}
.cm-s-default .cm-quote {color: #090;}
.cm-s-default .cm-hr {color: #999;}
.cm-s-default .cm-link {color: #00c;}

.cm-negative {color: #d44;}
.cm-positive {color: #292;}
.cm-header, .cm-strong {font-weight: bold;}
.cm-em {font-style: italic;}
.cm-link {text-decoration: underline;}

.cm-invalidchar {color: #f00;}

/* STOP */

/* The rest of this file contains styles related to the mechanics of
   the editor. You probably shouldn't touch them. */

.CodeMirror {
    line-height: 1;
    position: relative;
    overflow: hidden;
    background: white;
    color: black;
}

.CodeMirror-scroll {
    /* 30px is the magic margin used to hide the element's real scrollbars */
    /* See overflow: hidden in .CodeMirror */
    margin-bottom: -30px; margin-right: -30px;
    padding-bottom: 30px; padding-right: 30px;
    height: 100%;
    outline: none; /* Prevent dragging from highlighting the element */
    position: relative;
}
.CodeMirror-sizer {
    position: relative;
}

/* The fake, visible scrollbars. Used to force redraw during scrolling
   before actuall scrolling happens, thus preventing shaking and
   flickering artifacts. */
.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler {
    position: absolute;
    z-index: 6;
    display: none;
}

.CodeMirror-vscrollbar {
    right: 0; top: 0;
    overflow-x: hidden;
    overflow-y: scroll;
}

.CodeMirror-hscrollbar {
    bottom: 0; left: 0;
    overflow-y: hidden;
    overflow-x: scroll;
}

.CodeMirror-scrollbar-filler {
    right: 0; bottom: 0;
    z-index: 6;
}

.CodeMirror-gutters {
    position: absolute; left: 0; top: 0;
    height: 100%;
    padding-bottom: 30px;
    z-index: 3;
}

.CodeMirror-lines {
    cursor: text;
}

.CodeMirror pre {
    /* Reset some styles that the rest of the page might have set */
    -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
    border-width: 0;
    background: transparent;
    font-family: inherit;
    font-size: inherit;
    margin: 0;
    white-space: pre;
    word-wrap: normal;
    line-height: inherit;
    color: inherit;
    z-index: 2;
    position: relative;
    overflow: visible;
}

.CodeMirror-wrap pre {
    word-wrap: break-word;
    white-space: pre-wrap;
    word-break: normal;
}

.CodeMirror-wrap .CodeMirror-scroll {
    overflow-x: hidden;
}

.CodeMirror-measure {
    position: absolute;
    width: 100%; height: 0px;
    overflow: hidden;
    visibility: hidden;
}

.CodeMirror-measure pre { position: static; }

.CodeMirror div.CodeMirror-cursor {
    position: absolute;
    visibility: hidden;
    border-right: none;
    width: 0;
}

.CodeMirror-focused div.CodeMirror-cursor {
    visibility: visible;
}

.CodeMirror-selected { background: #d9d9d9; }
.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }

/* IE7 hack to prevent it from returning funny offsetTops on the spans */
.CodeMirror span { *vertical-align: text-bottom; }

@media print {
/* Hide the cursor when printing */
    .CodeMirror div.CodeMirror-cursor {
        visibility: hidden;
    }
}


<!doctype html>

    <meta charset="utf-8">
    <title>CodeMirror: Markdown mode</title>
    <link rel="stylesheet" href="../../lib/codemirror.css">

    <link rel="stylesheet" href="../../doc/docs.css">

CodeMirror: Markdown mode

<form><textarea id="code" name="code">
Markdown: Basics
================

<ul id="ProjectSubmenu">
    <li><a href="/projects/markdown/" title="Markdown Project Page">Main</a></li>
    <li><a class="selected" title="Markdown Basics">Basics</a></li>
    <li><a href="/projects/markdown/syntax" title="Markdown Syntax Documentation">Syntax</a></li>
    <li><a href="/projects/markdown/license" title="Pricing and License Information">License</a></li>
    <li><a href="/projects/markdown/dingus" title="Online Markdown Web Form">Dingus</a></li>
</ul>

Getting the Gist of Markdown's Formatting Syntax
------------------------------------------------

This page offers a brief overview of what it's like to use Markdown.
The [syntax page] [s] provides complete, detailed documentation for
every feature, but Markdown should be very easy to pick up simply by
looking at a few examples of it in action. The examples on this page
are written in a before/after style, showing example syntax and the
HTML output produced by Markdown.

It's also helpful to simply try Markdown out; the [Dingus] [d] is a
web application that allows you type your own Markdown-formatted text
and translate it to XHTML.

**Note:** This document is itself written using Markdown; you
can [see the source for it by adding '.text' to the URL] [src].

  [s]: /projects/markdown/syntax  "Markdown Syntax"
  [d]: /projects/markdown/dingus  "Markdown Dingus"
  [src]: /projects/markdown/basics.text

## Paragraphs, Headers, Blockquotes ##

A paragraph is simply one or more consecutive lines of text, separated
by one or more blank lines. (A blank line is any line that looks like
a blank line -- a line containing nothing but spaces or tabs is
considered blank.) Normal paragraphs should not be indented with
spaces or tabs.

Markdown offers two styles of headers: *Setext* and *atx*.
Setext-style headers for `<h1>` and `<h2>` are created by
"underlining" with equal signs (`=`) and hyphens (`-`), respectively.
To create an atx-style header, you put 1-6 hash marks (`#`) at the
beginning of the line -- the number of hashes equals the resulting
HTML header level.

Blockquotes are indicated using email-style '`>`' angle brackets.

Markdown:

    A First Level Header
    ====================

    A Second Level Header
    ---------------------

    Now is the time for all good men to come to
    the aid of their country. This is just a
    regular paragraph.

    The quick brown fox jumped over the lazy
    dog's back.

    ### Header 3

    > This is a blockquote.
    >
    > This is the second paragraph in the blockquote.
    >
    > ## This is an H2 in a blockquote

Output:

    <h1>A First Level Header</h1>

    <h2>A Second Level Header</h2>

    <p>Now is the time for all good men to come to
    the aid of their country. This is just a
    regular paragraph.</p>

    <p>The quick brown fox jumped over the lazy
    dog's back.</p>

    <h3>Header 3</h3>

    <blockquote>
        <p>This is a blockquote.</p>

        <p>This is the second paragraph in the blockquote.</p>

        <h2>This is an H2 in a blockquote</h2>
    </blockquote>

### Phrase Emphasis ###

Markdown uses asterisks and underscores to indicate spans of emphasis.

Markdown:

    Some of these words *are emphasized*.
    Some of these words _are emphasized also_.

    Use two asterisks for **strong emphasis**.
    Or, if you prefer, __use two underscores instead__.

Output:

    <p>Some of these words <em>are emphasized</em>.
    Some of these words <em>are emphasized also</em>.</p>

    <p>Use two asterisks for <strong>strong emphasis</strong>.
    Or, if you prefer, <strong>use two underscores instead</strong>.</p>

## Lists ##

Unordered (bulleted) lists use asterisks, pluses, and hyphens (`*`,
`+`, and `-`) as list markers. These three markers are
interchangable; this:

    *   Candy.
    *   Gum.
    *   Booze.

this:

    +   Candy.
    +   Gum.
    +   Booze.

and this:

    -   Candy.
    -   Gum.
    -   Booze.

all produce the same output:

    <ul>
    <li>Candy.</li>
    <li>Gum.</li>
    <li>Booze.</li>
    </ul>

Ordered (numbered) lists use regular numbers, followed by periods, as
list markers:

    1.  Red
    2.  Green
    3.  Blue

Output:

    <ol>
    <li>Red</li>
    <li>Green</li>
    <li>Blue</li>
    </ol>

If you put blank lines between items, you'll get `<p>` tags for the
list item text. You can create multi-paragraph list items by indenting
the paragraphs by 4 spaces or 1 tab:

    *   A list item.

        With multiple paragraphs.

    *   Another item in the list.

Output:

    <ul>
    <li><p>A list item.</p>
    <p>With multiple paragraphs.</p></li>
    <li><p>Another item in the list.</p></li>
    </ul>

### Links ###

Markdown supports two styles for creating links: *inline* and
*reference*. With both styles, you use square brackets to delimit the
text you want to turn into a link.

Inline-style links use parentheses immediately after the link text.
For example:

    This is an [example link](http://example.com/).

Output:

    <p>This is an <a href="http://example.com/">
    example link</a>.</p>

Optionally, you may include a title attribute in the parentheses:

    This is an [example link](http://example.com/ "With a Title").

Output:

    <p>This is an <a href="http://example.com/" title="With a Title">
    example link</a>.</p>

Reference-style links allow you to refer to your links by names, which
you define elsewhere in your document:

    I get 10 times more traffic from [Google][1] than from
    [Yahoo][2] or [MSN][3].

    [1]: http://google.com/        "Google"
    [2]: http://search.yahoo.com/  "Yahoo Search"
    [3]: http://search.msn.com/    "MSN Search"

Output:

    <p>I get 10 times more traffic from <a href="http://google.com/"
    title="Google">Google</a> than from <a href="http://search.yahoo.com/"
    title="Yahoo Search">Yahoo</a> or <a href="http://search.msn.com/"
    title="MSN Search">MSN</a>.</p>

The title attribute is optional. Link names may contain letters,
numbers and spaces, but are *not* case sensitive:

    I start my morning with a cup of coffee and
    [The New York Times][NY Times].

    [ny times]: http://www.nytimes.com/

Output:

    <p>I start my morning with a cup of coffee and
    <a href="http://www.nytimes.com/">The New York Times</a>.</p>

### Images ###

Image syntax is very much like link syntax.

Inline (titles are optional):

    ![alt text](/path/to/img.jpg "Title")

Reference-style:

    ![alt text][id]

    [id]: /path/to/img.jpg "Title"

Both of the above examples produce the same output:

    <img src="/path/to/img.jpg" alt="alt text" title="Title" />

### Code ###

In a regular paragraph, you can create code span by wrapping text in
backtick quotes. Any ampersands (`&`) and angle brackets (`<` or
`>`) will automatically be translated into HTML entities. This makes
it easy to use Markdown to write about HTML example code:

    I strongly recommend against using any `<blink>` tags.

    I wish SmartyPants used named entities like `&mdash;`
    instead of decimal-encoded entites like `&#8212;`.

Output:

    <p>I strongly recommend against using any
    <code>&lt;blink&gt;</code> tags.</p>

    <p>I wish SmartyPants used named entities like
    <code>&amp;mdash;</code> instead of decimal-encoded
    entites like <code>&amp;#8212;</code>.</p>

To specify an entire block of pre-formatted code, indent every line of
the block by 4 spaces or 1 tab. Just like with code spans, `&`, `<`,
and `>` characters will be escaped automatically.

Markdown:

    If you want your page to validate under XHTML 1.0 Strict,
    you've got to put paragraph tags in your blockquotes:

        <blockquote>
            <p>For example.</p>
        </blockquote>

Output:

    <p>If you want your page to validate under XHTML 1.0 Strict,
    you've got to put paragraph tags in your blockquotes:</p>

    <pre><code>&lt;blockquote&gt;
        &lt;p&gt;For example.&lt;/p&gt;
    &lt;/blockquote&gt;
    </code></pre>
</textarea></form>

Optionally depends on the XML mode for properly highlighted inline XML blocks.

MIME types defined: text/x-markdown.

Parsing/Highlighting Tests: normal,  verbose.


keep keep keep keep add keep keep keep keep keep

// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "content/nw/src/shell_browser_main_parts.h"

#include "base/bind.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/string_number_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/nw/src/api/app/app.h"
#include "content/nw/src/browser/shell_devtools_delegate.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/nw_package.h"
#include "content/nw/src/nw_shell.h"
#include "content/nw/src/shell_browser_context.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "grit/net_resources.h"
#include "net/base/net_module.h"
#include "ui/base/resource/resource_bundle.h"

#if defined(TOOLKIT_GTK)
#include "content/nw/src/browser/printing/print_dialog_gtk.h"
#endif

namespace {

base::StringPiece PlatformResourceProvider(int key) {
  if (key == IDR_DIR_HEADER_HTML) {
    base::StringPiece html_data =
        ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
            IDR_DIR_HEADER_HTML);
    return html_data;
  }
  return base::StringPiece();
}

}  // namespace

namespace content {

ShellBrowserMainParts::ShellBrowserMainParts(
    const MainFunctionParams& parameters)
    : BrowserMainParts(),
      parameters_(parameters),
      run_message_loop_(true),
      devtools_delegate_(NULL)
{
}

ShellBrowserMainParts::~ShellBrowserMainParts() {
}

#if !defined(OS_MACOSX)
void ShellBrowserMainParts::PreMainMessageLoopStart() {
}
#endif

void ShellBrowserMainParts::PreMainMessageLoopRun() {
#if !defined(OS_MACOSX)
  Init();
#endif

  if (parameters_.ui_task) {
    parameters_.ui_task->Run();
    delete parameters_.ui_task;
    run_message_loop_ = false;
  }
}

bool ShellBrowserMainParts::MainMessageLoopRun(int* result_code)  {
  return !run_message_loop_;
}

void ShellBrowserMainParts::PostMainMessageLoopRun() {
  if (devtools_delegate_)
    devtools_delegate_->Stop();
  browser_context_.reset();
  off_the_record_browser_context_.reset();
}

void ShellBrowserMainParts::PostMainMessageLoopStart() {
#if defined(TOOLKIT_GTK)
  printing::PrintingContextGtk::SetCreatePrintDialogFunction(
      &PrintDialogGtk::CreatePrintDialog);
#endif
}

void ShellBrowserMainParts::Init() {
  package_.reset(new nw::Package());

  browser_context_.reset(new ShellBrowserContext(false, package()));
  off_the_record_browser_context_.reset(
      new ShellBrowserContext(true, package()));

  // OS X automatically handles multi process issue for us, so we don't need
  // to check for other instances of node-webkit on Mac.
#if !defined(MAC_OSX)
  process_singleton_.reset(new ProcessSingleton(browser_context_->GetPath()));
  ProcessSingleton::NotifyResult result =
      process_singleton_->NotifyOtherProcessOrCreate(
                                                     base::Bind(&ShellBrowserMainParts::ProcessSingletonNotificationCallback, base::Unretained(this)));

  // Quit if the other existing instance want to handle it.
  if (result == ProcessSingleton::PROCESS_NOTIFIED) {
    MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
    return;
  }
#endif

  net::NetModule::SetResourceProvider(PlatformResourceProvider);

  int port = 0;
  // See if the user specified a port on the command line (useful for
  // automation). If not, use an ephemeral port by specifying 0.
  CommandLine& command_line = *CommandLine::ForCurrentProcess();
  if (command_line.HasSwitch(switches::kRemoteDebuggingPort)) {
    int temp_port;
    std::string port_str =
        command_line.GetSwitchValueASCII(switches::kRemoteDebuggingPort);
    if (base::StringToInt(port_str, &temp_port) &&
        temp_port > 0 && temp_port < 65535) {
      port = temp_port;
    } else {
      DLOG(WARNING) << "Invalid http debugger port number " << temp_port;
    }
  }
  devtools_delegate_ = new ShellDevToolsDelegate(browser_context_.get(), port);

  Shell::Create(browser_context_.get(),
                package()->GetStartupURL(),
                NULL,
                MSG_ROUTING_NONE,
                NULL);
}

bool ShellBrowserMainParts::ProcessSingletonNotificationCallback(
    const CommandLine& command_line,
    const base::FilePath& current_directory) {
  if (!package_->self_extract()) {
    // We're in runtime mode, create the new app.
    return false;
  }

  // Don't reuse current instance if 'single-instance' is specified to false.
  bool single_instance;
  if (package_->root()->GetBoolean(switches::kmSingleInstance,
                                   &single_instance) &&
      !single_instance)
    return false;

  CommandLine::StringVector args = command_line.GetArgs();

  // Send open event one by one.
  for (size_t i = 0; i < args.size(); ++i) {
#if defined(OS_WIN)
    api::App::EmitOpenEvent(UTF16ToUTF8(args[i]));
#else
    api::App::EmitOpenEvent(args[i]);
#endif
  }

  return true;
}

}  // namespace content


// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "content/nw/src/net/resource_request_job.h"

#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/logging.h"
#include "googleurl/src/gurl.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job.h"
#include "grit/nw_resources.h"
#include "ui/base/resource/resource_bundle.h"

namespace nw {

ResourceRequestJob::ResourceRequestJob(
    net::URLRequest* request,
    net::NetworkDelegate* network_delegate,
    std::string mime_type,
    int resource_id)
    : net::URLRequestJob(request, network_delegate),
      data_offset_(0),
      pending_buf_size_(0),
      mime_type_(mime_type),
      resource_id_(resource_id),
      ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
}

// static
ResourceRequestJob* ResourceRequestJob::Factory(
    net::URLRequest* request,
    net::NetworkDelegate* network_delegate) {
  std::string url = request->url().spec();
  if (url == "nw:version") {
    return new ResourceRequestJob(request,
        network_delegate, "text/html", IDR_NW_VERSION);
  } else if (url == "nw:gpu") {
    return new ResourceRequestJob(request,
        network_delegate, "text/html", IDR_NW_GPU);
  }

  return new ResourceRequestJob(request,
        network_delegate, "text/html", IDR_NW_BLANK);
}

ResourceRequestJob::~ResourceRequestJob() {
}

void ResourceRequestJob::Start() {
  // Start reading asynchronously so that all error reporting and data
  // callbacks happen as they would for network requests.
  MessageLoop::current()->PostTask(
      FROM_HERE,
      base::Bind(&ResourceRequestJob::StartAsync, weak_factory_.GetWeakPtr()));
}

void ResourceRequestJob::DataAvailable(base::RefCountedMemory* bytes) {
  if (bytes) {
    // The request completed, and we have all the data.
    // Clear any IO pending status.
    SetStatus(net::URLRequestStatus());

    data_ = bytes;
    int bytes_read;
    if (pending_buf_.get()) {
      CHECK(pending_buf_->data());
      CompleteRead(pending_buf_, pending_buf_size_, &bytes_read);
      pending_buf_ = NULL;
      NotifyReadComplete(bytes_read);
    }
  } else {
    // The request failed.
    NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED,
                                     net::ERR_FAILED));
  }
}

bool ResourceRequestJob::ReadRawData(net::IOBuffer* buf,
                                     int buf_size, int* bytes_read) {
  if (!data_.get()) {
    SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0));
    DCHECK(!pending_buf_.get());
    CHECK(buf->data());
    pending_buf_ = buf;
    pending_buf_size_ = buf_size;
    return false;  // Tell the caller we're still waiting for data.
  }

  // Otherwise, the data is available.
  CompleteRead(buf, buf_size, bytes_read);
  return true;
}

void ResourceRequestJob::CompleteRead(net::IOBuffer* buf, int buf_size,
                                      int* bytes_read) {
  int remaining = static_cast<int>(data_->size()) - data_offset_;
  if (buf_size > remaining)
    buf_size = remaining;
  if (buf_size > 0) {
    memcpy(buf->data(), data_->front() + data_offset_, buf_size);
    data_offset_ += buf_size;
  }
  *bytes_read = buf_size;
}

bool ResourceRequestJob::GetMimeType(std::string* mime_type) const {
  *mime_type = "text/html";
  return true;
}

void ResourceRequestJob::GetResponseInfo(net::HttpResponseInfo* info) {
  DCHECK(!info->headers);
  info->headers = new net::HttpResponseHeaders("HTTP/1.1 200 OK");
  info->headers->AddHeader("Cache-Control: no-cache");
}

void ResourceRequestJob::StartAsync() {
  if (!request_)
    return;

  NotifyHeadersComplete();
  DataAvailable(ResourceBundle::GetSharedInstance().LoadDataResourceBytes(
      resource_id_));
}

}  // namespace nw


<?xml version="1.0" encoding="UTF-8"?>
<grit latest_public_release="0" current_release="1">
  <outputs>
    <output filename="grit/nw_resources.h" type="rc_header" context="default_100_percent" >
      <emit emit_type='prepend'></emit>
    </output>
    <output filename="grit/nw_resources_map.cc" type="resource_map_source" context="default_100_percent" />
    <output filename="grit/nw_resources_map.h" type="resource_map_header" context="default_100_percent" />
    <output filename="nw_resources.pak" type="data_package" context="default_100_percent" />
  </outputs>
  <translations />
  <release seq="1">
    <structures fallback_to_low_resolution="true">
      <structure type="chrome_scaled_image" name="IDR_NW_DEFAULT_ICON" file="nw.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_BACK" file="browser_back_normal.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_BACK_D" file="browser_back_disabled.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_BACK_H" file="browser_back_hover.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_BACK_P" file="browser_back_pressed.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_FORWARD" file="browser_forward_normal.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_FORWARD_D" file="browser_forward_disabled.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_FORWARD_H" file="browser_forward_hover.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_FORWARD_P" file="browser_forward_pressed.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_STOP" file="browser_stop_normal.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_STOP_D" file="browser_stop_disabled.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_STOP_H" file="browser_stop_hover.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_STOP_P" file="browser_stop_pressed.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_RELOAD" file="browser_reload_normal.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_RELOAD_D" file="browser_reload_disabled.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_RELOAD_H" file="browser_reload_hover.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_RELOAD_P" file="browser_reload_pressed.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_TOOLS" file="browser_tools_normal.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_TOOLS_H" file="browser_tools_hover.png" />
      <structure type="chrome_scaled_image" name="IDR_NW_TOOLS_P" file="browser_tools_pressed.png" />
    </structures>
    <includes>
      <include name="IDR_NW_VERSION" file="pages/nw_version.html" type="BINDATA" />
      <include name="IDR_NW_BLANK" file="pages/nw_blank.html" type="BINDATA" />
      <include name="IDR_NW_PACKAGE_ERROR" file="pages/package_error.html" type="BINDATA" />
      <include name="IDR_NW_FATAL_ERROR" file="pages/fatal_error.html" type="BINDATA" />
      <include name="IDR_NW_GPU" file="pages/nw_gpu.html" type="BINDATA" />
      <include name="IDR_NW_DEVTOOLS_DISCOVERY_PAGE" file="pages/shell_devtools_discovery_page.html" type="BINDATA" />
      <include name="IDR_NW_API_DISPATCHER_BINDINGS_JS" file="../api/dispatcher_bindings.js" type="BINDATA" />
      <include name="IDR_NW_API_WINDOW_BINDINGS_JS" file="../api/window_bindings.js" type="BINDATA" />
      <include name="IDR_NW_API_BASE_JS" file="../api/base/base.js" type="BINDATA" />
      <include name="IDR_NW_API_MENUITEM_JS" file="../api/menuitem/menuitem.js" type="BINDATA" />
      <include name="IDR_NW_API_MENU_JS" file="../api/menu/menu.js" type="BINDATA" />
      <include name="IDR_NW_API_TRAY_JS" file="../api/tray/tray.js" type="BINDATA" />
      <include name="IDR_NW_API_CLIPBOARD_JS" file="../api/clipboard/clipboard.js" type="BINDATA" />
      <include name="IDR_NW_API_WINDOW_JS" file="../api/window/window.js" type="BINDATA" />
      <include name="IDR_NW_API_SHELL_JS" file="../api/shell/shell.js" type="BINDATA" />
      <include name="IDR_NW_API_APP_JS" file="../api/app/app.js" type="BINDATA" />
      <if expr="pp_ifdef('enable_printing')">
        <include name="IDR_PRINT_PREVIEW_PAGE" file="pages/print_preview_page.html" flattenhtml="true" allowexternalscript="false" type="BINDATA" />
      </if>
    </includes>
    <messages fallback_to_english="true">
      <message name="IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS" desc="Message to display when selected printer is not reachable or its settings are invalid.">
        The selected printer is not available or not installed correctly.  Check your printer or try selecting another printer.
      </message>
      <!-- Print -->
      <message name="IDS_DEFAULT_PRINT_DOCUMENT_TITLE" desc="Default title for a print document">
        Untitled Document
      </message>
      <message name="IDS_PRINT_SPOOL_FAILED_TITLE_TEXT" desc="Title of a message box when printing fails because of printer issues.">
        Print Failed
      </message>
      <message name="IDS_PRINT_SPOOL_FAILED_ERROR_TEXT" desc="Text in a messagebox when printing fails because of printer issues.">
        Something went wrong when trying to print.  Please check your printer and try again.
      </message>
    </messages>
  </release>
</grit>


## Introduction

node-webkit is an app runtime based on `Chromium` and `node.js`. You can
write native apps in HTML and Javascript with node-webkit. It also lets you
to call Node.js modules directly from DOM and enables a new way of writing
native applications with all Web technologies.

It's created and developed in Intel Open Source Technology Center.

[Introduction to node-webkit (slides)](https://speakerdeck.com/u/zcbenz/p/node-webkit-app-runtime-based-on-chromium-and-node-dot-js).

## Features

* Apps written in modern HTML5, CSS3, JS and WebGL.
* Complete support for [Node.js APIs](http://nodejs.org/api/) and all its [third party modules](https://npmjs.org).
* Good performance: Node and WebKit runs in the same thread: Function calls are made straightforward; objects are in the same heap and can just reference each other;
* Easy to package and distribute apps.
* Available on Linux, Mac OSX and Windows

## Downloads

[v0.4.2 release note](https://groups.google.com/d/msg/node-webkit/Fq5Mio4k2xw/McGDIUs-oSMJ)

Prebuilt binaries (v0.4.2 — Feb 21, 2013):

* Linux: [32bit](https://s3.amazonaws.com/node-webkit/v0.4.2/node-webkit-v0.4.2-linux-ia32.tar.gz) / [64bit](https://s3.amazonaws.com/node-webkit/v0.4.2/node-webkit-v0.4.2-linux-x64.tar.gz)
* Windows: [win32](https://s3.amazonaws.com/node-webkit/v0.4.2/node-webkit-v0.4.2-win-ia32.zip)
* Mac: [32bit, 10.7+](https://s3.amazonaws.com/node-webkit/v0.4.2/node-webkit-v0.4.2-osx-ia32.zip)

[Looking for older versions?](https://github.com/rogerwang/node-webkit/wiki/Downloads-of-old-versions)

###Demos and real apps
You may also be interested in [our demos repository](https://github.com/zcbenz/nw-sample-apps) and the [List of apps and companies using node-webkit](https://github.com/rogerwang/node-webkit/wiki/List-of-apps-and-companies-using-node-webkit).

## Quick Start

Create `index.html`:

````html
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using node.js <script>document.write(process.version)</script>
</body>
</html>
````

Create `package.json`:

````json
{
  "name": "nw-demo",
  "main": "index.html"
}
````

Compress `index.html` and `package.json` into a zip archive, and rename
it to `app.nw`:

    app.nw
    |-- package.json
    `-- index.html

Download the prebuilt binary for your platform and use it to open the
`app.nw` file:

````bash
$ ./nw app.nw
````

Note: on Windows, you can drag the `app.nw` to `nw.exe` to open it.

## Documents

For more information on how to write/package/run apps, see:

* [How to run apps](https://github.com/rogerwang/node-webkit/wiki/How-to-run-apps)
* [How to package and distribute your apps](https://github.com/rogerwang/node-webkit/wiki/How-to-package-and-distribute-your-apps)
* [How to use 3rd party node.js modules in node-webkit](https://github.com/rogerwang/node-webkit/wiki/How-to-use-3rd-party-node.js-modules-in-node-webkit)

And our [Wiki](https://github.com/rogerwang/node-webkit/wiki) for much more.

## Community

We use [node-webkit group](http://groups.google.com/group/node-webkit) as
our mailing list, subscribe via [node-webkit+subscribe@googlegroups.com](mailto:node-webkit+subscribe@googlegroups.com).

## License

`node-webkit`'s code uses the MIT license, see our `LICENSE` file.


// Must be created after the NotificationService.


// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "content/nw/src/shell_browser_main.h"

#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/threading/thread_restrictions.h"
#include "content/public/common/content_switches.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/nw_shell.h"
#include "content/nw/src/shell_browser_context.h"
#include "content/nw/src/shell_content_browser_client.h"

// Main routine for running as the Browser process.
int ShellBrowserMain(const content::MainFunctionParams& parameters) {
  scoped_ptr<content::BrowserMainRunner> main_runner_(
      content::BrowserMainRunner::Create());

  int exit_code = main_runner_->Initialize(parameters);

  if (exit_code >= 0)
    return exit_code;

  main_runner_->Run();

  main_runner_->Shutdown();

  return content::Shell::exit_code();
}


// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "content/nw/src/browser/chrome_event_processing_window.h"

#include "base/logging.h"
#import "content/public/browser/render_widget_host_view_mac_base.h"

@interface ChromeEventProcessingWindow ()
// Duplicate the given key event, but changing the associated window.
- (NSEvent*)keyEventForWindow:(NSWindow*)window fromKeyEvent:(NSEvent*)event;
@end

@implementation ChromeEventProcessingWindow

- (BOOL)redispatchKeyEvent:(NSEvent*)event {
  DCHECK(event);
  NSEventType eventType = [event type];
  if (eventType != NSKeyDown &&
      eventType != NSKeyUp &&
      eventType != NSFlagsChanged) {
    NOTREACHED();
    return YES;  // Pretend it's been handled in an effort to limit damage.
  }

  // Ordinarily, the event's window should be this window. However, when
  // switching between normal and fullscreen mode, we switch out the window, and
  // the event's window might be the previous window (or even an earlier one if
  // the renderer is running slowly and several mode switches occur). In this
  // rare case, we synthesize a new key event so that its associate window
  // (number) is our own.
  if ([event window] != self)
    event = [self keyEventForWindow:self fromKeyEvent:event];

  // Redispatch the event.
  eventHandled_ = YES;
  redispatchingEvent_ = YES;
  [NSApp sendEvent:event];
  redispatchingEvent_ = NO;

  // If the event was not handled by [NSApp sendEvent:], the sendEvent:
  // method below will be called, and because |redispatchingEvent_| is YES,
  // |eventHandled_| will be set to NO.
  return eventHandled_;
}

- (void)sendEvent:(NSEvent*)event {
  if (!redispatchingEvent_)
    [super sendEvent:event];
  else
    eventHandled_ = NO;
}

- (NSEvent*)keyEventForWindow:(NSWindow*)window fromKeyEvent:(NSEvent*)event {
  NSEventType eventType = [event type];

  // Convert the event's location from the original window's coordinates into
  // our own.
  NSPoint eventLoc = [event locationInWindow];
  eventLoc = [[event window] convertBaseToScreen:eventLoc];
  eventLoc = [self convertScreenToBase:eventLoc];

  // Various things *only* apply to key down/up.
  BOOL eventIsARepeat = NO;
  NSString* eventCharacters = nil;
  NSString* eventUnmodCharacters = nil;
  if (eventType == NSKeyDown || eventType == NSKeyUp) {
    eventIsARepeat = [event isARepeat];
    eventCharacters = [event characters];
    eventUnmodCharacters = [event charactersIgnoringModifiers];
  }

  // This synthesis may be slightly imperfect: we provide nil for the context,
  // since I (viettrungluu) am sceptical that putting in the original context
  // (if one is given) is valid.
  return [NSEvent keyEventWithType:eventType
                          location:eventLoc
                     modifierFlags:[event modifierFlags]
                         timestamp:[event timestamp]
                      windowNumber:[window windowNumber]
                           context:nil
                        characters:eventCharacters
       charactersIgnoringModifiers:eventUnmodCharacters
                         isARepeat:eventIsARepeat
                           keyCode:[event keyCode]];
}

- (BOOL)performKeyEquivalent:(NSEvent*)event {
  if (redispatchingEvent_)
    return NO;

  // Give the web site a chance to handle the event. If it doesn't want to
  // handle it, it will call us back with one of the |handle*| methods above.
  NSResponder* r = [self firstResponder];
  if ([r conformsToProtocol:@protocol(RenderWidgetHostViewMacBase)])
    return [r performKeyEquivalent:event];

  if ([super performKeyEquivalent:event])
    return YES;

  return NO;
}

@end  // ChromeEventProcessingWindow


// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

namespace base {
class DictionaryValue;
}

namespace content {
class Shell;
}

namespace nw {

class NativeWindow;

NativeWindow* CreateNativeWindowCocoa(content::Shell* shell,
                                      base::DictionaryValue* manifest);

}  // namespace nw


// print_job_manager_ is initialized in the constructor and destroyed in the

// destructor, so it should always be valid.

// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_
#define CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_

#include <string>
#include <map>

#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/web_contents_view.h"

namespace printing {
class PrintJobManager;
}

namespace content {

class ShellBrowserContext;
class ShellBrowserMainParts;
class ShellResourceDispatcherHostDelegate;

class ShellContentBrowserClient : public ContentBrowserClient {
 public:
  ShellContentBrowserClient();
  virtual ~ShellContentBrowserClient();

  // ContentBrowserClient overrides.
  virtual BrowserMainParts* CreateBrowserMainParts(
      const MainFunctionParams& parameters) OVERRIDE;
  virtual void RenderViewHostCreated(
      RenderViewHost* render_view_host) OVERRIDE;
  virtual WebContentsViewPort* OverrideCreateWebContentsView(
      WebContents* web_contents,
      RenderViewHostDelegateView** render_view_host_delegate_view) OVERRIDE;
  virtual std::string GetApplicationLocale() OVERRIDE;
  virtual void AppendExtraCommandLineSwitches(CommandLine* command_line,
                                              int child_process_id) OVERRIDE;
  virtual void ResourceDispatcherHostCreated() OVERRIDE;
  virtual AccessTokenStore* CreateAccessTokenStore() OVERRIDE;
  virtual void OverrideWebkitPrefs(
      RenderViewHost* render_view_host,
      const GURL& url,
      webkit_glue::WebPreferences* prefs) OVERRIDE;
  virtual std::string GetDefaultDownloadName() OVERRIDE;
  virtual MediaObserver* GetMediaObserver() OVERRIDE;
  virtual void BrowserURLHandlerCreated(BrowserURLHandler* handler) OVERRIDE;
  virtual bool ShouldTryToUseExistingProcessHost(
      BrowserContext* browser_context, const GURL& url) OVERRIDE;
  virtual bool IsSuitableHost(RenderProcessHost* process_host,
                              const GURL& site_url) OVERRIDE;
  ShellBrowserContext* browser_context();
  ShellBrowserContext* off_the_record_browser_context();
  ShellResourceDispatcherHostDelegate* resource_dispatcher_host_delegate() {
    return resource_dispatcher_host_delegate_.get();
  }
  ShellBrowserMainParts* shell_browser_main_parts() {
    return shell_browser_main_parts_;
  }
  virtual printing::PrintJobManager* print_job_manager();
  virtual void RenderProcessHostCreated(RenderProcessHost* host) OVERRIDE;
  virtual net::URLRequestContextGetter* CreateRequestContext(
      BrowserContext* browser_context,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          blob_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          file_system_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          developer_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          chrome_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          chrome_devtools_protocol_handler) OVERRIDE;
  virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition(
      BrowserContext* browser_context,
      const base::FilePath& partition_path,
      bool in_memory,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          blob_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          file_system_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          developer_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          chrome_protocol_handler,
      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>
          chrome_devtools_protocol_handler) OVERRIDE;

 private:
  ShellBrowserContext* ShellBrowserContextForBrowserContext(
      BrowserContext* content_browser_context);
  scoped_ptr<ShellResourceDispatcherHostDelegate>
      resource_dispatcher_host_delegate_;

  ShellBrowserMainParts* shell_browser_main_parts_;
  // Ensures that all the print jobs are finished before closing the browser.
  scoped_ptr<printing::PrintJobManager> print_job_manager_;
};

}  // namespace content

#endif  // CONTENT_SHELL_SHELL_CONTENT_BROWSER_CLIENT_H_


// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef CONTENT_NW_SRC_BROWSER_SHELL_TOOLBAR_DELEGATE_MAC_H_
#define CONTENT_NW_SRC_BROWSER_SHELL_TOOLBAR_DELEGATE_MAC_H_

#import <Cocoa/Cocoa.h>

#include "content/nw/src/browser/native_window.h"

namespace content {
class Shell;
}

@interface ShellToolbarDelegate : NSObject<NSToolbarDelegate> {
 @private
  content::Shell* shell_;
  NSTextField* entry_;
  NSToolbarItem* back_button_;
  NSToolbarItem* forward_button_;
  NSToolbarItem* refresh_stop_button_;
  NSToolbarItem* devtools_button_;
  NSToolbarItem* refresh_dev_button_;
}

- (id)initWithShell:(content::Shell*)shell;
- (void)buttonPressed:(id)sender;
- (void)urlEntered:(id)sender;
- (void)setEnabled:(BOOL)enabled
         forButton:(nw::NativeWindow::TOOLBAR_BUTTON)button;
- (void)setUrl:(NSString*)url;
- (void)setIsLoading:(BOOL)loading;

- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar
     itemForItemIdentifier:(NSString *)itemIdentifier
 willBeInsertedIntoToolbar:(BOOL)flag;
- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar;
- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar;
@end

#endif  // CONTENT_NW_SRC_BROWSER_SHELL_TOOLBAR_DELEGATE_MAC_H_


// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "content/nw/src/browser/shell_download_manager_delegate.h"

#include <AppKit/NSSavePanel.h>
#include <Foundation/NSURL.h>

#include "base/bind.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "net/base/net_util.h"

using base::FilePath;

namespace content {

void ShellDownloadManagerDelegate::ChooseDownloadPath(
    int32 download_id,
    const DownloadTargetCallback& callback,
    const FilePath& suggested_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DownloadItem* item = download_manager_->GetDownload(download_id);
  if (!item || (item->GetState() != DownloadItem::IN_PROGRESS))
    return;

  FilePath result;
  std::string base_name = FilePath(suggested_path).BaseName().value();

  NSSavePanel *savePanel = [NSSavePanel savePanel];

  [savePanel setNameFieldStringValue:[NSString stringWithUTF8String:base_name.c_str()]];

  if ([savePanel runModal] == NSFileHandlingPanelOKButton) {
    char *filename = (char *)[[[savePanel URL] path] UTF8String];

    result = FilePath(filename);
  }

  callback.Run(result, DownloadItem::TARGET_DISPOSITION_PROMPT,
               DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, result);
}
}  // namespace content


var path = require('path');
var app_test = require('./nw_test_app');

describe('Plugin', function() {
  describe('flash', function(){
    it('should not crash', function(done) {
      var result = false;

      var child = app_test.createChildProcess({
        execPath: process.execPath,
        appPath: path.join('app_tests', 'plugin', 'flash'),
        end: function(data, app) {
          done();
          result = true;
          app.kill();
        }
      });

      setTimeout(function(){
        if (!result) {
          done('nw crash.');
          child.removeConnection();
        }
      }, 1000);

    })
  })
})


class CommandLine;
class FilePath;
namespace content {
class ShellBrowserContext;

namespace printing {
class PrintJobManager;
}


// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

var argv, fullArgv;

function App() {
}
require('util').inherits(App, exports.Base);

App.filteredArgv = [
  /--no-toolbar/,
  /--url=.*/,
  /--remote-debugging-port=.*/,
  /--renderer-cmd-prefix.*/,
];

App.prototype.quit = function() {
  nw.callStaticMethod('App', 'Quit', [ ]);
}

App.prototype.closeAllWindows = function() {
  nw.callStaticMethod('App', 'CloseAllWindows', [ ]);
}

App.prototype.__defineGetter__('argv', function() {
  if (!argv) {
    var fullArgv = this.fullArgv;
    argv = [];
    for (var i = 0; i < fullArgv.length; ++i) {
      var matched = false;
      for (var j = 0; j < App.filteredArgv.length; ++j) {
        if (App.filteredArgv[j].test(fullArgv[i])) {
          matched = true;
          break;;
        }
      }
      if (matched)
        continue;

      argv.push(fullArgv[i]);
    }
  }

  return argv;
});

App.prototype.__defineGetter__('fullArgv', function() {
  if (!fullArgv)
    fullArgv = nw.callStaticMethodSync('App', 'GetArgv', [ ]);

  return fullArgv;
});

// Store App object in node's context.
if (process['_nw_app']) {
  exports.App = process['_nw_app'];
} else {
  exports.App = process['_nw_app'] = new App();
}


exports.test = function() {
  return "module2";
}


nw::Package* package() { return package_.get(); }

bool ProcessSingletonNotificationCallback(const CommandLine& command_line,


// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "content/nw/src/api/menu/menu.h"

#include "base/values.h"
#include "content/nw/src/api/dispatcher_host.h"
#include "content/nw/src/api/menuitem/menuitem.h"
#include "content/nw/src/nw_shell.h"

namespace api {

Menu::Menu(int id,
           DispatcherHost* dispatcher_host,
           const base::DictionaryValue& option)
    : Base(id, dispatcher_host, option) {
  Create(option);
}

Menu::~Menu() {
  Destroy();
}

void Menu::Call(const std::string& method,
                const base::ListValue& arguments) {
  if (method == "Append") {
    int object_id = 0;
    arguments.GetInteger(0, &object_id);
    Append(dispatcher_host()->GetApiObject<MenuItem>(object_id));
  } else if (method == "Insert") {
    int object_id = 0;
    arguments.GetInteger(0, &object_id);
    int pos = 0;
    arguments.GetInteger(1, &pos);
    Insert(dispatcher_host()->GetApiObject<MenuItem>(object_id), pos);
  } else if (method == "Remove") {
    int object_id = 0;
    arguments.GetInteger(0, &object_id);
    int pos = 0;
    arguments.GetInteger(1, &pos);
    Remove(dispatcher_host()->GetApiObject<MenuItem>(object_id), pos);
  } else if (method == "Popup") {
    int x = 0;
    arguments.GetInteger(0, &x);
    int y = 0;
    arguments.GetInteger(1, &y);
    Popup(x, y, content::Shell::FromRenderViewHost(
          dispatcher_host()->render_view_host()));
  } else {
    NOTREACHED() << "Invalid call to Menu method:" << method
                 << " arguments:" << arguments;
  }
}

}  // namespace api