/lib/chute.js
JavaScript | 1803 lines | 1280 code | 268 blank | 255 comment | 368 complexity | de866c87b905cd888b1231a74b959109 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- function chutelog(what) {
- try {
- console.log(what);
- }
- catch (e) {}
- finally {
- return;
- }
- }
- /*
- * jQuery SlideChute Plugin 1.0.0
- * www.slidechute.com
- * Copyright 2012, Chute Corporation
- * Free to use under the MIT license.
- * http://www.opensource.org/licenses/mit-license.php
- */
- var currentWidget = null;
- var $chuteWidget;
- function chuteGetScript(url, success) {
- var script = document.createElement('script');
- script.src = url;
- var head = document.getElementsByTagName('head')[0],
- done = false;
- script.onload = script.onreadystatechange = function() {
- if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
- done = true;
- success();
- script.onload = script.onreadystatechange = null;
- head.removeChild(script);
- }
- };
- head.appendChild(script);
- }
- var __chute = function(element, data){
- function _loader(element, data){
- __chuteFunctions()
- jQuery(element).chute(data);
- }
- if (typeof(jQuery) != 'undefined') {
- _loader(element, data);
- }
- var _readyCallback = function(){
- if (typeof(jQuery) == 'undefined'){
- chuteGetScript('//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', function(){
- setTimeout(function(){
- _loader(element, data);
- }, 10);
- });
- } else {
- _loader(element, data);
- }
- }
- var _loadCallback = function(){
- if (document.readyState == 'complete'){
- _readyCallback();
- }
- };
- if (typeof(jQuery) == 'undefined'){
- if (document.readyState == 'complete'){
- _readyCallback();
- } else if (document.addEventListener){
- document.addEventListener("readystatechange", _loadCallback);
- } else {
- document.attachEvent("onreadystatechange", _loadCallback);
- }
- }
- }
- var __chuteFunctions = function(){
- (function($) {
- var CHUTE = {
- popupHtml: "<style type='text/css'>.chute-reveal-modal { visibility:hidden }</style><div class='chute-popup chute-reveal-modal'>\
- <iframe width='100%' height='100%' marginWidth='0' marginHeight='0' frameBorder='0' scrolling='no' title='' src='//s3.amazonaws.com/cdn.getchute.com/html/v1/loading.html'>IFrame not supported</iframe>\
- <a class='close-chute-reveal-modal'>×</a>\
- </div>\
- <div class='chute-thanks chute-reveal-modal'>\
- <div class='chute-thanks-header'>SUCCESS_MESSAGE</div>\
- <div class='chute-thanks-footer'>\
- <a href='mailto:info@getchute.com'>info@getchute.com</a>\
- </div>\
- <a class='close-chute-reveal-modal'> </a>\
- </div>",
- defaultDisplayTemplateHtml: "<style type='text/css'>.chute-thumbnails a{margin: 5px} .chute-thumbnails img{width:100px;height:100px;} .chute-thumbnail-reveal-modal {visibility: hidden;top: 0;left: 50%;margin-left: -250px;width: 500px;max-height: 800px;position: fixed;z-index: 10001;background-color:#fff;-moz-box-shadow: 0 0 10px rgba(0,0,0,.4);-webkit-box-shadow: 0 0 10px rgba(0,0,0,.4);-box-shadow: 0 0 10px rgba(0,0,0,.4);overflow:hidden;} .chute-thumbnail-reveal-modal img{width: 100%;float: left;} .chute-thumbnail-reveal-modal .close-chute-thumbnail-reveal-modal {font-size: 22px;line-height: .5;position: absolute;top: 15px;right: 11px;color: #aaa;text-shadow: 0 -1px 1px rbga(0,0,0,.6);font-weight: bold;cursor: pointer;} .chute-thumbnail-reveal-modal .chute-thumbnail-source{position:absolute;left: 0;bottom: 30px;background-color: #000;background-color: rgba(0,0,0, 0.6);color: #fff;padding: 5px;text-decoration: none;-moz-box-shadow: 0 0 5px #888;-webkit-box-shadow: 0 0 5px#888;box-shadow: 0 0 5px #888;} .chute-reveal-modal-bg {position: fixed;height: 100%;width: 100%;background: #000;background: rgba(150,150,150,.8);z-index: 10000;display: none;top: 0;left: 0;}</style><div class='chute-thumbnails'>{{#images}}<a href='{{url}}' data-source-url='{{source_url}}' data-url='{{url}}'><img src='{{url}}/100x100'></a>{{/images}}</div>",
- defaultCollectTemplateHtml: "<a href='#' class='chute-browseButton'><img src='//s3.amazonaws.com/cdn.getchute.com/v1/images/add-photos.png' style='border:0'></a>",
- // Paths
- paths: {
- assets : '/assets/:id', // Path to assets data
- gallery : '/chutes/:id.js', // Path to gallery data
- collection : '/collection/:id' // Path to collection data
- },
- // Defaults
- defaults: {
- uploadServer : '//upload.getchute.com', // Path to Upload Server
- apiServer : '//api.getchute.com', // Path to API
- cdnRoot : '//s3.amazonaws.com/cdn.getchute.com/v1',
- popup : false,
- app : null, // ID of the app
- disable_auto_identifier : false,
- display_template_name : null, // required only with an external url based template
- display_template : null, // jQuery Object or HTML template
- collector_template_name : null, // collector theme name
- collector_template : null, // collector theme path
- collector_width : '635px', // collector template width
- collector_height : '435px', // collector template height
- template_options : {},
- // Data Sources
- assets : null, // ID of Asset(s) to render as comma-delimited list
- gallery : null, // ID of the Gallery to render
- collection : null, // ID of the Collection to render
- // Externals
- css : '', // Comma-delimited list of css externals to load
- css_loaded : false, // Boolean indicating if all required css is loaded
- scripts : '', // Comma-delimited list of js externals to load
- scripts_lodaed : false, // Boolean indicating if all required js is loaded,
- exclusions : "",
- file_types : 1, // 0 = all, 1 = image, 2 = video
- file_limit : 0, // 0 = unlimited
- is_display : true,
- success_message : "<h3>Thanks!</h3><p>Your photos will be online as soon as they're approved</p>",
- // Plugin Events
- onComplete : function() {}, // Fired when the the plugin has completely initialized
- // Display Events
- onTemplateLoaded : function() {}, // Fired when template loaded
- onDependenciesLoaded : function() {}, // Fired when template dependencies loaded
- onAssetsLoading : function() {}, // Fired when assets are starting to load
- onAssetsLoaded : function() {}, // Fired when assets are loaded
- onAssetsRendered : null, // Fired when assets are rendered
- onAssetsReRendered : function() {}, // Fired when assets are re-rendered
- // Collection Events
- onDrop : function() {}, // Fired when assets are dropped on the plugin
- onAlbumList : function() {}, // Fired when the listing of albums is loaded
- onAlbumLoad : function() {}, // Fired when an external album loads
- onAdd : function() {}, // Fired when assets are selection for inclusion
- onRemove : function() {}, // Fired when assets are removed from inclusion
- onSelection : function() {}, // Fired when selection of photos has been completed
- onConfirmation : function() {}, // Fired when rights are confirmed
- onProfileComplete : function() {}, // Fired when custom profile is completed
- onSelectionComplete : function() {} // Fired when widget has completed the process
- },
- // Initializer
- init: function(element, options) {
- // Save values
- this.$element = $(element);
- this.$element.addClass('chute-loaded');
- // pull in options specified by html5 tags
- var _htmlOptions = {
- app : this.$element.attr('data-app-id'),
- identifier : this.$element.attr('data-identifier') == undefined || this.$element.attr('data-identifier') == '' ? null : this.$element.attr('data-identifier'),
- disable_auto_identifier : this.$element.attr('data-disable-auto-identifier') == undefined ? this.defaults.disable_auto_identifier : true,
- id : this.$element.attr('data-id') == undefined ? null : this.$element.attr('data-id'),
- bundle_id : this.$element.attr('data-bundle-id') == undefined ? '' : this.$element.attr('data-bundle-id'),
- custom_id : this.$element.attr('data-custom_id') == undefined ? '' : this.$element.attr('data-custom_id'),
- assets : this.$element.attr('data-assets') == undefined ? this.defaults.assets : this.$element.attr('data-assets').split(','),
- name : this.$element.attr('data-name'),
- url : this.$element.attr('data-url') == undefined ? document.location.href : this.$element.attr('data-url'),
- tags : this.$element.attr('data-tags') == undefined ? '' : this.$element.attr('data-tags'),
- css : this.$element.attr('data-css') == undefined ? '' : this.$element.attr('data-css'),
- screens : this.$element.attr('data-screens') == undefined ? '' : this.$element.attr('data-screens'),
- display_template_name : this.$element.attr('data-display-template-name') == undefined ? this.defaults.display_template_name : this.$element.attr('data-display-template-name'),
- display_template : this.$element.attr('data-display-template') == undefined ? this.defaults.display_template : this.$element.attr('data-display-template'),
- collector_template_name : this.$element.attr('data-collector-template-name') == undefined ? this.defaults.collector_template_name : this.$element.attr('data-collector-template-name'),
- collector_template : this.$element.attr('data-collector-template') == undefined ? this.defaults.collector_template : this.$element.attr('data-collector-template'),
- collector_width : this.$element.attr('data-collector-width') == undefined ? this.defaults.collector_width : this.$element.attr('data-collector-width'),
- collector_height : this.$element.attr('data-collector-height') == undefined ? this.defaults.collector_height : this.$element.attr('data-collector-height'),
- template_options : this.$element.attr('data-template-options') == undefined ? this.defaults.template_options : $.parseJSON(this.$element.attr('data-template-options')),
- captions : this.$element.attr('data-captions') == undefined ? 'hide' : this.$element.attr('data-captions'),
- exclusions : this.$element.attr('data-services-exclude') == undefined ? this.defaults.exclusions : this.$element.attr('data-services-exclude'),
- inclusions : this.$element.attr('data-services-include') == undefined ? '' : this.$element.attr('data-services-include'),
- dialogTitle : this.$element.attr('data-chooser-button-text') == undefined ? 'Choose Photos' : this.$element.attr('data-chooser-button-text'),
- mode : this.$element.attr('data-mode') == undefined ? 'thumbnails' : this.$element.attr('data-mode'),
- uploadServer : this.$element.attr('data-uploadServer') == undefined ? this.defaults.uploadServer : this.$element.attr('data-uploadServer'),
- apiServer : this.$element.attr('data-apiServer') == undefined ? this.defaults.apiServer : this.$element.attr('data-apiServer'),
- cdnRoot : this.$element.attr('data-cdnRoot') == undefined ? this.defaults.cdnRoot : this.$element.attr('data-cdnRoot'),
- file_types : this.$element.attr('data-file-types') == undefined ? this.defaults.file_types : this.$element.attr('data-file-types'),
- file_limit : this.$element.attr('data-file-limit') == undefined ? this.defaults.file_limit : this.$element.attr('data-file-limit'),
- share_text : this.$element.attr('data-share-text') == undefined ? '' : this.$element.attr('data-share-text'),
- awesm_key : this.$element.attr('data-awesm-key') == undefined ? '' : this.$element.attr('data-awesm-key'),
- popup : this.$element.attr('data-popup') == 'popup',
- success_message : this.$element.attr('data-success_message') == undefined ? this.defaults.success_message : this.$element.attr('data-success_message')
- }
- // Set the options
- this.options = $.extend({}, this.defaults, _htmlOptions);
- this.options = $.extend({}, this.options, options);
- this.options.is_display = !(this.options.mode == 'collector' || this.options.mode == 'chooser');
- this.popupHtml = this.popupHtml.replace('SUCCESS_MESSAGE', this.options.success_message);
- if (this.options.identifier == null && !this.options.disable_auto_identifier){
- this.options.identifier = '';
- this.options.id = '';
- }
- // use popup window when in an iframe hosted by us, or on a mobile
- // browser, unless already specified
- if ((!this.options.popup && window!=window.top && (document.location.host.indexOf("chute.com") == 0 || document.location.host.indexOf("slidechute.com") == 0))
- || navigator.userAgent.match(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i)) {
- this.options.popup = true;
- }
- var me = this;
- me.$element.addClass('chute-base-widget').css('position', 'relative');
- me.$element.data('options', this.options);
- me.$element.data('instanceReference', this);
- if (me.options.is_display){
- if (this.options.display_template == null && this.options.display_template_name != null){
- this.options.display_template = this.options.cdnRoot + "/templates/display/" + this.options.display_template_name + "/template.js";
- }
- if (me.options.display_template && me.options.display_template.indexOf('#') == 0){
- me.options.display_template = $(me.options.display_template).html();
- me.renderData();
- } else if (this.options.display_template != undefined && (this.options.display_template.indexOf('http') == 0 || this.options.display_template.indexOf('//') == 0)){
- $.getScript(me.options.display_template, function() {
- me.loadTemplateData(function(){
- me.options.onDependenciesLoaded(me.$element);
- me.renderData();
- });
- });
- } else if (this.options.display_template_name == undefined || this.options.display_template_name == 'default' || this.options.display_template_name == ''){
- this.options.display_template = this.defaultDisplayTemplateHtml;
- this.options.onAssetsRendered = this.assetsRendered;
- me.renderData();
- }
- }
- else {
- if (this.options.collector_template == null && this.options.collector_template_name == null){
- this.options.collector_template = this.defaultCollectTemplateHtml;
- }
- else if (this.options.collector_template == null){
- this.options.collector_template = this.options.cdnRoot + "/templates/collector/" + this.options.collector_template_name + "/template.js";
- }
- me.renderData();
- }
- me.options.onComplete();
- return me;
- },
- renderData: function(page_url){
- var me = this;
- me.resetTimestamp();
- if (me.options.is_display){
- if (me.options.id == null && me.options.identifier == null){
- me.$element.addClass('chute-disabled').css('opacity', '0.5');
- return;
- }
- me.options.onAssetsLoading(me.$element);
- var defaultUrl = me.options.imagesUrl;
- // if assets already given then get the ids
- if (me.options.assets){
- var staticAssets = "";
- if (typeof me.options.assets == 'string')
- me.options.assets = me.options.assets.split(',');
- if (me.options.assets[0].indexOf('http') == 0) {
- staticAssets = "assets=" + $.map(me.options.assets, function(asset_url){
- var match = asset_url.match("\/m\/([^\/]+)/");
- return match.pop();
- }).join(',');
- } else {
- staticAssets = "assets=" + me.options.assets.join(',');
- }
- defaultUrl += "&" + staticAssets;
- }
- if (this.options.template_options.per_page)
- defaultUrl += "&per_page=" + this.options.template_options.per_page;
- var loadState = page_url == undefined ? -1 : (page_url == me.options.nextImagesUrl ? 0 : 1);
- var _url = page_url ? page_url : defaultUrl;
- // if there is a hash in the document, then it could point to an asset
- // make sure its there in the page
- if (loadState == -1 && document.location.hash != "" && document.location.hash != "#"){
- var _extraAssetId = document.location.hash.replace('#', '');
- _url = _url + "&extra_assets=" + _extraAssetId;
- }
- me.loadPath(_url, function(data){
- // new data link
- // don't update when requesting next and previous pages
- if (data.data.next_url && loadState != 1){
- me.options.nextImagesUrl = data.data.next_url;
- }
- // paginations link
- // don't update when requesting new data
- if (loadState != 0){
- me.options.nextPageUrl = data.data.next_page_url;
- me.options.previousPageUrl = data.data.previous_page_url;
- }
- if (data.data.assets.length > 0){
- if (me.options.onAssetsLoaded(me.$element, data) != false){
- // writeout template html in page
- me.displayRender(data, loadState);
- }
- }
- });
- } else {
- me.setupCollectorModal();
- me.collectorRender(function(){
- me.$element.find('.chute-popup').css({
- width: me.options.collector_width,
- height: me.options.collector_height,
- 'margin-left' : '-' + parseInt(me.options.collector_width)/2 + 'px'
- });
- if (me.options.id == null && me.options.identifier == null){
- me.$element.addClass('chute-disabled').css('opacity', '0.5');
- return;
- }
- me.makeDroppable(me.$element.find('.chutedrop'));
- });
- }
- },
- hasNextPage: function(){
- return (this.options.nextPageUrl != undefined);
- },
- hasPreviousPage: function(){
- return (this.options.previousPageUrl != undefined);
- },
- hasNewPage: function(){
- return (this.options.nextImagesUrl != undefined);
- },
- renderNextPage: function(){
- if (this.hasNextPage()){
- this.renderData(this.options.nextPageUrl)
- }
- },
- renderPreviousPage: function(){
- if (this.hasPreviousPage())
- this.renderData(this.options.previousPageUrl)
- },
- renderNewData: function(){
- if (this.hasNewPage()){
- this.renderData(this.options.nextImagesUrl)
- }
- },
- //////////////////////////////////////////////////////////
- // Loaders
- //////////////////////////////////////////////////////////
- // Load CSS dependencies
- loadCSS: function(url) {
- if(!url) return;
- if (typeof(url) == 'string') {
- if (url.indexOf('http') != 0)
- url = document.location.protocol + url;
- $('head').append( '<link rel="stylesheet" type="text/css" href="' + url + '" />' );
- }
- else {
- $.each(url, function(i, _url){
- if (_url.indexOf('http') != 0)
- _url = document.location.protocol + _url;
- $('head').append( '<link rel="stylesheet" type="text/css" href="' + _url + '" />' );
- });
- }
- },
- // Load JS dependencies
- loadJS: function(url, callback) {
- if(!url) {
- callback();
- return;
- }
- if (typeof(url) == 'string') {
- $.getScript(url, callback);
- }
- else if (url.length == 0) {
- callback();
- }
- else if (url.length == 1) {
- $.getScript(url[0], callback);
- }
- else {
- // http://www.jquery4u.com/ajax/getscript-mutiple-scripts/
- var // reference declaration & localization
- length = url.length,
- deferreds = [],
- counter = 0,
- idx = 0;
- var handler = function(){
- counter++;
- if (counter == length) {
- callback();
- }
- }
- for ( ; idx < length; idx++ ) {
- deferreds.push(
- $.getScript( url[ idx ], handler )
- );
- }
- }
- },
- // Load the data based on the passed data sources
- // Data order: Collection > Gallery > Asset
- loadData: function(callback) {
- var path = '';
- // Collection
- if (this.options.collection != null) {
- path = this.paths.collection.replace(':id',this.options.collection);
- // Gallery
- } else if (this.options.gallery != null) {
- path = this.paths.gallery.replace(':id',this.options.gallery);
- // Asset
- } else if (this.options.assets != null) {
- path = this.paths.asset.replace(':id',this.options.asset);
- }
- // If we have found a data call to make, complete it
- if (path.length) {
- var url = this.paths.api + path;
- /*this.loadJS(this.paths.api + path, function(data, status) {
- console.log(data)
- console.log(status)
- });*/
- //$.get(url, function(data, status) { console.log(data); console.log(status);}, "json");
- $.ajax({
- url : this.paths.api + path,
- dataType : 'jsonp',
- success : function(data, textStatus, jqXHR) {
- // console.log(data);
- },
- error : function(e) {
- // console.log(e);
- }
- });
- }
- },
- loadPath: function(path, callback){
- $.ajax({
- url : path,
- dataType : 'jsonp',
- success : function(data, textStatus, jqXHR) {
- callback(data);
- },
- error : function(e) {
- // console.log(e);
- }
- });
- },
- //////////////////////////////////////////////////////////
- // Load Template Data
- //////////////////////////////////////////////////////////
- loadTemplateData : function(callback){
- var me = this;
- if (this.options.is_display){
- this.options.display_template = eval(this.options.display_template_name + '_template_definition');
- if (typeof(this.options.display_template) != 'string'){
- this.options = $.extend({}, this.options, this.options.display_template.bindings);
- this.options.onTemplateLoaded(me.$element);
- me.loadCSS(this.options.display_template.requires.css);
- me.loadJS(this.options.display_template.requires.js, function(){
- callback();
- });
- } else {
- callback();
- }
- }
- },
- //////////////////////////////////////////////////////////
- // Collectors
- //////////////////////////////////////////////////////////
- // Load dependencies for collection mode
- setupCollectorModal: function() {
- if (!$('#chute-collector-modal').length) {
- // Load Reveal External
- this.loadCSS(this.options.cdnRoot + '/css/c.css');
- }
- },
- // Render Collector
- collectorRender: function(callback) {
- var me = this;
- if (me.options.collector_template.indexOf('http') == 0) {
- $.getScript(me.options.collector_template, function() {
- me.$element.html(me.popupHtml + eval(me.options.collector_template_name + '_template_html'));
- callback();
- });
- } else {
- me.$element.html(me.popupHtml + me.options.collector_template);
- callback();
- }
- },
- // Collector Modal
- collectorModal: function() {
- this.setupCollectorModal();
- // Attach the behavior
- this.$element.click(function(event) {
- event.preventDefault();
- })
- },
- makeDroppable: function(element) {
- var me = this;
- me.$element.find('.chute-browseButton, .chute-dropBox').click(function(event){
- event.preventDefault();
- me.openChuteBrowser();
- });
- me.openChuteBrowser = function(){
- if (me.options.popup){
- var width = 700;
- var height = 450
- var left = parseInt((screen.availWidth/2) - (width/2));
- var top = parseInt((screen.availHeight/2) - (height/2));
- var windowFeatures = "width=" + width + ",height=" + height + ",status,resizable,scrollbars=0,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top;
- window.open(me.options.browsePath, "chute_browse_popup", windowFeatures);
- } else if (me.options.embed) {
- var element = jQuery(me.options.embed).append(me.$element.find('.chute-popup iframe').clone().attr('src', me.options.browsePath));
- element.css({
- width: 600,
- height: 400
- });
- } else {
- me.$element.find(".chute-popup iframe").attr('src', me.options.browsePath);
- me.$element.find(".chute-popup").chuteReveal();
- }
- this.resetTimestamp();
- currentWidget = me;
- }
- me.$element.find('.chute-popup .close-chute-reveal-modal').click(function(){
- me.resetIframe();
- });
- if(element.length == 0) return;
- var totalImagesCount = 0;
- var uploadedImagesCount = 0;
- var totalUploadPercentDone = 0;
- var maxFileSize = '';
- var extensions = '';
- var browseTitle = '';
- if (me.options.file_types == 0) {
- maxFileSize = '50MB';
- extensions = 'jpg,gif,png,jpeg,mov,mp4,mpeg,mpeg,avi';
- browseTitle = 'Media Files';
- } else if (me.options.file_types == 1) {
- maxFileSize = '5MB';
- extensions = 'jpg,gif,png,jpeg';
- browseTitle = 'Image Files';
- } else {
- maxFileSize = '50MB';
- extensions = 'mov,mp4,mpeg,mpeg,avi';
- browseTitle = 'Video Files';
- }
- element.attr('id', me.options.timestamp);
- // upload code - start
- var ChuteUploader = new plupload.Uploader({
- runtimes : 'html5,flash,silverlight',
- browse_button : '',
- container : me.options.timestamp,
- max_file_size : maxFileSize,
- resize : { quality : 90 },
- url : me.options.uploadPath,
- flash_swf_url : '//s3.amazonaws.com/cdn.getchute.com/objects/v1/plupload.flash.swf',
- silverlight_xap_url : '//s3.amazonaws.com/cdn.getchute.com/objects/v1/plupload.silverlight.xap',
- filters : [{
- title : browseTitle,
- extensions : extensions
- }],
- drop_element : me.options.timestamp
- });
- ChuteUploader.bind('Init', function(up, params) {
- // ready
- setTimeout(function(){
- me.$element.find('.plupload.html5 input').attr('size', 300);
- }, 100);
- me.$element.find('.chute-select-button').click(function(event){
- event.preventDefault();
- me.openChuteBrowser();
- });
- });
- $('#uploadfiles').click(function(e) {
- ChuteUploader.start();
- e.preventDefault();
- });
- ChuteUploader.init();
- ChuteUploader.bind('FilesAdded', function(up, files) {
- me.options.onDrop(me.$element, files);
- me.setChuteFileProgress(0);
- $.each(files, function(i, file) {
- totalImagesCount++;
- });
- up.refresh(); // Reposition Flash/Silverlight
- // automatically start upload, no need to click a button
- ChuteUploader.start();
- });
- ChuteUploader.bind('UploadProgress', function(up, file) {
- totalUploadPercentDone = (file.percent + uploadedImagesCount*100)/totalImagesCount;
- me.setChuteFileProgress(totalUploadPercentDone);
- });
- ChuteUploader.bind('Error', function(up, err) {
- alert('Files cannot be larger than ' + maxFileSize);
- up.refresh(); // Reposition Flash/Silverlight
- });
- ChuteUploader.bind('FileUploaded', function(up, file) {
- uploadedImagesCount ++;
- totalUploadPercentDone = (uploadedImagesCount*100)/totalImagesCount;
- me.setChuteFileProgress(totalUploadPercentDone);
- });
- ChuteUploader.bind('UploadComplete', function(up, file) {
- totalUploadPercentDone = 100;
- me.setChuteFileProgress(totalUploadPercentDone);
- me.openChuteBrowser();
- });
- me.setChuteFileProgress = function(progress){
- if (progress < 100) {
- me.$element.find('.chute-collector').addClass('chute-uploading');
- } else {
- me.$element.find('.chute-collector').removeClass('chute-uploading');
- }
- me.$element.find('.chute-uploadProgress .chute-bar').css('width', progress + "%");
- }
- // upload code - end
- },
- resetTimestamp: function(){
- var d = new Date();
- var timestamp = ("" + (d.getTime()-d.getMilliseconds())/1000 + "-" + Math.random()).replace("0.", "");
- this.options.timestamp = timestamp;
- var toURIParams = function(obj) {
- var val, params=[];
- for (var key in obj) {
- val = obj[key];
- if (val && typeof val != 'undefined' && (val.length > 0 || typeof val === 'number')) {
- params.push(key + "=" + encodeURIComponent(val));
- }
- }
- return params.join('&');
- };
- this.options.uploadPath = this.options.uploadServer + '/upload?' + toURIParams({
- timestamp : this.options.timestamp,
- app_id : this.options.app,
- id : this.options.id,
- identifier : this.options.identifier,
- title : this.options.name,
- url : this.options.url,
- tags : this.options.tags,
- screens : this.options.screens,
- css : this.options.css,
- captions : this.options.captions,
- exclusions : this.options.exclusions,
- inclusions : this.options.inclusions
- });
- this.options.browsePath = this.options.uploadServer + '/payload/' + this.options.timestamp + "?" + toURIParams({
- app_id : this.options.app,
- id : this.options.id,
- identifier : this.options.identifier,
- custom_id : this.options.custom_id,
- title : this.options.name,
- url : this.options.url,
- tags : this.options.tags,
- host : document.location.host,
- page : document.location.href,
- screens : this.options.screens,
- css : this.options.css,
- scripts : this.options.scripts,
- iframe : this.options.iframe,
- iframe_position : this.options.iframe_position,
- iframe_title : this.options.iframe_title,
- captions : this.options.captions,
- exclusions : this.options.exclusions,
- inclusions : this.options.inclusions,
- dialog_title : this.options.dialogTitle,
- popup : this.options.popup.toString(),
- picker_version : this.options.picker_version,
- limit : this.options.limit,
- config : this.options.config
- });
- this.options.imagesUrl = this.options.apiServer + '/widget/data?' + toURIParams({
- app_id : this.options.app,
- id : this.options.id,
- identifier : this.options.identifier,
- origin : document.location.host
- });
- },
- resetIframe: function(){
- this.$element.find(".chute-popup iframe").attr('src', "//s3.amazonaws.com/cdn.getchute.com/html/v1/loading.html");
- },
- uploadComplete: function(data){
- if (data.moderated && !this.options.popup){
- if (data.success_message && typeof data.success_message === 'string' && data.success_message.length > 0) {
- this.$element.find('.chute-thanks .chute-thanks-header').html(data.success_message);
- }
- this.$element.find('.chute-thanks').chuteReveal();
- }
- this.options.onSelectionComplete(this.$element, data);
- if (typeof(chuteSelectionComplete) == 'function'){
- chuteSelectionComplete(this.$element, data);
- }
- },
- //////////////////////////////////////////////////////////
- // Presenters
- //////////////////////////////////////////////////////////
- assetsRendered: function(element, data){
- var chuteThumbnailReveal = jQuery('#chute-thumbnail-reveal');
- if (chuteThumbnailReveal.length == 0){
- jQuery('body').append('<div class="chute-thumbnail-reveal-modal" id="chute-thumbnail-reveal"><img src=""><a class="chute-thumbnail-source" href="" target="_blank">source</a><a class="close-chute-thumbnail-reveal-modal">×</a></div>');
- chuteThumbnailReveal = jQuery('#chute-thumbnail-reveal');
- }
- element.find('.chute-thumbnails a').live('click', function(event){
- event.preventDefault();
- chuteThumbnailReveal.find('img').attr('src', $(this).attr('data-url'));
- chuteThumbnailReveal.find('.chute-thumbnail-source').attr('href', $(this).attr('data-source-url'));
- chuteThumbnailReveal.chuteReveal({
- dismissmodalclass: 'close-chute-thumbnail-reveal-modal',
- top: "50px"
- });
- });
- },
- // Render Display Template
- displayRender: function(data, loadState) {
- var _templateDefinition = typeof(this.options.display_template) == 'string' ? this.options.display_template : this.options.display_template.template;
- var _templateContainer = typeof(this.options.display_template) == 'string' ? null : this.options.display_template.templateContainer;
- for (var key in this.options.template_options){
- if (this.options.display_template.options[key]){
- this.options.display_template.options[key].value = this.options.template_options[key];
- }
- }
- if (typeof(this.options.display_template.options) != 'undefined') {
- this.options.display_template.options.share_text = this.options.share_text;
- this.options.display_template.options.awesm_key = this.options.awesm_key;
- this.options.display_template.options.chute_id = this.options.chute_id;
- this.options.display_template.options.widget_id = this.options.widget_id;
- }
- for (var i in data.data.assets) {
- data.data.assets[i].serialized = encodeURIComponent($.serializeJSON(data.data.assets[i]).replace(/(\r\n|\n|\r|\t)/gm, ""));
- }
- var _html = ChuteMustache.to_html(_templateDefinition, { images: data.data.assets, options : this.options.display_template.options });
- if (_templateContainer){
- _html = _templateContainer.replace("{{yield}}", _html);
- }
- var appendContent = false;
- if (this.options.display_template.systemOptions && this.options.display_template.systemOptions.appendContent)
- appendContent = true;
- if (loadState > -1){
- if (_templateContainer){
- // new data
- if (loadState == 0)
- this.options.templateContainer.prepend(_html);
- // paginated data
- else if (appendContent)
- this.options.templateContainer.append(_html);
- else
- this.options.templateContainer.html(_html);
- } else {
- // new data
- if (loadState == 0)
- this.$element.prepend(_html);
- // paginted data
- else if (appendContent)
- this.$element.append(_html);
- else
- this.$element.html(_html);
- }
- this.options.onAssetsReRendered(this.$element, data, this.options.display_template.options, loadState);
- } else {
- this.options.templateContainer = this.$element.html(_html);
- if (typeof(this.options.onAssetsRendered) == 'function')
- this.options.onAssetsRendered(this.$element, data, this.options.display_template.options);
- }
- }
- };
- var methods = {
- init : function(options){
- if (options == undefined) options = {};
- return this.each(function () {
- var chute = $.extend({}, CHUTE);
- chute.init(this, options);
- chute.$element.data('callback', function(){
- if(chute.options.popup) {
- // do something
- } else {
- chute.$element.find(".close-chute-reveal-modal").click();
- }
- });
- if (options != undefined && typeof(options.success) == "function"){
- chute.$element.data('success-callback', options.success);
- }
- });
- },
- chooser : function(callback){
- var me = $(this);
- if (callback != undefined)
- me.data('success-callback', callback);
- me.find('.chute-browseButton').click();
- return me;
- },
- close : function(){
- var me = $(this);
- me.find('.close-chute-reveal-modal').click();
- return me;
- },
- success : function(files){
- var me = $(this);
- if (typeof(me.data('callback')) == 'function')
- me.data('callback')();
- if (typeof(me.data('success-callback')) == 'function')
- me.data('success-callback')(files);
- return me;
- },
- widget : function(){
- return $(this).find('.chute-popup iframe');
- }
- }
- $.fn.chute = function(method, callback){
- if (method == undefined || typeof(method) == 'object'){
- return methods.init.apply( this, arguments );
- } else if ( methods[method] ) {
- return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
- } else {
- $.error( 'Method ' + method + ' does not exist on jQuery.chute' );
- }
- };
- })(jQuery);
- (function($) {
- if ($chuteWidget != undefined){
- // add listsners just once
- $('.chute-widget:not(.chute-loaded)').chute();
- return;
- }
- $chuteWidget = 'chute';
- if (document.addEventListener){
- window.addEventListener('message', receiveMessage, false);
- } else {
- window.attachEvent('onmessage', receiveMessage);
- }
- function receiveMessage(event){
- receiveData(event.data);
- }
- function parseJSON(data){
- if (typeof(JSON) != 'undefined'){
- return JSON.parse(data);
- } else {
- return $.parseJSON(data);
- }
- }
- function receiveData(data){
- try {
- data = parseJSON(data);
- } catch(ex){
- data = data;
- }
- if (currentWidget && data.moderated != undefined){
- currentWidget.$element.chute('success', data);
- currentWidget.uploadComplete(data);
- }
- }
- chuteImageLoaded = function(image){
- $(image).chuteScaleImage({fade: Math.floor(Math.random()*1000)});
- }
- })(jQuery);
- /*********************************************
- mustache
- **********************************************/
- /*
- mustache.js â Logic-less templates in JavaScript
- See http://mustache.github.com/ for more info.
- */
- ChuteMustache = function() {
- var regexCache = {};
- var Renderer = function() {};
- Renderer.prototype = {
- otag: "{{",
- ctag: "}}",
- pragmas: {},
- buffer: [],
- pragmas_implemented: {
- "IMPLICIT-ITERATOR": true
- },
- context: {},
- render: function(template, context, partials, in_recursion) {
- // reset buffer & set context
- if(!in_recursion) {
- this.context = context;
- this.buffer = []; // TODO: make this non-lazy
- }
- // fail fast
- if(!this.includes("", template)) {
- if(in_recursion) {
- return template;
- } else {
- this.send(template);
- return;
- }
- }
- // get the pragmas together
- template = this.render_pragmas(template);
- // render the template
- var html = this.render_section(template, context, partials);
- // render_section did not find any sections, we still need to render the tags
- if (html === false) {
- html = this.render_tags(template, context, partials, in_recursion);
- }
- if (in_recursion) {
- return html;
- } else {
- this.sendLines(html);
- }
- },
- /*
- Sends parsed lines
- */
- send: function(line) {
- if(line !== "") {
- this.buffer.push(line);
- }
- },
- sendLines: function(text) {
- if (text) {
- var lines = text.split("\n");
- for (var i = 0; i < lines.length; i++) {
- this.send(lines[i]);
- }
- }
- },
- /*
- Looks for %PRAGMAS
- */
- render_pragmas: function(template) {
- // no pragmas
- if(!this.includes("%", template)) {
- return template;
- }
- var that = this;
- var regex = this.getCachedRegex("render_pragmas", function(otag, ctag) {
- return new RegExp(otag + "%([\\w-]+) ?([\\w]+=[\\w]+)?" + ctag, "g");
- });
- return template.replace(regex, function(match, pragma, options) {
- if(!that.pragmas_implemented[pragma]) {
- throw({message:
- "This implementation of mustache doesn't understand the '" +
- pragma + "' pragma"});
- }
- that.pragmas[pragma] = {};
- if(options) {
- var opts = options.split("=");
- that.pragmas[pragma][opts[0]] = opts[1];
- }
- return "";
- // ignore unknown pragmas silently
- });
- },
- /*
- Tries to find a partial in the curent scope and render it
- */
- render_partial: function(name, context, partials) {
- name = this.trim(name);
- if(!partials || partials[name] === undefined) {
- throw({message: "unknown_partial '" + name + "'"});
- }
- if(typeof(context[name]) != "object") {
- return this.render(partials[name], context, partials, true);
- }
- return this.render(partials[name], context[name], partials, true);
- },
- /*
- Renders inverted (^) and normal (#) sections
- */
- render_section: function(template, context, partials) {
- if(!this.includes("#", template) && !this.includes("^", template)) {
- // did not render anything, there were no sections
- return false;
- }
- var that = this;
- var regex = this.getCachedRegex("render_section", function(otag, ctag) {
- // This regex matches _the first_ section ({{#foo}}{{/foo}}), and captures the remainder
- return new RegExp(
- "^([\\s\\S]*?)" + // all the crap at the beginning that is not {{*}} ($1)
- otag + // {{
- "(\\^|\\#)\\s*(.+)\\s*" + // #foo (# == $2, foo == $3)
- ctag + // }}
- "\n*([\\s\\S]*?)" + // between the tag ($2). leading newlines are dropped
- otag + // {{
- "\\/\\s*\\3\\s*" + // /foo (backreference to the opening tag).
- ctag + // }}
- "\\s*([\\s\\S]*)$", // everything else in the string ($4). leading whitespace is dropped.
- "g");
- });
- // for each {{#foo}}{{/foo}} section do...
- return template.replace(regex, function(match, before, type, name, content, after) {
- // before contains only tags, no sections
- var renderedBefore = before ? that.render_tags(before, context, partials, true) : "",
- // after may contain both sections and tags, so use full rendering function
- renderedAfter = after ? that.render(after, context, partials, true) : "",
- // will be computed below
- renderedContent,
- value = that.find(name, context);
- if (type === "^") { // inverted section
- if (!value || that.is_array(value) && value.length === 0) {
- // false or empty list, render it
- renderedContent = that.render(content, context, partials, true);
- } else {
- renderedContent = "";
- }
- } else if (type === "#") { // normal section
- if (that.is_array(value)) { // Enumerable, Let's loop!
- renderedContent = that.map(value, function(row) {
- return that.render(content, that.create_context(row), partials, true);
- }).join("");
- } else if (that.is_object(value)) { // Object, Use it as subcontext!
- renderedContent = that.render(content, that.create_context(value),
- partials, true);
- } else if (typeof value === "function") {
- // higher order section
- renderedContent = value.call(context, content, function(text) {
- return that.render(text, context, partials, true);
- });
- } else if (value) { // boolean section
- renderedContent = that.render(content, context, partials, true);
- } else {
- renderedContent = "";
- }
- }
- return renderedBefore + renderedContent + renderedAfter;
- });
- },
- /*
- Replace {{foo}} and friends with values from our view
- */
- render_tags: function(template, context, partials, in_recursion) {
- // tit for tat
- var that = this;
- var new_regex = function() {
- return that.getCachedRegex("render_tags", function(otag, ctag) {
- return new RegExp(otag + "(=|!|>|\\{|%)?([^\\/#\\^]+?)\\1?" + ctag + "+", "g");
- });
- };
- var regex = new_regex();
- var tag_replace_callback = function(match, operator, name) {
- switch(operator) {
- case "!": // ignore comments
- return "";
- case "=": // set new delimiters, rebuild the replace regexp
- that.set_delimiters(name);
- regex = new_regex();
- return "";
- case ">": // render partial
- return that.render_partial(name, context, partials);
- case "{": // the triple mustache is unescaped
- return that.find(name, context);
- default: // escape the value
- return that.escape(that.find(name, context));
- }
- };
- var lines = template.split("\n");
- for(var i = 0; i < lines.length; i++) {
- lines[i] = lines[i].replace(regex, tag_replace_callback, this);
- if(!in_recursion) {
- this.send(lines[i]);
- }
- }
- if(in_recursion) {
- return lines.join("\n");
- }
- },
- set_delimiters: function(delimiters) {
- var dels = delimiters.split(" ");
- this.otag = this.escape_regex(dels[0]);
- this.ctag = this.escape_regex(dels[1]);
- },
- escape_regex: function(text) {
- // thank you Simon Willison
- if(!arguments.callee.sRE) {
- var specials = [
- '/', '.', '*', '+', '?', '|',
- '(', ')', '[', ']', '{', '}', '\\'
- ];
- arguments.callee.sRE = new RegExp(
- '(\\' + specials.join('|\\') + ')', 'g'
- );
- }
- return text.replace(arguments.callee.sRE, '\\$1');
- },
- /*
- find `name` in current `context`. That is find me a value
- from the view object
- */
- find: function(name, context) {
- name = this.trim(name);
- // Checks whether a value is thruthy or false or 0
- function is_kinda_truthy(bool) {
- return bool === false || bool === 0 || bool;
- }
- var value;
- // check for dot notation eg. foo.bar
- if(name.match(/([a-z_]+)\./ig)){
- var childValue = this.walk_context(name, context);
- if(is_kinda_truthy(childValue)) {
- value = childValue;
- }
- }
- else{
- if(is_kinda_truthy(context[name])) {
- value = context[name];
- } else if(is_kinda_truthy(this.context[name])) {
- value = this.context[name];
- }
- }
- if(typeof value === "function") {
- return value.apply(context);
- }
- if(value !== undefined) {
- return value;
- }
- // silently ignore unkown variables
- return "";
- },
- walk_context: function(name, context){
- var path = name.split('.');
- // if the var doesn't exist in current context, check the top level context
- var value_context = (context[path[0]] != undefined) ? context : this.context;
- var value = value_context[path.shift()];
- while(value != undefined && path.length > 0){
- value_context = value;
- value = value[path.shift()];
- }
- // if the value is a function, call it, binding the correct context
- if(typeof value === "function") {
- return value.apply(val…
Large files files are truncated, but you can click here to view the full file