UNPKG

jive-sdk

Version:

Node.js SDK for Jive Software to assist with the development of add-ons

1 lines 34.6 kB
function ImageProcessor(){var e=90,t=90,n=0,r=function(e,t,n,r){var i,s=0,o=n/e,u=r/t;return o>u?(s=r/o,i=e):(i=n/u,s=t),{width:i,height:s}},i=function(e,t){var n=[];return e>t?(n[0]=e-t,n[1]=0):(n[0]=0,n[1]=t-e),n},s=function(n){var r=n.getImageData(0,0,e,t),i=r.data;for(var s=0,o=i.length;s<o;s+=4){var u=i[s]*.3+i[s+1]*.59+i[s+2]*.11;i[s]=u,i[s+1]=u,i[s+2]=u}n.putImageData(r,0,0)},o=function(n,r,i){var s,o,u,a=4;n.globalAlpha=.1;for(s=1;s<=a;s++)for(u=-a/2;u<=a/2;u++)for(o=-a/2;o<=a/2;o++)n.drawImage(r,i[0]/2,i[1]/2,r.width-i[0],r.height-i[1],o,u,e,t);n.globalAlpha=1},u=function(e,t){var n=e.getImageData(0,0,e.canvas.width,e.canvas.height),r=n.data,i=1-t,s=Math.round(e.canvas.width*3.73),o=new Array(s);for(var u=0;u<s;u++)o[u]=Math.random()*t+i;for(var u=0,a=r.length;u<a;u+=4)r[u]=r[u]*o[u%s]|0;e.putImageData(n,0,0)},a=function(e,t,n,r,u){var a=document.createElement("canvas");a.width=t,a.height=n;var f=a.getContext("2d"),l=[0,0];return u=="crop"&&(l=i(e.width,e.height)),f.drawImage(e,l[0]/2,l[1]/2,e.width-l[0],e.height-l[1],0,0,t,n),r=="grayscale"?s(f):r=="blurry"&&o(f,e,l),a.toDataURL("image/jpeg",.95)},f=function(e){var t=$("input[name=effect]:checked").val(),n=$("input[name=croping]:checked").val(),i=r(90,90,e.width,e.height);return{width:i.width,height:i.height,url:a(e,i.width,i.height,t,n)}},l=function(e){var t=$("input[name=effect]:checked").val(),n=$("input[name=croping]:checked").val(),i=r(350,350,e.width,e.height);return{width:i.width,height:i.height,url:a(e,i.width,i.height,t,n)}},c=function(e){var t=e?e:1e6;return Math.floor(Math.random()*t)},h=function(e){return(e/1024).toFixed(1)},p=function(e){var t=window.WebKitBlobBuilder||window.MozBlobBuilder||window.BlobBuilder;if(typeof t=="undefined")return $("#err").html("Ops! There have some limited with your browser! <br/>New image produced from canvas can't be upload to the server..."),e;var n;e.split(",")[0].indexOf("base64")>=0?n=atob(e.split(",")[1]):n=unescape(e.split(",")[1]);var r=e.split(",")[0].split(":")[1].split(";")[0],i=new ArrayBuffer(n.length),s=new Uint8Array(i);for(var o=0;o<n.length;o++)s[o]=n.charCodeAt(o);var u=new t;return u.append(i),u.getBlob(r)},d=function(e,t,n){return $("<img/>").load(function(){var t=f(this),r=l(this);console.log(t,r);var i={};i.imageId=c(),i.thumbSrc=t.url,i.fullSrc=r.url,i.imageWidth=r.width,i.imageHeight=r.height,i.fileName=e.substr(0,e.lastIndexOf(".")),n&&n(i)}).attr("src",t)},v=function(e,t,n,r){if(/image/i.test(e.type)){var i=new FileReader;t(e),i.onload=function(t){$("<img/>").load(function(){var t=f(this),r=l(this);console.log(t,r);var i={};i.imageId=c(),i.thumbSrc=t.url,i.fullSrc=r.url,i.imageWidth=r.width,i.imageHeight=r.height,i.fileName=e.name.substr(0,e.name.lastIndexOf(".")),i.fileOriSize=h(e.size),i.fileUploadSize=h(p(t.url).size),n(e,i)}).attr("src",t.target.result)},i.readAsDataURL(e)}else r(e,"*Selected file format not supported!")};return{readFile:v,buildImage:d}}function Container(){return{mostRecentSize:{width:0,height:0},props:{},appContext:{},getValue:function(e,t){return!e||!e[t]?null:_.isFunction(e[t])?e[t]():e[t]},sync:function(e,t,n){if(t.useAppData){if(!n.data&&t&&(e=="create"||e=="update")){var r=t.toJSON(),i=t.appDataKey(),s={};s[i]=JSON.stringify(r),osapi.appdata.update({data:s,userId:"@me",escapeType:opensocial.EscapeType.NONE}).execute(function(e){e.error?(console.log("update error",e.error),n.error&&n.error(e.error)):(console.log("update response",e),t.set("id",i),n.postSuccess&&n.postSuccess(t),t.trigger("saved"))})}else if(e=="read"){var o={userId:"@me",fields:t.appDataFields(),escapeType:opensocial.EscapeType.NONE};osapi.appdata.get(o).execute(function(e){e.error?(console.log("fetch error",e.error),n.error&&n.error(e.error)):(t.parse(e),n.postSuccess&&n.postSuccess(t))})}else if(e=="delete"){var o={keys:t.appDataFields(),userId:"@me"};console.log("to remove",o),osapi.appdata["delete"](o).execute(function(e){e.error?(console.log("delete error",e.error),n.error&&n.error(e.error)):(n.postSuccess&&n.postSuccess(t),t.trigger("deleted"))})}}else{var u=gadgets.util.getUrlParameters().url;u=u.substring(0,u.lastIndexOf("/"));var a=u+this.getValue(t,"url")+"?ts="+(new Date).getTime(),o={href:a,format:"json",authz:null};t.headers&&(o.headers=this.getValue(t,"headers")),o.callback=function(e){if(e.status==200||e.status==204)t.parse(e.content),n.postSuccess&&n.postSuccess(t,e);else{var r;e.content&&e.content.jiveFault?r=e.content:r={jiveFault:{stackTrace:"",errorMessage:e.status,errorCode:"UNKNOWN_ERROR",requestId:"",blocking:!1}},n.error(t,r)}},e=="read"&&t.postForRead||e=="create"?osapi.http.post(o).execute(o.callback):e=="read"?osapi.http.get(o).execute(o.callback):alert("Unsupported method")}},loadExperience:function(){var e=this;$.get(gadgets.io.getProxyUrl(gadgets.util.getUrlParameters().url.replace(/(\/app.xml)|(\/gadget.xml)/,"/templates.html"))+"&nocache=1",function(t){e.$templates=$(t),$("body").append(t);var n=e.appContext.defaultRoute||"main";Backbone.history.navigate(n,!0)})},getTemplate:function(e){return this.$templates.filter(e).html()},httpPost:function(e){var t=gadgets.util.getUrlParameters().url;t=t.substring(0,t.lastIndexOf("/"));var n={href:t+this.getValue(e,"url"),format:"json",authz:"signed"};e.headers&&(n.headers=this.getValue(e,"headers")),e.data&&(n.body=JSON.stringify(this.getValue(e,"data"))),osapi.http.post(n).execute(function(t){if(t.status==200||t.status==204)e.success(t.content);else{var n;t.content&&t.content.jiveFault?n=t.content:n={jiveFault:{stackTrace:"",errorMessage:t.status,errorCode:"UNKNOWN_ERROR",requestId:"",blocking:!1}},e.error&&e.error(n)}})},httpGet:function(e){var t=gadgets.util.getUrlParameters().url;t=t.substring(0,t.lastIndexOf("/"));var n={href:t+this.getValue(e,"url"),format:"json",authz:"signed"};e.headers&&(n.headers=this.getValue(e,"headers")),osapi.http.get(n).execute(function(t){if(t.status==200||t.status==204)e.success(t.content);else{var n;t.content&&t.content.jiveFault?n=t.content:n={jiveFault:{stackTrace:"",errorMessage:t.status,errorCode:"UNKNOWN_ERROR",requestId:"",blocking:!1}},e.error&&e.error(n)}})},getProxyUrl:function(e){return gadgets.io.getProxyUrl(e)+"&nocache="+gadgets.util.getUrlParameters().nocache},close:function(e){e?osapi.jive.core.container.closeApp({data:{events:e}}):osapi.jive.core.container.closeApp()},getViewerId:function(){return opensocial.data.getDataContext().getDataSet("sbsContext").user.userID},adjustSize:function(){this.adjustWidth(),this.adjustHeight()},adjustWidth:function(e){gadgets.window.adjustWidth&&gadgets.window.adjustWidth(e)},adjustHeight:function(e){gadgets.window.adjustHeight&&gadgets.window.adjustHeight(e)},windowWidthHasChanged:function(e){var t=parseInt(e||gadgets.window.getWidth(),0);return t==this.mostRecentSize.width?!1:(this.mostRecentSize.width=t,!0)},windowHeightHasChanged:function(e){var t=parseInt(e||gadgets.window.getHeight(),0);return t==this.mostRecentSize.height?!1:(this.mostRecentSize.height=t,!0)},getUser:function(e,t){osapi.people.get({userId:e}).execute(t)},setProps:function(e){this.props=e},getProps:function(){return this.props},setAppContext:function(e){e&&(this.appContext=e)},getAppContext:function(){return this.appContext}}}function Router(){var e={main:"showMain","gallery-create":"galleryCreate","gallery-edit/:id":"galleryEdit","gallery-edit-cancel":"galleryEditCancel","gallery-delete/:id":"galleryDelete","gallery-drop/:id":"galleryDrop","gallery-select/:id":"galleryDrop","gallery-view/:id":"galleryView","gallery-saved/:id":"gallerySaved",close:"close","*actions":"defaultAction"},t,n=Backbone.Router.extend({showMain:function(){this.galleryList()},galleryList:function(){this.galleryListController.galleryList()},galleryCreate:function(){this.galleryController.galleryCreate()},galleryEdit:function(e){this.galleryController.galleryEdit(e)},galleryEditCancel:function(e){this.showMain()},galleryDelete:function(e){this.galleryController.galleryDelete(e)},gallerySaved:function(e){this.showMain()},galleryDrop:function(e){this.galleryController.galleryDrop(e)},galleryView:function(e){this.galleryController.galleryView(e)},close:function(){osapi.jive.core.container.closeApp()},defaultAction:function(){t.loadExperience()}}),r=function(r){var i=e;t=r;var s=t.getAppContext();if(s){var o=s.routes;if(o)for(var u in o)if(o.hasOwnProperty(u)){var a=o[u];a&&(i[u]=a)}}var f=new n({routes:i}),l=new ViewManager;f.galleryListController=new GalleryListController(t,l),f.galleryController=new GalleryController(t,l),Backbone.history.start()};return{initialize:r}}function App(){var e=new Container,t=function(t){t&&e.setAppContext(t),e.initialize&&e.initialize();var n=new Router;n.initialize(e)};return Backbone.sync=function(t,n,r){e.sync(t,n,r)},Backbone.View.prototype.close=function(){this.remove(),this.unbind(),this.onClose&&this.onClose()},{initialize:t,getAbsoluteUrl:function(e){return gadgets.util.getUrlParameters().url.replace(/(\/app.xml)|(\/gadget.xml)/,e)},getProxiedUrl:function(e){return gadgets.io.getProxyUrl(gadgets.util.getUrlParameters().url.replace(/(\/app.xml)|(\/gadget.xml)/,e))+"&nocache=1"}}}function ViewManager(){return{showView:function(e){if(!this.currentView||e!=this.currentView)this.currentView&&this.currentView.close(),this.currentView=e,$("#main-content").html(this.currentView.el)}}}window.GalleryList=Backbone.Model.extend({defaults:{galleryIDs:[]},useAppData:!0,appDataKey:function(){return"gallery_list"},appDataFields:function(){return["gallery_list"]},initialize:function(){},parse:function(e){for(var t in e)for(var n in e[t])if(n&&n.indexOf("gallery_list")==0){var e=JSON.parse(e[t][n]);this.set("galleryIDs",e.galleryIDs)}for(var r in e)this.set(r,e[r]);this.trigger("parsed",this.get("galleryIDs"))},add:function(e){var t=this.get("galleryIDs");console.log("current",t),$.inArray(e,t)<0&&t.push(e),console.log("after",t)},subtract:function(e){var t=this.get("galleryIDs");t.splice(t.indexOf(e),1)}}),window.GalleryModel=Backbone.Model.extend({defaults:{title:"",imgIDs:"",preview:"",created:0,parentList:null},useAppData:!0,appDataKey:function(){if(this.isNew()){var e=(new Date).getTime();return $.trim("gallery_"+e)}return this.get("id")},appDataFields:function(){return[this.get("id")]},initialize:function(){},parse:function(e){for(var t in e)for(var n in e[t])if(n&&n.indexOf("gallery_")==0){var e=JSON.parse(e[t][n]);this.set("id",n),this.set("title",e.title),this.set("imageIDs",e.imageIDs),this.set("preview",e.preview),this.set("created",e.created)}for(var r in e)this.set(r,e[r]);this.trigger("parsed",this)},save:function(e,t,n){this.isNew()&&this.set("created",(new Date).getTime()),Backbone.Model.prototype.save.call(this,e,t,n)},destroy:function(e,t){var n=this.get("imgIDs")==""?[]:this.get("imgIDs");$.each(n,function(e,t){var n={imageId:t},r=new GalleryEntry;r.destroy(n,function(){console.log("Destroyed image '"+t+"' in GalleryModel.destroy")})}),Backbone.Model.prototype.destroy.call(this)}}),window.GalleryEntry=Backbone.Model.extend({initialize:function(){},fetch:function(){this.fetchThumb(),this.fetchSource()},fetchThumb:function(e){var t=this.get("id"),n=new GalleryImage({id:"thumb_"+t}),r=this;n.bind("parsed",function(t){r.trigger("fetchedThumbnail",t),e&&e(t)}),n.fetch()},fetchSource:function(e){var t=this.get("id"),n=new GalleryImage({id:"image_"+t}),r=this;n.bind("parsed",function(t){r.trigger("fetchedFullSource",t),e&&e(t)}),n.fetch()},save:function(e,t){var n=new GalleryImage;n.set({id:"thumb_"+e.imageId,src:e.previewSrc,width:e.width,height:e.height});var r=function(){var n=new GalleryImage;n.set({id:"image_"+e.imageId,src:e.fullSrc,width:e.width,height:e.height}),n.bind("saved",function(){t(e.imageId)}),n.save()};n.bind("saved",r),n.save()},destroy:function(e,t){var n=new GalleryImage;n.set({id:"thumb_"+e.imageId,src:e.previewSrc,width:e.width,height:e.height});var r=new GalleryImage;r.set({id:"image_"+e.imageId,src:e.fullSrc,width:e.width,height:e.height});var i=function(){r.destroy()};n.bind("destroy",i),r.bind("saved",function(){t(e.imageId)}),n.destroy()}}),window.GalleryImage=Backbone.Model.extend({defaults:{width:"",height:0,src:"",created:0},useAppData:!0,appDataKey:function(){return this.get("id")},getImageKey:function(){return this.get("id")},appDataFields:function(){return[this.get("id")]},initialize:function(){},parse:function(e){for(var t in e)for(var n in e[t])if(n&&n.indexOf(this.getImageKey())==0){var e=JSON.parse(e[t][n]);this.set("id",n),this.set("width",e.width),this.set("height",e.height),this.set("src",e.src),this.set("created",e.created)}for(var r in e)this.set(r,e[r]);this.trigger("parsed",this)},save:function(e,t,n){this.isNew()&&this.set("created",(new Date).getTime()),Backbone.Model.prototype.save.call(this,e,t,n)},destroy:function(e,t,n){Backbone.Model.prototype.destroy.call(this,e,t,n)}}),window.GalleryPreviewView=function(){function e(e,t){var n=_args().url,r=n.replace(/[a-zA-Z0-9_]+\.xml(\?.*)?/,"");return t?gadgets.io.getProxyUrl(r+e):r+e}return Backbone.View.extend({events:{},generatePreview:function(t,n,r){function i(t,n,r,i){var s=new Image;s.src=e("images/play-graphic.png",!0);var o=new Image;o.src=e("images/background_wood.jpg",!0);var u=new Image;u.src=$(t).attr("src");var a=u.width,f=u.height;u=null;var l=i==1?240:180,c=240,h,p,d=a/f;f>a?(p=l,h=p*d):(h=c,p=h*1/d);if(p>l){var v=l/p;p*=v,h*=v}var m=c-h,g=l-p,y=40,b=10,w=13,E=50,S=50,x=Math.max(y+b,p+g/2-y+b),T=$("<canvas></canvas>")[0],N=$("<canvas></canvas>")[0],C=$("<canvas></canvas>")[0];T.width=c+2*b,T.height=T.width,N.width=c,N.height=S,C.width=c,C.height=y;var k=T.getContext("2d");k.drawImage(o,0,0,T.width,T.height);var L=N.getContext("2d"),A=0;n.each(function(e,t){e<=3&&(L.drawImage(t,A,0,E,S),A+=E+w)});var O=L.getImageData(0,0,N.width,N.height);k.putImageData(O,b,b+l+b),k.globalAlpha=.8,k.drawImage(t,b+m/2,b+g/2,h,p),k.globalAlpha=.4,k.fillStyle="black",k.fillRect(b,x,c,y);var M=20,_=!1,D=r.length;r.length>M&&(_=!0),r=r.slice(0,Math.min(M,r.length));if(_)r+="...";else{for(var P=0;P<M-D;P++)r+=" ";r+=" "}r+=" ("+i+")";var H=14;return k.globalAlpha=1,k.font=H+"px Georgia",k.fillStyle="#ffffff",k.fillText(r,b*2,x+y/2+H/2),T.toDataURL("image/jpeg")}var s=t.find("img").first();return i(s[0],t.find("img").slice(1),n,r)},generateListEntry:function(e){function t(e){var t=new Image;t.src=$(e).attr("src");var n=t.width,r=t.height;t=null;var i=120,s=120,o,u,a=n/r;r>n?(u=i,o=u*a):(o=s,u=o/a);if(u>i){var f=i/u;u*=f,o*=f}var l=s-o,c=i-u,h=10,p=$("<canvas></canvas>")[0];p.width=s+2*h,p.height=p.width;var d=$("<canvas></canvas>")[0];d.width=s+2*h,d.height=d.width;var v=i*.05,m=d.getContext("2d");m.globalAlpha=.4,m.rotate(-0.1),m.lineWidth=1,m.strokeStyle="red",m.rect(h+l/2-v,h+c/2+v,o,u),m.drawImage(e,h+l/2-v,h+c/2+v,o-1,u-1),m.stroke(),m.globalAlpha=1;debugger;var g=m.getImageData(0,0,d.width,d.height),y=p.getContext("2d");return y.fillStyle="blue",y.fillRect(0,0,s,i),y.putImageData(g,0,0),y.drawImage(e,h+l/2,h+c/2,o,u),y.lineWidth=1,y.strokeStyle="red",y.rect(h+l/2,h+c/2,o,u),y.stroke(),p.toDataURL("image/jpeg")}var n=e.find("img").first();return t(n[0])}})}(),window.GalleryListItemView=Backbone.View.extend({events:{},initialize:function(){},render:function(){var e=this.model;return $(this.el).html($(_.template(this.options.container.getTemplate("#GalleryListItem"),{title:e.get("title"),galleryID:e.get("id"),listSrc:e.get("list")}))),this.el},createNewGallery:function(){return Backbone.history.navigate("gallery-create",!0),!1}}),window.GalleryListView=Backbone.View.extend({events:{"click #btn_create_an_album":"createNewGallery"},initialize:function(){this.collection=new GalleryList},render:function(){},createNewGallery:function(){return Backbone.history.navigate("gallery-create",!0),!1},renderNoGalleries:function(){$(this.el).html(_.template(this.options.container.getTemplate("#GalleryListNone")))},renderGalleries:function(){$(this.el).html(_.template(this.options.container.getTemplate("#GalleryList")))},renderGallery:function(e){var t=new GalleryListItemView({model:e,container:this.options.container}),n=t.render();$(n).attr("name",e.get("created"));var r=$(this.el),i=r.find("#listcontent"),s=r.find("#listcontent > div");if(s.length<=0)i.append(n);else{var o=!1;for(var u=0;u<s.length;u++)if($(s[u]).attr("name")>e.get("created")){$(s[u]).before(n),o=!0;break}o||i.append(n)}return this.el}}),window.GalleryEditView=Backbone.View.extend({didNotChangeImages:!0,events:{"click #uploadbtn":"triggerUpload","click #link_save":"saveGallery","click #link_cancel":"cancelEdit","change #upload":"uploadFiles","drop #result":"uploadFiles"},initialize:function(e){this.render(),this.imageProcessor=new ImageProcessor},render:function(){var e=$(this.el),t=e.find("#result");e.html(_.template(this.options.container.getTemplate("#GalleryEdit"))),t.sortable().disableSelection()},deactivateIE:function(){var e=$(this.el),t=e.find("#ieUpload");t.hide()},setupIE:function(){debugger;var e=$(this.el),t=e.find("#ieUpload");e.find("#upload-files").hide();var n=gadgets.util.getUrlParameters().url.replace("/app.xml",""),r=gadgets.io.getProxyUrl(n+"/flashupload/bin/flashupload.swf?cachebust="+Math.random()),i=gadgets.io.getProxyUrl(n+"/flashupload/expressInstall.swf"),s="10.0.0";$.fn.addFlashUpload=function(){return this.each(function(){var e=$(this),t="flashUpload-"+$.fn.addFlashUpload.id++,n=e.outerWidth(),o=e.outerHeight(),u=e.css("position");e.attr("data-uploadid",t).append('<span id="'+t+'"></span>'),u!=="absolute"&&u!=="relative"&&e.css("position","relative");var a={uploadId:t},f={wmode:"transparent",allowscriptaccess:"always"},l={style:"position: absolute; z-index: 100; left: 0; right: 0; top: 0; bottom: 0;"};swfobject.embedSWF(r,t,n,o,s,i,a,f,l)})},$.fn.addFlashUpload.id=1,window.processBase64Encodings=function(e,t,n){$("[data-uploadid="+n+"]").trigger("upload",[e,t])},t.addFlashUpload().bind("upload",function(e,t,n){var r=t.split(".").pop();r==="jpg"&&(r="jpeg");var i=this.options.container,s=function(e){var t=new GalleryEntryView({container:i}),n=t.render(e);n.prependTo("#result").hide().css({"z-index":self.zindex++}).show(),$("#link_save").show()};this.imageProcessor.buildImage(t,"data:image/"+r+";base64,"+n,s)})},renderGallery:function(e){var t=$(this.el),n=e.get("title");n?t.find("#gallery_title").val(n):t.find("#gallery_title").val(this.prettyDate(new Date));var r=e.get("imgIDs");if(!r||r.length<1)return;console.log("Prepping image id manifest",r);var i={},s=this.options.container;$.each(r,function(){var e=this,n=new GalleryEntry({id:e}),r=new GalleryEntryView({model:n,container:s});i[e]={view:r,model:n};var o=r.render();t.find("#result").append(o)}),$.each(r,function(){var e=this;console.log("loading image id "+e);var t=i[e],n=t.model,r=t.view;n.bind("fetchedThumbnail",function(e){r.renderThumbnail(e)}),n.bind("fetchedFullSource",function(e){r.attachFullImageSource(e)}),n.fetch()});var o=this;$(this.el).find("#result").sortable(),$(this.el).find("#result img").draggable(),$(this.el).find("#trashcan_img").droppable({tolerance:"touch",drop:function(e,t){t.draggable.remove()},activate:function(e,t){$(o.el).find("#trashcan_img").hide(),$(o.el).find("#trashcan_img_active").show()},deactivate:function(e,t){$(o.el).find("#trashcan_img_active").hide(),$(o.el).find("#trashcan_img").show()}})},triggerUpload:function(){$("#upload").click()},saveGallery:function(){var e=$(this.el),t=this.model,n=e.find("#result img");if(n.length<1){console.log("Nothing to save");return}var r=[];$.each(n,function(){var e=$(this),t=e.attr("data-id")||-1;r.push(t)});for(var i=0;i<r.length;i++)if(r[i]===-1){do var s=randomNum();while(r.indexOf(s)>=0);r[i]=s}var o=this.options.container;this.saveGalleryImages(n,r,function(){var i=e.find("#gallery_title").val(),s=new GalleryPreviewView({container:o});$.each(n,function(){var e=$(this),t=$("<img>").attr("src",e.attr("data-fullsrc"));$("#secret").append(t)}),window.setTimeout(function(){var e=s.generatePreview($("#secret"),i,n.length),o=s.generateListEntry($("#secret"));t.set({title:i,imgIDs:r,preview:e,list:o}),t.save()},150)})},saveGalleryImages:function(e,t,n){var r=0,i=0,s=this.model,o=s.get("imgIDs")==""?[]:s.get("imgIDs"),u=[],a=[],f=this;$.each(t,function(e,t){o.indexOf(t)<0&&a.push({id:t,dom:$(f.el).find("#result").find("[data-id="+t+"]")[0]})}),$.each(o,function(e,n){t.indexOf(n)<0&&u.push({id:n})});var l=function(){u.length==0&&n(),$.each(u,function(e,t){i++;var r={imageId:t.id},s=function(e){console.log("Destroyed image id "+e+" source")},o=new GalleryEntry;o.destroy(r,s),i==u.length&&(console.log("Done destroying "+i),n())})};a.length==0?l():$.each(a,function(e,t){var n=$(t.dom),i={previewSrc:n.attr("src"),fullSrc:n.attr("data-fullsrc"),width:n.attr("data-width"),height:n.attr("data-height"),imageId:t.id},s=function(e){console.log("Saved image id "+e+" source"),r++,r==a.length&&(console.log("Done saving "+r),l())},o=new GalleryEntry;o.save(i,s)})},cancelEdit:function(){Backbone.history.navigate("gallery-edit-cancel",!0)},uploadFiles:function(e){var t=this;if(e.originalEvent&&e.originalEvent.dataTransfer&&e.originalEvent.dataTransfer.files){e.preventDefault();var n=e.originalEvent.dataTransfer.files}else var n=e.target.files;this.didNotChangeImages=!1;var r=function(e){$("#link_save").hide()},i=function(e,n){var r=new GalleryEntryView({container:t.options.container}),i=r.render(n);i.prependTo("#result").hide().css({"z-index":t.zindex++}).show(),$("#link_save").show()},s=function(e,t){alert(t)};if(n&&typeof FileReader!="undefined")for(var o=0;o<n.length;o++)this.imageProcessor.readFile(n[o],r,i,s);else debugger},prettyDate:function(e){function t(e){var t=String(e);return t.length===1&&(t="0"+t),t}function n(e){switch(e){case 0:return"Jan.";case 1:return"Feb.";case 2:return"Mar.";case 3:return"Apr.";case 4:return"May";case 5:return"June";case 6:return"July";case 7:return"Aug.";case 8:return"Sep.";case 9:return"Oct.";case 10:return"Nov.";case 11:return"Dec."}return""}function r(e,n){return(e%12==0?"12":e%12)+":"+t(n)+(e<12?" AM":" PM")}return n(e.getMonth())+" "+e.getDate()+", "+e.getFullYear()+" "+r(e.getHours(),e.getMinutes())}}),window.GalleryEntryView=Backbone.View.extend({events:{},render:function(e){if(!e){var t=this.model.get("id");e={thumbSrc:app.getAbsoluteUrl("/images/ajax_loader_large.gif"),imageId:t,fileName:"",fullSrc:"",imageWidth:"90",imageHeight:"90"},$(this.el).html(_.template(this.options.container.getTemplate("#GalleryEntry"),e)),this.imgDom=$(this.el).find("img")}else this.imgDom=$(_.template(this.options.container.getTemplate("#GalleryEntry"),e)),$(this.el).html(this.imgDom);return this.imgDom},renderThumbnail:function(e){var t=e.get("src"),n=e.get("width"),r=e.get("height");return this.imgDom.attr("src",t),this.imgDom.attr("data-width",n),this.imgDom.attr("data-height",r),this.imgDom},attachFullImageSource:function(e){var t=e.get("src");this.imgDom.attr("data-fullsrc",t)}}),window.GalleryViewer=Backbone.View.extend({events:{"click #close":"close"},initialize:function(){},close:function(){osapi.jive.core.container.closeApp()},render:function(){var e=this.model,t=$(this.el);t.html(_.template(this.options.container.getTemplate("#GalleryViewer"),{title:e.get("title")}));var n=e.get("imgIDs"),r=new Array,i=0,s=function(e){if(e<n.length)return;console.log(e,"versus",n.length),console.log("Loaded "+e++),$(".j-loading").hide(),$(".slideshow").show(),gadgets.window.adjustWidth(),$(".slideshow").cycle({next:"#next",pause:1,prev:"#previous",speed:100,timeout:5e3,pager:"#pager",pagerAnchorBuilder:function(e,t){return"#pager li:eq("+e+") a"}}),window.setTimeout(function(){$.each(r,function(){var e=this;e()})},2e3)};console.log("Prepping image id manifest",n);var o={},u=t.find(".slideshow").css("height").replace("px",""),a=t.find(".slideshow").css("width").replace("px",""),f=this.options.container;return $.each(n,function(){var e=this,n=new GalleryEntry({id:e}),r=new GalleryEntryView({model:n,container:f});o[e]={view:r,model:n};var i=r.render();i.hide();var s=i.clone().css("width",50).css("height",50).show();t.find(".slideshow").append(i);var u=$("<li></li>"),a=$("<a href='#'></a>");u.append(a.append(s)),t.find("#pager").append(u)}),$.each(n,function(){var e=this;console.log("loading image id "+e);var t=o[e],n=t.model,u=t.view;n.fetchThumb(function(t){var o=u.renderThumbnail(t);$("#pager img[data-id="+e+"]").attr("src",t.get("src")),o.css("width",t.get("width")*1.5),o.css("height",t.get("height")*1.5);var a=$(".slideshow").css("height").replace("px",""),f=$(".slideshow").css("width").replace("px",""),l=o.css("width").replace("px",""),c=o.css("height").replace("px",""),h=f-l,p=a-c;o.css("margin-left",h/2),o.css("margin-top",p/2),i++,s(i),r.push(function(){n.fetchSource(function(t){console.log("loaded image id "+e);var n=t.get("src"),r=$(".slideshow img[data-id="+e+"]");r.show(),r.attr("src",n)})})})}),this.el}}),window.GalleryController=function(e,t){this.viewManager=t,this.container=e,this.galleryCreate=function(){var e=new GalleryModel,t=new GalleryEditView({model:e,container:this.container});$.browser.msie||t.deactivateIE(),this.viewManager.showView(t),$.browser.msie&&t.setupIE(),e.bind("saved",function(){var t=e.get("id"),n=new GalleryList;n.bind("saved",function(){Backbone.history.navigate("gallery-saved/"+t,!0)}),n.bind("parsed",function(){n.add(t),n.save()}),n.fetch()}),t.renderGallery(e)},this.galleryEdit=function(e){var n=new GalleryModel({id:e}),r=new GalleryEditView({model:n,container:this.container});$.browser.msie||r.deactivateIE(),t.showView(r),$.browser.msie&&r.setupIE(),n.bind("parsed",function(e){r.renderGallery(e)}),n.bind("saved",function(){var t=new GalleryList;t.bind("saved",function(){Backbone.history.navigate("gallery-saved/"+e,!0)}),t.bind("parsed",function(){t.add(e),t.save()}),t.fetch()}),n.fetch()},this.galleryDelete=function(e){var t=new GalleryModel({id:e});t.bind("deleted",function(){var t=new GalleryList;t.bind("saved",function(){Backbone.history.navigate("main",!0)}),t.bind("parsed",function(){t.subtract(e),t.save()}),t.fetch()}),t.fetch({postSuccess:function(e){e.destroy()},error:function(e,t){console.log("Error fetching Gallery Model to be deleted",t)}})},this.galleryDrop=function(e){var t=new GalleryModel({id:e});t.fetch({postSuccess:function(){function n(e,t){var n=_args().url,r=n.replace(/[a-zA-Z0-9_]+\.xml(\?.*)?/,"");return t?gadgets.io.getProxyUrl(r+e):r+e}osapi.jive.corev3.people.get({id:"@me"}).execute(function(r){var i=r.id,s={display:{type:"image",previewImage:n("images/1x1.GIF")},target:{type:"embed",view:"show",context:{galleryID:e}}};osapi.jive.version.getVersionInfo().execute(function(e){osapi.jive.core.container.artifacts.create(s,"com.jivesoftware.inline.gallery.show",function(e){var n=e.markup,r=e.error,i=$("<span>"+n+"</span>");i.find("a").html('<img src="'+t.get("preview")+'"/>');var s=i.html()+"<div>"+n+"</div>";osapi.jive.core.container.editor().insert(s)},!1,!0)})})}})},this.galleryView=function(e){var t=new GalleryModel({id:e}),n=new GalleryViewer({model:t,container:this.container}),r=this.viewManager;t.bind("parsed",function(e){n.render(),r.showView(n)}),t.fetch()}},window.GalleryListController=function(e,t){this.viewManager=t,this.container=e,this.galleryList=function(){var e=new GalleryList,t=new GalleryListView({container:this.container});e.bind("parsed",function(e){!e||e.length<1?t.renderNoGalleries():(t.renderGalleries(),$.each(e,function(){var e=this,n=new GalleryModel({id:e});n.bind("parsed",function(e){t.renderGallery(e)}),n.fetch()}))}),t.render(),this.viewManager.showView(t),e.fetch()}};var jigPersistence=function(e){e=e||"@me";var t=function(t,n,r){if(t.length<1)var i={userId:e,escapeType:opensocial.EscapeType.NONE};else var i={fields:t,userId:e,escapeType:opensocial.EscapeType.NONE};osapi.appdata.get(i).execute(function(e){e.error?(console.log("fetch error",e.error),r&&r()):n&&n(e)})},n=function(e,t,n){var r={keys:e,userId:"@me"};console.log("to remove",r),osapi.appdata["delete"](r).execute(function(e){e.error?(console.log("delete error",e.error),n&&n()):t&&t(e)})},r=function(e,t,n,r){var i={};i[e]=t,osapi.appdata.update({data:i,userId:"@me",escapeType:opensocial.EscapeType.NONE}).execute(function(e){e.error?(console.log("update error",e.error),r&&r()):(console.log("update response",e),n&&n())})};this.save=function(e,t,n){r(n||"jig",e,t)},this.load=function(e,n){t([n],function(t){var r;for(var i in t)if(t.hasOwnProperty(i)){r=t[i];break}for(var s in r){console.log(r);if(r.hasOwnProperty(s)){var o=r[n||"jig"];if(o){var u=JSON.parse(o);e(u);return}}}e(null)})}};gadgets.util.registerOnLoadHandler(function(){function n(e){var t=e?e:1e6;return Math.floor(Math.random()*t)}var e=!0,t=new Image;$(document).ready(function(){function o(){e=!1,$("#result img").remove()}function u(){o(),e=!0;var t=new jigPersistence;t.load(function(e){console.log("Loaded image id manifest",e);if(!e)return;$.each(e.images,function(){var e=this,t=$(document.createElement("img"));t.attr("src","http://apphosting.jivesoftware.com/apps/dev/jigtest/images/ajax_loader_large.gif").attr("data-id",e),$("#result").append(t)}),console.log("Loaded image id manifest",e),$.each(e.images,function(){var e=this;console.log("loading image id "+e),t.load(function(n){var r=$("#result img[data-id="+e+"]"),i=n.imageSrc,s=n.width,o=n.height;r.attr("src",i),r.attr("data-width",s),r.attr("data-height",o),t.load(function(e){var t=e.imageSrc;r.attr("data-fullsrc",t)},"jig_src_"+e)},"jig_thumb_"+e)})},"jig_ids")}function a(){debugger;var t=$("#result").find("img");if(t.length<1){alert("Nothing to save");return}var r=new jigPersistence,i=0,s=function(){var e={images:[]};$.each(t,function(){var t=$(this),r=t.attr("data-id")||n();e.images.push(r)}),r.save(e,function(){console.log("Saved gallery image IDs")},"jig_ids")},o=function(){i==t.length&&(s(),alert("Done saving "+i))};if(e){s(),alert("Did not change images, maybe just order. Saving that.");return}$.each(t,function(){var e=$(this),t=e.attr("src"),s=e.attr("data-fullsrc"),u=e.attr("data-width"),a=e.attr("data-height"),f=e.attr("data-id")||n(),l={imageSrc:t,width:u,height:a},c={imageSrc:s,width:u,height:a};r.save(l,function(){console.log("Saved image id "+f+" thumb"),r.save(c,function(){console.log("Saved image id "+f+" source"),i++,o()},"jig_src_"+f)},"jig_thumb_"+f)})}function f(e){return(e/1024).toFixed(1)}function l(e,t){var n=[];return e>t?(n[0]=e-t,n[1]=0):(n[0]=0,n[1]=t-e),n}function c(e){var t=window.WebKitBlobBuilder||window.MozBlobBuilder||window.BlobBuilder;if(typeof t=="undefined")return $("#err").html("Ops! There have some limited with your browser! <br/>New image produced from canvas can't be upload to the server..."),e;var n;e.split(",")[0].indexOf("base64")>=0?n=atob(e.split(",")[1]):n=unescape(e.split(",")[1]);var r=e.split(",")[0].split(":")[1].split(";")[0],i=new ArrayBuffer(n.length),s=new Uint8Array(i);for(var o=0;o<n.length;o++)s[o]=n.charCodeAt(o);var u=new t;return u.append(i),u.getBlob(r)}t.src=app.getAbsoluteUrl("/images/play-graphic.png");var r=90,i=90,s=0;dropzone=$("#result"),uploadBtn=$("#uploadbtn"),defaultUploadBtn=$("#upload"),dropzone.on("dragover",function(){return dropzone.addClass("hover"),!1}),dropzone.on("dragleave",function(){return dropzone.removeClass("hover"),!1}),dropzone.on("drop",function(t){t.stopPropagation(),t.preventDefault(),dropzone.removeClass("hover");var n=t.originalEvent.dataTransfer.files;return e=!1,d(n),!1}),uploadBtn.on("click",function(e){e.stopPropagation(),e.preventDefault(),defaultUploadBtn.click()}),defaultUploadBtn.on("change",function(){var t=$(this)[0].files;return e=!1,d(t),!1}),$("#link_save").click(a),$("#link_clear").click(o),$("#link_load").click(u),$("#result").sortable(),$("#result").disableSelection(),u();var h=function(e){var t=e.getImageData(0,0,r,i),n=t.data;for(var s=0,o=n.length;s<o;s+=4){var u=n[s]*.3+n[s+1]*.59+n[s+2]*.11;n[s]=u,n[s+1]=u,n[s+2]=u}e.putImageData(t,0,0)},p=function(e,t,n){var s,o,u,a=4;e.globalAlpha=.1;for(s=1;s<=a;s++)for(u=-a/2;u<=a/2;u++)for(o=-a/2;o<=a/2;o++)e.drawImage(t,n[0]/2,n[1]/2,t.width-n[0],t.height-n[1],o,u,r,i);e.globalAlpha=1},d=function(e){if(e&&typeof FileReader!="undefined")for(var t=0;t<e.length;t++)v(e[t])},v=function(e){if(/image/i.test(e.type)){var t=new FileReader;$("#link_save").hide(),t.onload=function(t){var n=$("<img/>").load(function(){var t=y(this),n=b(this);console.log(t,n),w(e,t.url,n.url,n.width,n.height)}).attr("src",t.target.result);$("#link_save").show()},t.readAsDataURL(e),$("#err").text("")}else $("#err").text("*Selected file format not supported!")},m=function(e,t,n,r,i){var s=document.createElement("canvas");s.width=t,s.height=n;var o=s.getContext("2d"),u=[0,0];return i=="crop"&&(u=l(e.width,e.height)),o.drawImage(e,u[0]/2,u[1]/2,e.width-u[0],e.height-u[1],0,0,t,n),r=="grayscale"?h(o):r=="blurry"&&p(o,e,u),s.toDataURL("image/jpeg")},g=function(e,t,n,r){var i,s=0,o=n/e,u=r/t;return o>u?(s=r/o,i=e):(i=n/u,s=t),{width:i,height:s}},y=function(e){var t=$("input[name=effect]:checked").val(),n=$("input[name=croping]:checked").val(),r=g(90,90,e.width,e.height);return{width:r.width,height:r.height,url:m(e,r.width,r.height,t,n)}},b=function(e){var t=$("input[name=effect]:checked").val(),n=$("input[name=croping]:checked").val(),r=g(500,500,e.width,e.height);return{width:r.width,height:r.height,url:m(e,r.width,r.height,t,n)}},w=function(e,t,r,i,o){var u={};u.imageId=n(),u.filePath=t,u.fullSrc=r,u.imageWidth=i,u.imageHeight=o,u.fileName=e.name.substr(0,e.name.lastIndexOf(".")),u.fileOriSize=f(e.size),u.fileUploadSize=f(c(t).size);var a=$("input[name=effect]:checked").val();a=="grayscale"?u.fileName+=" (Grayscale)":a=="blurry"&&(u.fileName+=" (Blurry)");var l=Math.floor(Math.random()*31)-15,h=$("#imageTemplate").tmpl(u).prependTo("#result").hide().css({"z-index":s++}).show();isNaN(u.fileUploadSize)&&$(".imageholder span").last().hide()},E=function(e){var t={},n=["jpg","jpeg","gif","png"],r=e.value;if(r){var i=r.indexOf("\\")>=0?r.lastIndexOf("\\"):r.lastIndexOf("/"),o=r.substring(i);if(o.indexOf("\\")===0||o.indexOf("/")===0)o=o.substring(1);var u=o.substr(0,o.lastIndexOf(".")),a=o.slice(o.lastIndexOf(".")+1).toLowerCase();if($.inArray(a,n)>-1){$("#err").text(""),t.filepath=r,t.filename=u;var f=Math.floor(Math.random()*31)-15;$("#imageTemplate").tmpl(t).prependTo("#result").hide().css({"z-index":s++}).show(),$("#result").find("figcaption span").hide()}else $("#err").text("*Selected file format not supported!")}}})}),function(){window.console||(console={log:function(e){}});var e={"gallery-select/:id":"galleryDrop"},t={routes:e};window.app=new App,app.initialize(t)}();