Skip to content

Instantly share code, notes, and snippets.

@bdensmore
Created September 7, 2013 18:05
Show Gist options
  • Save bdensmore/6477794 to your computer and use it in GitHub Desktop.
Save bdensmore/6477794 to your computer and use it in GitHub Desktop.
File Uploader using cloudinary API and JQuery fileUpload plugin
<script type="text/javascript">
// Constants for urls
PHOTO_URL = '/buildingtourphotos';
FLOORPLAN_URL = '/buildingtourfloorplans';
DOCS_URL = '/buildingtourdocs';
function file_props(file_data) {
controller_url = {
'image': {url: PHOTO_URL, obj_name: "photo", data_obj: {
buildingtourphoto: {
building_tour_id: $('#buildingtourphoto_id').val(),
name: $('#buildingtourphoto_name').val(),
photo: 'image/upload/' + file_data.result.path + '#' + file_data.result.signature,
lltoken: $('#buildingtourphoto_lltoken').val()
},
file: file_data.files[0].name }
},
'pdf': {url: FLOORPLAN_URL, obj_name: "floorplan", data_obj: {
buildingtourfloorplan: {
building_tour_id: $('#buildingtourphoto_id').val(),
name: $('#buildingtourphoto_name').val(),
floorplan: 'image/upload/' + file_data.result.path + '#' + file_data.result.signature,
lltoken: $('#buildingtourphoto_lltoken').val()
},
file: file_data.files[0].name }
},
'application/msword': {url: DOCS_URL, obj_name: "doc", data_obj: {
buildingtourdoc: {
building_tour_id: $('#buildingtourphoto_id').val(),
name: $('#buildingtourphoto_name').val(),
doc: 'raw/upload/' + file_data.result.path + '#' + file_data.result.signature,
lltoken: $('#buildingtourphoto_lltoken').val()
},
file: file_data.files[0].name }
},
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': {url: DOCS_URL, obj_name: "doc", data_obj: {
buildingtourdoc: {
building_tour_id: $('#buildingtourphoto_id').val(),
name: $('#buildingtourphoto_name').val(),
doc: 'raw/upload/' + file_data.result.path + '#' + file_data.result.signature,
lltoken: $('#buildingtourphoto_lltoken').val()
},
file: file_data.files[0].name }
},
'application/vnd.ms-excel': {url: DOCS_URL, obj_name: "doc", data_obj: {
buildingtourdoc: {
building_tour_id: $('#buildingtourphoto_id').val(),
name: $('#buildingtourphoto_name').val(),
doc: 'raw/upload/' + file_data.result.path + '#' + file_data.result.signature,
lltoken: $('#buildingtourphoto_lltoken').val()
},
file: file_data.files[0].name }
},
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': {url: DOCS_URL, obj_name: "doc", data_obj: {
buildingtourdoc: {
building_tour_id: $('#buildingtourphoto_id').val(),
name: $('#buildingtourphoto_name').val(),
doc: 'raw/upload/' + file_data.result.path + '#' + file_data.result.signature,
lltoken: $('#buildingtourphoto_lltoken').val()
},
file: file_data.files[0].name }
},
'application/vnd.ms-powerpoint': {url: DOCS_URL, obj_name: "doc" , data_obj: {
buildingtourdoc: {
building_tour_id: $('#buildingtourphoto_id').val(),
name: $('#buildingtourphoto_name').val(),
doc: 'raw/upload/' + file_data.result.path + '#' + file_data.result.signature,
lltoken: $('#buildingtourphoto_lltoken').val()
},
file: file_data.files[0].name }
},
'application/vnd.openxmlformats-officedocument.presentationml.presentation': {url: DOCS_URL, obj_name: "doc" , data_obj: {
buildingtourdoc: {
building_tour_id: $('#buildingtourphoto_id').val(),
name: $('#buildingtourphoto_name').val(),
doc: 'raw/upload/' + file_data.result.path + '#' + file_data.result.signature,
lltoken: $('#buildingtourphoto_lltoken').val()
},
file: file_data.files[0].name }
},
'application/vnd.openxmlformats-officedocument.presentationml.slideshow': {url: DOCS_URL, obj_name: "doc" , data_obj: {
buildingtourdoc: {
building_tour_id: $('#buildingtourphoto_id').val(),
name: $('#buildingtourphoto_name').val(),
doc: 'raw/upload/' + file_data.result.path + '#' + file_data.result.signature,
lltoken: $('#buildingtourphoto_lltoken').val()
},
file: file_data.files[0].name }
},
'text/rtf': {url: DOCS_URL, obj_name: "doc", data_obj: {
buildingtourdoc: {
building_tour_id: $('#buildingtourphoto_id').val(),
name: $('#buildingtourphoto_name').val(),
doc: 'raw/upload/' + file_data.result.path + '#' + file_data.result.signature,
lltoken: $('#buildingtourphoto_lltoken').val()
},
file: file_data.files[0].name }
},
'raw': {url: DOCS_URL, obj_name: "doc", data_obj: {
buildingtourdoc: {
building_tour_id: $('#buildingtourphoto_id').val(),
name: $('#buildingtourphoto_name').val(),
doc: 'raw/upload/' + file_data.result.path + '#' + file_data.result.signature,
lltoken: $('#buildingtourphoto_lltoken').val()
},
file: file_data.files[0].name }
}
};
if ( file_data.files[0].type ) {
if ( file_data.files[0].type.split('/')[0] == 'image' ) {
type = 'image';
}
else if( file_data.files[0].type.split('/')[1] == 'pdf' ) {
type = 'pdf';
}
else {
type = file_data.files[0].type;
}
}
else {
if ( file_data._response.result.resource_type == 'raw' ) {
type = 'raw';
}
else if ( file_data._response.result.format == 'pdf' ) {
type = 'pdf';
}
else if ( file_data._response.result.resource_type == 'image' ) {
type = file_data._response.result.resource_type;
}
}
props = {
c_url: controller_url[type].url,
obj_name: controller_url[type].obj_name,
data_obj: controller_url[type].data_obj
};
return props;
}
function save_file_to_tour(file_data) {
props = file_props(file_data)
$.ajax({
url: props.c_url,
type: 'POST',
data: props.data_obj,
success: function(e) {
files_uploaded = files_uploaded + 1
if ( files_uploaded == file_count ) {
if ( window.location.href.indexOf('?') > 0 ) {
url = window.location.href;
} else {
url = window.location.href + '?upload_complete=true';
}
window.location.href = url;
}
},
fail: function(e) {
console.log("failed");
console.log(e);
}
})
}
</script>
# == Schema Information
#
# Table name: building_tours
#
# id :integer not null, primary key
# tour_id :integer
# building_id :integer
# notes :text
# created_at :datetime not null
# updated_at :datetime not null
# position :integer
# suites :string(255)
# sqft :integer
# rentalrate :decimal(6, 2)
# monthly :decimal(9, 2)
#
class BuildingTour < ActiveRecord::Base
attr_accessible :building_id, :notes, :tour_id, :suites, :sqft, :rentalrate, :monthly, :groupscore, :hidden, :custom1, :custom1_label, :custom2, :custom2_label, :custom3, :custom3_label, :custom4, :custom4_label, :custom5, :custom5_label, :custom6, :custom6_label, :custom7, :custom7_label, :custom8, :custom8_label, :lltokendate, :llsend, :description
after_initialize :get_monthly
after_initialize :get_groupscore
before_save :set_monthly
before_save :set_groupscore
belongs_to :building
belongs_to :tour
has_many :buildingtourphotos, :dependent => :destroy
has_many :buildingtourdocs, :dependent => :destroy
has_many :buildingtourfloorplans, :dependent => :destroy
has_one :marker_color
def get_monthly
if !self.monthly
self.save
end
end
def set_monthly
if self.tour.lp == 2
if sqft && rentalrate
self.monthly = sqft * rentalrate
end
else
if sqft && rentalrate
self.monthly = (sqft * rentalrate) / 12
end
end
end
letsrate_rateable "rating1", "rating2", "rating3", "rating4", "rating5", "rating6", "rating7", "rating8"
def get_groupscore
if !self.groupscore
self.save
end
end
def set_groupscore
total = 0
for score in RatingCache.find_all_by_cacheable_id(self.id)
total += score.avg
end
total = total / 8.0
total = total * 1.67
self.groupscore = total.round(1)
end
def next
bt = tour.buildingTours.where("position > ? AND hidden = ?", position, hidden).order("position").first
if !bt
bt = tour.buildingTours.where(hidden:hidden).order("position").first
end
return bt
end
def prev
bt = tour.buildingTours.where("position < ? AND hidden = ?", position, hidden).order("position DESC").first
if !bt
bt = tour.buildingTours.where(hidden:hidden).order("position DESC").first
end
return bt
end
def marker_color_values
if self.marker_color.nil?
['fe8176','000000']
else
[self.marker_color.color,self.marker_color.text_color]
end
end
def has_marker_color?
!self.marker_color.nil?
end
end
class BuildingToursController < ApplicationController
include NumberHelper
before_filter :signed_in_user, except: [:llportal, :lldone]
before_filter :owner_acct_or_admin, only: [:destroy, :new, :create, :edit, :update, :hide, :unhide]
before_filter :member_manager_or_admin, only: [:index, :show]
before_filter :valid_token, only: [:llportal]
def show
@buildingTour = BuildingTour.find(params[:id])
@tour = @buildingTour.tour
if @tour.account
@template = true
else
@template = false
end
if params[:upload_complete]
flash[:notice] = "File(s) uploaded succesfully."
end
if tm = @tour.tourmemberships.find_by_owner(true)
owner = tm.user
if account = owner.account
if (account == current_user.account) || current_user.admin?
@owner = true
else
@owner = false
end
else
if (owner == current_user) || current_user.admin?
@owner = true
else
@owner = false
end
end
else
if current_user.manager? || current_user.admin? || (current_user.account && (@tour.account == current_user.account))
@owner = true
else
@owner = false
end
end
end
def llportal
@tour = @buildingTour.tour
@llportal = true
if params[:upload_complete]
flash[:notice] = "File(s) uploaded succesfully."
end
end
def lldone
require 'rest_client'
buildingTour = BuildingTour.find(params[:id])
buildingTour.lltoken = nil
buildingTour.save
tour = buildingTour.tour
email = tour.tourmemberships.find_by_owner(true).user.email
subject = "Landlord Broker has finished uploading information for " + buildingTour.building.address
body = "The Landlord Broker has finished uploading information for " + buildingTour.building.address + " for " + tour.name + ".\n\nThanks for using Ten Eight!\n\nSincerely,\n\nTen Eight Management"
RestClient.post MAILGUN_API_URL+"/messages", :from => "Ten Eight Exchange <noreply@teneight.mailgun.org>", :to => email, :subject => subject, :text => body
redirect_to root_path, notice: "The Tenant Rep Broker has been notified that you completed uploading building information."
end
def index
end
def create
end
def edit
@buildingTour = BuildingTour.find(params[:id])
end
def update
@buildingTour = BuildingTour.find(params[:id])
respond_to do |format|
if params[:building_tour][:sqft]
params[:building_tour][:sqft] = params[:building_tour][:sqft].to_s.gsub(/[^\d\.]/, '')
elsif params[:building_tour][:rentalrate]
params[:building_tour][:rentalrate] = params[:building_tour][:rentalrate] .to_s.gsub(/[^\d\.]/, '')
end
if @buildingTour.update_attributes(params[:building_tour])
if params[:building_tour][:sqft]
display_as = display_with_delimiter(@buildingTour.sqft)
format.json {
render :json => {
:display_as => display_as,
:monthly => convert_to_currency(@buildingTour.monthly, 0),
:rate => convert_to_currency(@buildingTour.rentalrate)
}
}
elsif params[:building_tour][:rentalrate]
display_as = convert_to_currency(@buildingTour.rentalrate)
format.json {
render :json => {
:display_as => display_as,
:monthly => convert_to_currency(@buildingTour.monthly, 0),
:rate => convert_to_currency(@buildingTour.rentalrate)
}
}
else
format.json { respond_with_bip(@buildingTour) }
end
else
format.json { respond_with_bip(@buildingTour) }
end
end
end
def hide
tour = Tour.find(params[:tour_id])
BuildingTour.update_all(
[
"hidden = ?, position = ?",
true, tour.buildingTours.maximum("position") + 1000
],
id: params[:id]
)
buildingTours = tour.buildingTours.order("position")
hiddencount=0
buildingTours.all.each_with_index do |abt, index|
if abt.hidden?
hiddencount+=1
else
abt.position=index+1-hiddencount
abt.save
end
end
params[:id]
flash[:success] = params[:id].count > 1 ? "Buildings archived" : "Building archived"
render nothing: true
#redirect_to tour
end
def unhide
tour = Tour.find(params[:tour_id])
id_arr = params[:id]
id_arr.each do |id|
bt = BuildingTour.find(id)
bt.hidden = false
if activecount = tour.buildingTours.where(hidden: false).count
bt.position = activecount + 1
else
bt.position = 1
end
bt.save
end
flash[:success] = id_arr.count > 1 ? "Buildings are now active." : "Building is now active."
render nothing: true
end
def destroy
tour = Tour.find(params[:tour_id])
id_arr = params[:id]
id_arr.each do |id|
buildingTour = BuildingTour.find(id)
hidden = buildingTour.hidden
buildingTour.destroy
end
buildingTours = tour.buildingTours.order("position")
buildingTours.all.each_with_index do |abt, index|
abt.position=index+1
abt.save
end
flash[:success] = id_arr.count > 1 ? "Buildings removed from tour." : "Building removed from tour."
render nothing: true
end
def compare
@tour = Tour.find(params[:tour_id])
@building_tours = BuildingTour.where(id: params[:id].split(',')).order("position asc")
if tm = @tour.tourmemberships.find_by_owner(true)
owner = tm.user
if account = owner.account
if (account == current_user.account) || current_user.admin?
@owner = true
else
@owner = false
end
else
if (owner == current_user) || current_user.admin?
@owner = true
else
@owner = false
end
end
else
if current_user.manager? || current_user.admin? || (current_user.account && (@tour.account == current_user.account))
@owner = true
else
@owner = false
end
end
render layout: false
end
def sort
params[:building_tour].each_with_index do |id, index|
BuildingTour.update_all({position: index+1}, {id: id})
end
render nothing: true
end
def move_building_info
@building_floor_plan = Buildingtourfloorplan.find(params[:building_info_id])
ActiveRecord::Base.transaction do
@building_tour_doc = Buildingtourdoc.find_by_sql(
"INSERT INTO buildingtourdocs(name,doc,building_tour_id,created_at,updated_at)
VALUES(
#{ActiveRecord::Base.connection.quote(@building_floor_plan.name)},
#{ActiveRecord::Base.connection.quote(@building_floor_plan.floorplan.to_s.split('/')[6] + '/' + @building_floor_plan.floorplan.to_s.split('/')[7])},
#{@building_floor_plan.building_tour_id},
#{ActiveRecord::Base.connection.quote(Time.now)},
#{ActiveRecord::Base.connection.quote(Time.now)})"
)
Buildingtourfloorplan.find_by_sql("DELETE FROM buildingtourfloorplans where id = #{@building_floor_plan.id}")
end
render json: {data: Buildingtourdoc.last.id }
end
def move_dealdoc
@deal_doc = Buildingtourdoc.find(params[:building_info_id])
ActiveRecord::Base.transaction do
@building_tour_floorplan = Buildingtourfloorplan.find_by_sql(
"INSERT INTO buildingtourfloorplans(name,floorplan,building_tour_id,created_at,updated_at)
VALUES(
#{ActiveRecord::Base.connection.quote(@deal_doc.name)},
#{ActiveRecord::Base.connection.quote(@deal_doc.doc.to_s.split('/')[6] + '/' + @deal_doc.doc.to_s.split('/')[7])},
#{@deal_doc.building_tour_id},
#{ActiveRecord::Base.connection.quote(Time.now)},
#{ActiveRecord::Base.connection.quote(Time.now)})"
)
Buildingtourdoc.find_by_sql("DELETE FROM buildingtourdocs where id = #{@deal_doc.id}")
end
render json: {data: Buildingtourfloorplan.last.id }
end
def generate_new_cloudinary_signature
api_secret = Cloudinary.config.api_secret
cloudinary_params = Cloudinary::Uploader.build_upload_params(params)
cloudinary_params[:transformation] = ""
cloudinary_params[:callback] = params[:callback]
cloudinary_params[:signature] = Cloudinary::Utils.api_sign_request(cloudinary_params, api_secret)
cloudinary_params[:api_key] = Cloudinary.config.api_key
render json: { cloudinary_params: cloudinary_params.reject{|k, v| v.blank?} }
end
private
def signed_in_user
unless valid_token
unless signed_in?
store_location
redirect_to signin_path, notice: "Please sign in." unless signed_in?
end
end
end
def owner_acct_or_admin
unless valid_token
if params[:id].kind_of?(Array)
id_arr = params[:id]
id_arr.each do |id|
buildingTour = BuildingTour.find(id)
tour = buildingTour.tour
unless current_user.account && (tour.account == current_user.account)
owner = tour.tourmemberships.find_by_owner(true).user
if account = owner.account
unless (account == current_user.account) || current_user.admin?
flash[:notice] = "You must be on the same Enterprise Account to perform this action."
redirect_to building_tour_path(buildingTour)
end
else
unless (owner == current_user) || current_user.admin?
flash[:notice] = "You must own this tour to perform this action."
redirect_to building_tour_path(buildingTour)
end
end
end
end
else
buildingTour = BuildingTour.find(params[:id])
tour = buildingTour.tour
unless current_user.account && (tour.account == current_user.account)
owner = tour.tourmemberships.find_by_owner(true).user
if account = owner.account
unless (account == current_user.account) || current_user.admin?
flash[:notice] = "You must be on the same Enterprise Account to perform this action."
redirect_to building_tour_path(buildingTour)
end
else
unless (owner == current_user) || current_user.admin?
flash[:notice] = "You must own this tour to perform this action."
redirect_to building_tour_path(buildingTour)
end
end
end
end
end
end
def member_manager_or_admin
buildingTour = BuildingTour.find(params[:id])
tour = buildingTour.tour
unless current_user.tours.find_by_id(tour.id) || current_user.admin? || (current_user.manager? && tour.users.find_by_account_id(current_user.account)) || (current_user.account && (tour.account == current_user.account))
flash[:notice] = "You are not a member of this tour."
redirect_to tours_path
end
end
def valid_token
@lltoken = params[:lltoken]
if @lltoken
@buildingTour = BuildingTour.find(params[:id])
if @lltoken == @buildingTour.lltoken && ((Time.now - @buildingTour.lltokendate) < TOKEN_EXPIRE)
return true
else
flash[:notice] = "This link has expired"
redirect_to root_path
end
else
return false
end
end
end
<script type="text/javascript">
$(document).ready(function() {
$(".c-upload").fileupload({
acceptFileTypes: /(\.|\/)(gif|jpe?g|png|pdf|tif|tiff|doc|docx|xls|xlsx|ppt|pptx|pps|ppsx|rtf)$/i,
autoUpload: true,
maxFileSize: 52428800,
dropZone: '#file-uploads',
start: function(e, data) {
$('#progress-window').dialog({
modal:true,
width: 400,
height: 250,
position: 'center'
});
$(".ui-dialog-titlebar").hide();
}
})
.on('fileuploadadd', function(e, data) {
data.contexts = $('<li>').appendTo('.preview');
d = new Date();
progress_id = d.getTime();
$.each(data.files, function(index, file) {
<% if browser.ie9? %>
if ( !/(jp?g|png|gif)/.test(file.name.split(".").pop().toLowerCase()) ) {
<% else %>
if ( file.type.split("/")[0] !== "image" ) {
<% end %>
form_data = $('.c-upload').data('form-data');
delete form_data['format'];
<% if browser.ie9? %>
if ( file.name.split(".").pop().toLowerCase() == "pdf" ) {
<% else %>
if ( file.type.split("/")[1] == "pdf" ) {
<% end %>
form_data['tags'] = '#floorplan';
} else {
form_data['tags'] = '#doc';
}
if ( $('#buildingtourphoto_lltoken').val() !== "" ) {
form_data['lltoken'] = $('#buildingtourphoto_lltoken').val();
form_data['id'] = $('#buildingtourphoto_id').val();
}
signature = generate_signature(form_data);
resp = signature.responseJSON['cloudinary_params'];
$('.c-upload').attr('data-form-data', create_form_data(resp));
data.formData = resp;
}
file_count = file_count + 1;
node = $('<div id="photo-progress_' + progress_id +
'" class="photo-progress"><div class="bar" style="width:0%;"></div></div><p><span>' + file.name +
'</span></p></li>');
node.appendTo(data.contexts);
});
})
.on('fileuploadprogress', function(e, data) {
progress = parseInt(data.loaded / data.total * 100, 10);
$('#' + data.contexts[0].firstChild.id + '.photo-progress .bar').css('width', progress + '%');
})
.on('fileuploadprocessfail', function(e, data) {
file_count = file_count - 1;
$('<div class="error">' + data.files[0].error + '! File was not saved!</div>').prependTo($('#' + data.contexts[0].firstChild.id).parent());
})
.on('cloudinarydone', function(e, data) {
save_file_to_tour(data);
});
$('.sortable-section').sortable({
cursor: 'move',
helper: 'clone',
start: function(event, ui) {
start_pos = ui.item.index() + 1;
},
stop: function(event, ui) {
end_pos = ui.item.index() + 1;
sort_update(ui, start_pos, end_pos, $(this), $(this).data('url'));
}
}).disableSelection();
$('#floorplans, #docs').sortable({
cursor: 'move',
helper: 'clone',
connectWith: '.connectable',
out: function(event, ui) {
$(this).removeClass('ui-state-highlight');
$(this).height(( (Math.ceil($(this).children().size() / 4) * 175) ) + 'px');
},
over: function(event, ui) {
$(this).addClass('ui-state-highlight');
$('#' + this.id ).height( ( (Math.ceil($('#' + this.id).children().size() / 4) * 175) + 10 ) + 'px');
},
start: function(event, ui) {
cancelStop = false;
url = $(this).data('url');
start_pos = ui.item.index() + 1;
},
receive: function(event, ui) {
if ( $(ui.sender)[0].id === 'docs' && $(ui.item).data('file-ext') !== 'pdf' ) {
$(ui.sender).sortable('cancel');
setTimeout(function() { $(ui.item).popover('hide') }, 3000);
$(ui.item).popover({
placement: 'top',
html: true,
content: '<p class="error">Only PDFs can be moved into Building Info</p>',
title: "<h6>This file can't be moved into Building Info</h6>"
});
$(ui.item).popover('show');
cancelStop = true;
} else {
url = $(this).data('url');
if ( $('#buildingtourphoto_lltoken').val() === "" ) {
data = { building_info_id: ui.item[0].id }
} else {
data = {
building_info_id: ui.item[0].id,
lltoken: $('#buildingtourphoto_lltoken').val(),
id: $('#buildingtourphoto_id').val()
}
}
$.post($(this).data('update_url'),
data
)
.done( function(e) {
ui.item.attr('id', e.data );
best_in_place = ui.item.find('.best_in_place');
remove_link = ui.item.find('.actions a');
main_link = "buildingtour" + $(ui.item).parent()[0].id;
cloned_bip = $(best_in_place).clone();
$(best_in_place).remove();
if ( $('#buildingtourphoto_lltoken').val() === "" ) {
$(cloned_bip).attr('data-url', '/' + main_link + '/' + e.data);
} else {
$(cloned_bip).attr('data-url', '/' + main_link + '/' + e.data + "?lltoken=" + $('#buildingtourphoto_lltoken').val() + "&btid=" + $('#buildingtourphoto_id').val());
}
$(cloned_bip).attr('data-object', main_link.slice(0, main_link.length -1 ));
$(cloned_bip).attr('id', 'best_in_place_' + main_link.slice(0, main_link.length -1 ) + '_' + e.data + '_name');
ui.item.find('.name').append($(cloned_bip));
$(remove_link).attr('href', '/' + main_link + '/' + e.data);
});
$('#' + this.id + '_toggle').find('small').text('(' + ($(ui.item).parent().children().length) + ')' );
cancelStop = false;
}
},
stop: function(event, ui) {
if ( !cancelStop ) {
end_pos = ui.item.index() + 1;
if ( this.id !== $(ui.item).parent()[0].id ) {
$('#' + this.id + '_toggle').find('small').text('(' + this.children.length + ')' );
setTimeout(
function() {
sort_update( $(ui.item).parent(), start_pos, end_pos, $(ui.item).parent(), url)
},
500
);
} else {
sort_update(ui, start_pos, end_pos, $(this), url);
}
}
$(this).height(( (Math.ceil($(this).children().size() / 4) * 175) ) + 'px');
}
}).disableSelection();
});
$(document).bind('dragover', function (e) {
var dropZone = $('#file-uploads'),
timeout = window.dropZoneTimeout;
if (!timeout) {
dropZone.addClass('in');
} else {
clearTimeout(timeout);
}
var found = false,
node = e.target;
do {
if (node === dropZone[0]) {
found = true;
break;
}
node = node.parentNode;
} while (node != null);
if (found) {
dropZone.addClass('hover');
} else {
dropZone.removeClass('hover');
}
window.dropZoneTimeout = setTimeout(function () {
window.dropZoneTimeout = null;
dropZone.removeClass('in hover');
}, 100);
});
file_count = 0
files_uploaded = 0
function sort_update(ui, start_pos, end_pos, sort_array, url) {
items = sort_array.sortable('toArray');
if ( typeof items !== 'undefined' ) {
updated_sort = [];
$.each(items, function(i, c) {
updated_sort.push(
{
id: c,
elem_position: i
}
);
});
$.post(url,
{
data: updated_sort,
btid: $('#buildingtourphoto_id').val(),
lltoken: $('#buildingtourphoto_lltoken').val()
}
);
}
}
function create_form_data(data2) {
var data = '{';
$.each(data2, function(key,val) {
data += '"' + key + '":"' + val +'",';
});
return data.substring(0,data.length - 1) + '}';
}
function generate_signature(data) {
return $.ajax({
url: '/generate_new_cloudinary_signature',
type: 'POST',
data: data,
async: false
});
}
</script>
<% provide(:title, @buildingTour.building.address) %>
<% if @tour.name.last(4).downcase == "tour" %>
<% fullname = (@tour.client || "") + " " + @tour.name %>
<% else %>
<% fullname = (@tour.client || "") + " " + @tour.name + " Tour" %>
<% end %>
<%= cloudinary_js_config %>
<ul class="breadcrumb">
<% unless @template %>
<li><%= link_to "Tours", tours_path %>
<span class="divider">/</span></li>
<% else %>
<li><%= link_to "Templates", tours_path(:templates => true) %><span class="divider">/</span></li>
<% end %>
<li><%= link_to fullname, tour_path(@buildingTour.tour) %><span class="divider">/</span></li>
<% unless @buildingTour.building.name.blank? %>
<li class="active"> <%= @buildingTour.building.name %></li>
<% else %>
<li class="active"> <%= @buildingTour.building.address %></li>
<% end %>
<span style="float:right;">
<%= link_to("Previous", @buildingTour.prev) %>
|
<%= link_to("Next", @buildingTour.next) %>
</span>
</ul>
<div class="row">
<aside class="span4" id="buildingtour-left">
<section>
<h1>
<small><%= @buildingTour.position %>)
</small>
<% unless @buildingTour.building.name.blank? %>
<%= @buildingTour.building.name %>
</h1>
<div class="building-info">
<%= @buildingTour.building.address %><br>
<% else %>
<%= @buildingTour.building.address %>
</h1>
<div class="building-info">
<% end %>
<%= @buildingTour.building.city %> <%= @buildingTour.building.zip %><br>
Suite(s): <%= best_in_place_if @owner, @buildingTour, :suites, :type => :input, :nil => "Click to add Suite(s)" %>
<br>
Description:
<%= best_in_place_if @owner, @buildingTour, :description, :nil => "Click to add Description" %>
</div>
</section>
<section id="mainphoto">
<% if photo=@buildingTour.buildingtourphotos.order("position").first %>
<%= link_to image_tag(photo.photo_url(:small).to_s), photo.photo_url, :rel => "prettyPhoto[pp_gal]", :title => photo.name %>
<div class="actions">
<%= link_to "remove", photo, :confirm => "Are you sure?", :method => :delete %>
</div>
<% else %>
<%= image_tag("http://res.cloudinary.com/hoskloe8r/image/upload/w_200,h_200,c_limit/097_urhjm2.jpg", :title => "default image") %>
<% end %>
</section>
<section id="rentalsection">
<div class="span2" id="rental">
<% if @buildingTour.tour.lp == 2 %>
SF:<br>
Rate:<br>
Price:
<% else %>
RSF:<br>
Rate:<br>
Monthly:
<% end %>
</div>
<div class="span1" id="rental-details-<%= @buildingTour.id %>">
<%= best_in_place_if @owner, @buildingTour, :sqft, :type => :input, :nil => "Add", :display_with => :number_with_delimiter, :helper_options => { :delimiter => ',' }, :classes => "sqft" %><br>
<%= best_in_place_if @owner, @buildingTour, :rentalrate, :type => :input, :nil => "Add", :display_with => :number_to_currency, :classes => "rental_rate" %><br>
<strong>
<span style="display:inline;" id="monthly_rate"><%= number_to_currency(@buildingTour.monthly, :precision => 0) %></span>
</strong>
</div>
</section>
<section>
<div class="span2" id="rental">
My Score:<br>
Group Score:
</div>
<div class="span1">
<%= current_user.myscore(@buildingTour.id) %>
<br>
<%= @buildingTour.groupscore %>
</div>
</section>
<section>
<% @tourtype = @buildingTour.tour.tourtype %>
<div class="span2" id="rental">
<% if @owner %>
<%= best_in_place @buildingTour, :custom1_label, :type => :input, :nil => SPECS[@tourtype - 1][0] %>:<br>
<%= best_in_place @buildingTour, :custom2_label, :type => :input, :nil => SPECS[@tourtype - 1][1] %>:<br>
<%= best_in_place @buildingTour, :custom3_label, :type => :input, :nil => SPECS[@tourtype - 1][2] %>:<br>
<%= best_in_place @buildingTour, :custom4_label, :type => :input, :nil => SPECS[@tourtype - 1][3] %>:<br>
<%= best_in_place @buildingTour, :custom5_label, :type => :input, :nil => SPECS[@tourtype - 1][4] %>:<br>
<%= best_in_place @buildingTour, :custom6_label, :type => :input, :nil => SPECS[@tourtype - 1][5] %>:<br>
<%= best_in_place @buildingTour, :custom7_label, :type => :input, :nil => SPECS[@tourtype - 1][6] %>:<br>
<%= best_in_place @buildingTour, :custom8_label, :type => :input, :nil => SPECS[@tourtype - 1][7] %>:
<% else %>
<% if @buildingTour.custom1_label.blank? %>
<%= SPECS[@tourtype - 1][0] %>:<br>
<% else %>
<%= @buildingTour.custom1_label %>:<br>
<% end %>
<% if @buildingTour.custom2_label.blank? %>
<%= SPECS[@tourtype - 1][1] %>:<br>
<% else %>
<%= @buildingTour.custom2_label %>:<br>
<% end %>
<% if @buildingTour.custom3_label.blank? %>
<%= SPECS[@tourtype - 1][2] %>:<br>
<% else %>
<%= @buildingTour.custom3_label %>:<br>
<% end %>
<% if @buildingTour.custom4_label.blank? %>
<%= SPECS[@tourtype - 1][3] %>:<br>
<% else %>
<%= @buildingTour.custom4_label %>:<br>
<% end %>
<% if @buildingTour.custom5_label.blank? %>
<%= SPECS[@tourtype - 1][4] %>:<br>
<% else %>
<%= @buildingTour.custom5_label %>:<br>
<% end %>
<% if @buildingTour.custom6_label.blank? %>
<%= SPECS[@tourtype - 1][5] %>:<br>
<% else %>
<%= @buildingTour.custom6_label %>:<br>
<% end %>
<% if @buildingTour.custom7_label.blank? %>
<%= SPECS[@tourtype - 1][6] %>:<br>
<% else %>
<%= @buildingTour.custom7_label %>:<br>
<% end %>
<% if @buildingTour.custom8_label.blank? %>
<%= SPECS[@tourtype - 1][7] %>:
<% else %>
<%= @buildingTour.custom8_label %>:
<% end %>
<% end %>
</div>
<div class="span1" style="width:120px;">
<%= best_in_place_if @owner, @buildingTour, :custom1, :type => :input, :nil => "Add" %><br>
<%= best_in_place_if @owner, @buildingTour, :custom2, :type => :input, :nil => "Add" %><br>
<%= best_in_place_if @owner, @buildingTour, :custom3, :type => :input, :nil => "Add" %><br>
<%= best_in_place_if @owner, @buildingTour, :custom4, :type => :input, :nil => "Add" %><br>
<%= best_in_place_if @owner, @buildingTour, :custom5, :type => :input, :nil => "Add" %><br>
<%= best_in_place_if @owner, @buildingTour, :custom6, :type => :input, :nil => "Add" %><br>
<%= best_in_place_if @owner, @buildingTour, :custom7, :type => :input, :nil => "Add" %><br>
<%= best_in_place_if @owner, @buildingTour, :custom8, :type => :input, :nil => "Add" %>
</div>
</aside>
<div class="span8" id="buildingtour-main">
<% photoscount = 0 %>
<% photoscount=(@buildingTour.buildingtourphotos.count - 1) unless @buildingTour.buildingtourphotos.count == 0 %>
<div id="file-upload-btn">
<%= link_to('javascript:void(0);', id: 'file-upload_toggle', class: 'btn btn-success') do %>
Add Files/Photos <i class="icon-plus icon-white"></i>
<% end %>
</div>
<br>
<%= render partial: '/shared/file_upload',
locals: { id: @buildingTour.id } %>
<h3><span id="photos_toggle">Photos <small>(<%=photoscount%>)</small></span></h3>
<ul id="photos" class="sortable-section" data-url="/update_photo_positions">
<% for photo in @buildingTour.buildingtourphotos.order("position") %>
<% unless photo == @buildingTour.buildingtourphotos.order("position").first %>
<li class="span2" id="<%= photo.id %>">
<%= link_to image_tag(photo.photo_url(:thumb).to_s), photo.photo_url, :rel => "prettyPhoto[pp_gal]", :title => photo.name %>
<div class="name">
<%= best_in_place photo, :name, :type => :input,
:display_with => lambda { |v| truncate(v, length: 23).html_safe } %>
</div>
<div class="actions">
<%= link_to "main", setmainphoto_path(:btid => @buildingTour.id, :pid => photo.id) %>
<span class="actions-right">
<%= link_to "remove", photo, :confirm => "Are you sure?", :method => :delete %>
</span>
</div>
</li>
<% end %>
<% end %>
</ul>
<div style="clear:both;"></div>
<h3> <span id="floorplans_toggle">Building Information <small>(<%=@buildingTour.buildingtourfloorplans.count%>)</small></span></h3>
<ul id="floorplans" class="connectable" data-url="/update_floorplan_positions" data-update_url="/move_dealdoc">
<% for floorplan in @buildingTour.buildingtourfloorplans.order("position") %>
<% extension = floorplan.floorplan.to_s.last(3) %>
<li class="span2" id="<%= floorplan.id %>" data-file-ext=<%= "#{extension}" %> data-link_name="buildingtourdocs">
<% if extension == "pdf" %>
<%= link_to image_tag(floorplan.floorplan_url(:thumb).to_s), floorplan.floorplan_url, :target => "_blank", :title => floorplan.name %>
<% else %>
<%= link_to image_tag("http://res.cloudinary.com/hoskloe8r/image/upload/v1366037772/docicon_xvknvy.png", size: "140x140"), floorplan.floorplan_url, :target => "_blank", :title => floorplan.name %>
<% end %>
<div class="name">
<%= best_in_place_if @owner, floorplan, :name, :type => :input,
:display_with => lambda { |v| truncate(v, length: 23).html_safe } %>
</div>
<div class="actions">
<%= link_to "remove", floorplan, :confirm => "Are you sure?", :method => :delete %>
</div>
</li>
<% end %>
</ul>
<div style="clear:both;"></div>
<h3><span id="docs_toggle">Deal Docs <small>(<%=@buildingTour.buildingtourdocs.count%>)</small></span></h3>
<ul id="docs" class="connectable" data-url="/update_dealdoc_positions" data-update_url="/move_building_info">
<% for doc in @buildingTour.buildingtourdocs.order("position") %>
<% extension = doc.doc.to_s.last(3) %>
<li class="span2" id="<%= doc.id %>" data-file-ext=<%= "#{extension}" %> data-link_name="buildingtourfloorplans">
<%= doc_icon doc %>
<div class="name">
<%= best_in_place_if @owner, doc, :name, :type => :input,
:display_with => lambda { |v| truncate(v, length: 23).html_safe } %>
</div>
<div class="actions">
<%= link_to "remove", doc, :confirm => "Are you sure?", :method => :delete %>
</div>
</li>
<% end %>
</ul>
<div style="clear:both;"></div>
<br>
<h3 id="notes_toggle">Notes</h3>
<section id="notes">
<%= best_in_place @buildingTour,
:notes,
:type => :textarea,
:nil => "Click to add Notes",
:display_with => lambda { |v| v.gsub(/\n/, '<br>').html_safe },
:classes => "txt_notes"
%>
</section>
<br>
<h3 id="ratings_toggle">Ratings</h3>
<br>
<section id="ratings">
<% if @owner %>
<div class = "span3">
<%= best_in_place @tour, :dimension1_name, :type => :input, :nil => DIMENSIONS[@tourtype - 1][0] %>
<%= rating_for @buildingTour, :rating1, :star => 6, :userid => current_user.id %>
<%= best_in_place @tour, :dimension2_name, :type => :input, :nil => DIMENSIONS[@tourtype - 1][1] %>
<%= rating_for @buildingTour, :rating2, :star => 6, :userid => current_user.id %>
<%= best_in_place @tour, :dimension3_name, :type => :input, :nil => DIMENSIONS[@tourtype - 1][2] %>
<%= rating_for @buildingTour, :rating3, :star => 6, :userid => current_user.id %>
<%= best_in_place @tour, :dimension4_name, :type => :input, :nil => DIMENSIONS[@tourtype - 1][3] %>
<%= rating_for @buildingTour, :rating4, :star => 6, :userid => current_user.id %>
</div>
<div class= "span3">
<%= best_in_place @tour, :dimension5_name, :type => :input, :nil => DIMENSIONS[@tourtype - 1][4] %>
<%= rating_for @buildingTour, :rating5, :star => 6, :userid => current_user.id %>
<%= best_in_place @tour, :dimension6_name, :type => :input, :nil => DIMENSIONS[@tourtype - 1][5] %>
<%= rating_for @buildingTour, :rating6, :star => 6, :userid => current_user.id %>
<%= best_in_place @tour, :dimension7_name, :type => :input, :nil => DIMENSIONS[@tourtype - 1][6] %>
<%= rating_for @buildingTour, :rating7, :star => 6, :userid => current_user.id %>
<%= best_in_place @tour, :dimension8_name, :type => :input, :nil => DIMENSIONS[@tourtype - 1][7] %>
<%= rating_for @buildingTour, :rating8, :star => 6, :userid => current_user.id %>
</div>
<% else %>
<div class = "span3">
<% if @tour.dimension1_name.blank? %>
<%= DIMENSIONS[@tourtype - 1][0] %>
<% else %>
<%= @tour.dimension1_name %>
<% end %>
<%= rating_for @buildingTour, :rating1, :star => 6, :userid => current_user.id %>
<% if @tour.dimension2_name.blank? %>
<%= DIMENSIONS[@tourtype - 1][1] %>
<% else %>
<%= @tour.dimension2_name %>
<% end %>
<%= rating_for @buildingTour, :rating2, :star => 6, :userid => current_user.id %>
<% if @tour.dimension3_name.blank? %>
<%= DIMENSIONS[@tourtype - 1][2] %>
<% else %>
<%= @tour.dimension3_name %>
<% end %>
<%= rating_for @buildingTour, :rating3, :star => 6, :userid => current_user.id %>
<% if @tour.dimension4_name.blank? %>
<%= DIMENSIONS[@tourtype - 1][3] %>
<% else %>
<%= @tour.dimension4_name %>
<% end %>
<%= rating_for @buildingTour, :rating4, :star => 6, :userid => current_user.id %>
</div>
<div class= "span3">
<% if @tour.dimension5_name.blank? %>
<%= DIMENSIONS[@tourtype - 1][4] %>
<% else %>
<%= @tour.dimension5_name %>
<% end %>
<%= rating_for @buildingTour, :rating5, :star => 6, :userid => current_user.id %>
<% if @tour.dimension6_name.blank? %>
<%= DIMENSIONS[@tourtype - 1][5] %>
<% else %>
<%= @tour.dimension6_name %>
<% end %>
<%= rating_for @buildingTour, :rating6, :star => 6, :userid => current_user.id %>
<% if @tour.dimension7_name.blank? %>
<%= DIMENSIONS[@tourtype - 1][6] %>
<% else %>
<%= @tour.dimension7_name %>
<% end %>
<%= rating_for @buildingTour, :rating7, :star => 6, :userid => current_user.id %>
<% if @tour.dimension8_name.blank? %>
<%= DIMENSIONS[@tourtype - 1][7] %>
<% else %>
<%= @tour.dimension8_name %>
<% end %>
<%= rating_for @buildingTour, :rating8, :star => 6, :userid => current_user.id %>
</div>
<% end %>
</section>
</div>
</div>
<div id="progress-window" style="display:none;">
<div align="center">
<p><%= image_tag 'http://res.cloudinary.com/hoskloe8r/image/upload/v1371745905/spinner_lvzlel.gif' %></p>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#photos_toggle").click(function()
{
jQuery("#photos").slideToggle("slow");
});
jQuery("#file-upload_toggle").click(function() {
jQuery("#file-uploads-section").slideToggle("slow");
});
jQuery("#floorplans_toggle").click(function()
{
jQuery("#floorplans").slideToggle("slow");
});
jQuery("#docs_toggle").click(function()
{
jQuery("#docs").slideToggle("slow");
});
jQuery("#notes_toggle").click(function()
{
jQuery("#notes").slideToggle("slow");
});
jQuery("#ratings_toggle").click(function()
{
jQuery("#ratings").slideToggle("slow");
});
$("a[rel^='prettyPhoto']").prettyPhoto( {
show_title: false,
social_tools: false
});
$('.cloudinary-fileupload').fileupload('option', 'replaceFileInput', false);
$('.cloudinary_photo_upload').bind('fileuploadprogress', function(e, data) {
$('#photo-progress .bar').css('width', Math.round((data.loaded * 100.0) / data.total) + '%');
});
$('.cloudinary_floorplan_upload').bind('fileuploadprogress', function(e, data) {
$('#floorplan-progress .bar').css('width', Math.round((data.loaded * 100.0) / data.total) + '%');
});
$('.cloudinary_doc_upload').bind('fileuploadprogress', function(e, data) {
$('#doc-progress .bar').css('width', Math.round((data.loaded * 100.0) / data.total) + '%');
});
$('.cloudinary_photo_upload').bind('cloudinarydone', function() {
$('#save-photo-button').removeAttr('disabled');
});
$('.cloudinary_floorplan_upload').bind('cloudinarydone', function() {
$('#save-floorplan-button').removeAttr('disabled');
});
$('.cloudinary_doc_upload').bind('cloudinarydone', function() {
$('#save-doc-button').removeAttr('disabled');
});
});
</script>
<%= render partial: '/shared/file_upload_js' %>
<%= render partial: 'building_tour_js' %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment