Skip to content

Instantly share code, notes, and snippets.

@angeloh
Created September 9, 2012 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angeloh/3687571 to your computer and use it in GitHub Desktop.
Save angeloh/3687571 to your computer and use it in GitHub Desktop.
shopinionPlugin.js
var SHOPINION_DOMAIN="a.shopinionapp.com"; // either "j." or "" for j.shopinionapp.com or shopinionapp.com
var friends = null;
var friendsName = [];
var loadingPusher=false;
var xhr;
var head = document.getElementsByTagName('head')[0];
var initialized = false;
var counter = 0;
var idList = new Array();
//window.onload=installFixedWidget;
// TODO might need to use jquery noConflict
//$(function() {
// installFixedWidget();
// });
if(typeof window.jQuery === 'undefined' || window.jQuery.fn.jquery !== '1.7.2') {
var e=document.createElement('script');
e.type = "text/javascript";
e.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";
e.onreadystatechange = function(){
if (this.readyState === "complete" || this.readyState === "loaded") {
initialize();
}
};
e.onload = initialize;
head.appendChild(e);
log("loading jQuery");
}
if(typeof easyXDM === 'undefined') {
var e=document.createElement('script');
e.type = "text/javascript";
e.src = "http://" + SHOPINION_DOMAIN + "/assets/javascripts/easyXDM.debug.js";
e.onreadystatechange = function(){
if (this.readyState === "complete" || this.readyState === "loaded") {
initialize();
}
};
e.onload = initialize;
head.appendChild(e);
log("loading easyXDM");
}
if(typeof JSON === 'undefined' || !JSON) {
var e=document.createElement('script');
e.type = "text/javascript";
e.src = "http://" + SHOPINION_DOMAIN + "/assets/javascripts/json2.js";
e.onreadystatechange = function(){
if (this.readyState === "complete" || this.readyState === "loaded") {
initialize();
}
};
e.onload = initialize;
head.appendChild(e);
log("loading json2");
}
//$(window).load(function() {
// var myPlugin = {
// jq: null,
// loadScript: function(src) {
// var s = document.createElement('script');
// s.setAttribute('src', src);
// s.setAttribute('type', 'text/javascript');
// document.getElementsByTagName('head')[0].appendChild(s);
// },
// whenLoaded: function(callback){
// if (typeof(window.jQuery) !== 'undefined' && window.jQuery.fn.jquery == '1.7.2') {
// myPlugin.jq = window.jQuery.noConflict(true);
// callback(myPlugin.jq);
// }
// else {
// setTimeout((function() {myPlugin.whenLoaded(callback); }), 100);
// }
// },
// init: function($){
// log($.fn.jquery);
// log(window.jQuery.fn.jquery);
// initialize($);
// }
// };
// if(typeof window.JSON === 'undefined' || !JSON){
// myPlugin.loadScript('http://' + SHOPINION_DOMAIN + '/assets/javascripts/json2.js');
// log("loading JSON");
// }
// if(typeof window.easyXDM === 'undefined'){
// myPlugin.loadScript('http://' + SHOPINION_DOMAIN + '/assets/javascripts/easyXDM.debug.js');
// log("loading easyXDM");
// }
// if(typeof window.jQuery === 'undefined' || window.jQuery.fn.jquery !== '1.7.2'){
// myPlugin.loadScript('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js');
// log("loading jQuery");
// }
// myPlugin.whenLoaded(myPlugin.init);
//});
/*
if(typeof jQuery.ui === 'undefined' ||
typeof jQuery.isArray === 'undefined') {
var e=document.createElement('script');
e.type = "text/javascript";
e.src = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js";
e.onreadystatechange = function(){
if (this.readyState === "complete" || this.readyState === "loaded") {
initialize();
}
};
e.onload = initialize;
head.appendChild(e);
log("loading jQuery UI");
if ($(".ui-widget:first").is(":visible") === false) {
alert("stylesheet loaded!");
} else {
var e=document.createElement('link');
e.type = "text/css";
e.rel = "stylesheet";
e.href = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/ui-lightness/jquery-ui.css";
e.onreadystatechange = function(){
if (this.readyState === "complete" || this.readyState === "loaded") {
initialize();
}
};
e.onload = initialize;
head.appendChild(e);
log("loading jQuery UI CSS");
}
}*/
function log(statement) {
if (console != undefined && console != null &&
console.log != undefined && console.log != null) {
console.log(statement);
}
}
function addCss(cssCode, id) {
var styleElement = document.createElement("style");
styleElement.type = "text/css";
styleElement.id = id;
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = cssCode;
} else {
styleElement.appendChild(document.createTextNode(cssCode));
}
document.getElementsByTagName("head")[0].appendChild(styleElement);
}
function installFixedWidget() {
var cssCode =["#shopinionChatLayer {height: 100%;overflow: hidden;visibility: hidden;width: 100%;z-index: 2147483647;position: fixed;bottom: 0;right: 0;}",
"#shopinionTabPositionWrapper {margin: 0 10px;float: right;position: relative;padding: 2px 3px;width: 150px;height: 100%;}",
"#shopinionTabDiv {background-color: #F3A01E; border-width: 1px 1px 0px; border-style: solid solid none; border-color: rgb(255, 255, 255) rgb(255, 255, 255) currentColor; border-radius: 6px 6px 0px 0px; box-shadow: 1px 1px 1px rgba(255, 255, 255, 0.25) inset, 0px 1px 2px rgba(0, 0, 0, 0.5); font: bold 14px Arial,sans-serif; position: absolute; bottom: 0px;visibility: visible;color:white;}",
"#shopinionTabA {color: white;display: block; padding: 6px 10px 5px 10px; text-decoration: none;}",
"#shopinionTabA:hover {cursor:pointer}"];
var chatLayer = document.getElementById("shopinionChatLayer");
if (chatLayer == null) {
addCss(cssCode.join("\n"), "shopinionFixedWidget");
chatLayer = document.createElement("div");
chatLayer.id="shopinionChatLayer";
document.body.appendChild(chatLayer);
}
var tabPositionDiv = document.createElement("div");
tabPositionDiv.id = "shopinionTabPositionWrapper";
chatLayer.appendChild(tabPositionDiv);
var tabDiv = document.createElement("div");
tabDiv.id = "shopinionTabDiv";
tabPositionDiv.appendChild(tabDiv);
var tabA = document.createElement("a");
tabA.id = "shopinionTabA";
tabA.innerHTML = "Chat With Friends";
tabDiv.appendChild(tabA);
tabDiv.onclick=function(){initializeBookmarklet(); return false;}
}
function getExistingChat(myJQ) {
myJQ.ajax({
type: "GET",
url: "http://" + SHOPINION_DOMAIN + "/getExistingChat",
dataType: "jsonp",
success: function(data, textStatus, jqXHR) {
log("success: " + data + ", " + textStatus +", " + jqXHR);
subjectIds = data.subjectIds;
myFbId = data.myFbId;
myMemberId = data.myMemberId;
myName = data.myName;
if (subjectIds == undefined || myFbId == undefined || myMemberId == undefined ||
myName == undefined || data == null) {
return;
} else {
for (ii in subjectIds){
log("calling open chat on " + subjectIds[ii].subjectId);
openChatWindowAndSubscribeSubjectChannel(myJQ, myFbId, myMemberId, myName, subjectIds[ii].subjectId);
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
log("error");
log(jqXHR + ", " +textStatus +", " +errorThrown);
}
});
}
function initialize() {
var myJQ = window.jQuery.noConflict(true);
if(initialized ||
typeof myJQ === 'undefined' ||
typeof myJQ.ajax === 'undefined' ||
// typeof jQuery.ui === 'undefined' ||
typeof myJQ.isArray === 'undefined' ||
typeof myJQ.parseJSON === 'undefined' ||
typeof easyXDM === 'undefined' ||
typeof JSON === 'undefined' || !JSON) {
return;
}
xhr = new easyXDM.Rpc({
remote: "http://" + SHOPINION_DOMAIN + "/assets/html/cors.html",
}, {
remote: {
request:{}
}
});
getExistingChat(myJQ);
initialized=true;
installFixedWidget(myJQ);
//initChatBoxManager();
}
function initializeBookmarklet() {
if(initialized) {
getFbFriendsJson();
} else {
// TODO should not happen, remove button?
initialize();
}
}
function initChatBoxManager() {
chatboxManager = function() {
// list of all opened boxes
var boxList = new Array();
// list of boxes shown on the page
var showList = new Array();
// list of first names, for in-page demo
var nameList = new Array();
var config = {
width : 200, //px
gap : 20,
maxBoxes : 5,
messageSent : function(dest, msg) {
// override this
$("#" + dest).chatbox("option", "boxManager").addMsg(dest, msg);
}
};
var init = function(options) {
$.extend(config, options)
};
var delBox = function(id) {
// TODO
};
var getNextOffset = function() {
return (config.width + config.gap) * showList.length;
};
var boxClosedCallback = function(id) {
// close button in the titlebar is clicked
var idx = showList.indexOf(id);
if(idx != -1) {
showList.splice(idx, 1);
diff = config.width + config.gap;
for(var i = idx; i < showList.length; i++) {
offset = $("#" + showList[i]).chatbox("option", "offset");
$("#" + showList[i]).chatbox("option", "offset", offset - diff);
}
}
else {
alert("should not happen: " + id);
}
};
// caller should guarantee the uniqueness of id
var addBox = function(id, user, name) {
var idx1 = showList.indexOf(id);
var idx2 = boxList.indexOf(id);
if(idx1 != -1) {
// found one in show box, do nothing
}
else if(idx2 != -1) {
// exists, but hidden
// show it and put it back to showList
$("#"+id).chatbox("option", "offset", getNextOffset());
var manager = $("#"+id).chatbox("option", "boxManager");
manager.toggleBox();
showList.push(id);
}
else{
var el = document.createElement('div');
el.setAttribute('id', id);
$(el).chatbox({id : id,
user : user,
title : user.first_name + " " + user.last_name,
hidden : false,
width : config.width,
offset : getNextOffset(),
messageSent : messageSentCallback,
boxClosed : boxClosedCallback
});
boxList.push(id);
showList.push(id);
nameList.push(user.first_name);
}
};
var messageSentCallback = function(id, user, msg) {
var idx = boxList.indexOf(id);
config.messageSent(nameList[idx], msg);
};
// not used in demo
var dispatch = function(id, user, msg) {
$("#" + id).chatbox("option", "boxManager").addMsg(user.first_name, msg);
}
return {
init : init,
addBox : addBox,
delBox : delBox,
dispatch : dispatch
};
}();
(function($){
$.widget("ui.chatbox", {
options: {
id: null, //id for the DOM element
title: null, // title of the chatbox
user: null, // can be anything associated with this chatbox
hidden: false,
offset: 0, // relative to right edge of the browser window
width: 230, // width of the chatbox
messageSent: function(id, user, msg){
// override this
this.boxManager.addMsg(user.first_name, msg);
},
boxClosed: function(id) {}, // called when the close icon is clicked
boxManager: {
// thanks to the widget factory facility
// similar to http://alexsexton.com/?p=51
init: function(elem) {
this.elem = elem;
},
addMsg: function(peer, msg) {
var self = this;
var box = self.elem.uiChatboxLog;
var e = document.createElement('div');
box.append(e);
$(e).hide();
var systemMessage = false;
if (peer) {
var peerName = document.createElement("b");
$(peerName).text(peer + ": ");
e.appendChild(peerName);
} else {
systemMessage = true;
}
var msgElement = document.createElement(systemMessage ? "i" : "span");
$(msgElement).text(msg);
e.appendChild(msgElement);
$(e).addClass("ui-chatbox-msg");
$(e).fadeIn();
self._scrollToBottom();
if (!self.elem.uiChatboxTitlebar.hasClass("ui-state-focus") && !self.highlightLock) {
self.highlightLock = true;
self.highlightBox();
}
},
highlightBox: function() {
//this.elem.uiChatbox.addClass("ui-state-highlight");
var self = this;
self.elem.uiChatboxTitlebar.effect("highlight", {}, 300);
self.elem.uiChatbox.effect("bounce", {times:3}, 300, function(){
self.highlightLock = false;
self._scrollToBottom();
});
},
toggleBox: function() {
this.elem.uiChatbox.toggle();
},
_scrollToBottom: function() {
var box = this.elem.uiChatboxLog;
box.scrollTop(box.get(0).scrollHeight);
}
}
},
toggleContent: function(event) {
this.uiChatboxContent.toggle();
if(this.uiChatboxContent.is(":visible")) {
this.uiChatboxInputBox.focus();
}
},
widget: function() {
return this.uiChatbox
},
_create: function(){
var self = this,
options = self.options,
title = options.title || "No Title",
// chatbox
uiChatbox = (self.uiChatbox = $('<div></div>'))
.appendTo(document.body)
.addClass('ui-widget ' +
'ui-corner-top ' +
'ui-chatbox'
)
.attr('outline', 0)
.focusin(function(){
// ui-state-highlight is not really helpful here
//self.uiChatbox.removeClass('ui-state-highlight');
self.uiChatboxTitlebar.addClass('ui-state-focus');
})
.focusout(function(){
self.uiChatboxTitlebar.removeClass('ui-state-focus');
}),
// titlebar
uiChatboxTitlebar = (self.uiChatboxTitlebar = $('<div></div>'))
.addClass('ui-widget-header ' +
'ui-corner-top ' +
'ui-chatbox-titlebar ' +
'ui-dialog-header' // take advantage of dialog header style
)
.click(function(event) {
self.toggleContent(event);
})
.appendTo(uiChatbox),
uiChatboxTitle = (self.uiChatboxTitle = $('<span></span>'))
.html(title)
.appendTo(uiChatboxTitlebar),
uiChatboxTitlebarClose = (self.uiChatboxTitlebarClose = $('<a href="#"></a>'))
.addClass('ui-corner-all ' +
'ui-chatbox-icon '
)
.attr('role', 'button')
.hover(function() {uiChatboxTitlebarClose.addClass('ui-state-hover');},
function() {uiChatboxTitlebarClose.removeClass('ui-state-hover');})
// .focus(function() {
// uiChatboxTitlebarClose.addClass('ui-state-focus');
// })
// .blur(function() {
// uiChatboxTitlebarClose.removeClass('ui-state-focus');
// })
.click(function(event) {
uiChatbox.hide();
self.options.boxClosed(self.options.id);
return false;
})
.appendTo(uiChatboxTitlebar),
uiChatboxTitlebarCloseText = $('<span></span>')
.addClass('ui-icon ' +
'ui-icon-closethick')
.text('close')
.appendTo(uiChatboxTitlebarClose),
uiChatboxTitlebarMinimize = (self.uiChatboxTitlebarMinimize = $('<a href="#"></a>'))
.addClass('ui-corner-all ' +
'ui-chatbox-icon'
)
.attr('role', 'button')
.hover(function() {uiChatboxTitlebarMinimize.addClass('ui-state-hover');},
function() {uiChatboxTitlebarMinimize.removeClass('ui-state-hover');})
// .focus(function() {
// uiChatboxTitlebarMinimize.addClass('ui-state-focus');
// })
// .blur(function() {
// uiChatboxTitlebarMinimize.removeClass('ui-state-focus');
// })
.click(function(event) {
self.toggleContent(event);
return false;
})
.appendTo(uiChatboxTitlebar),
uiChatboxTitlebarMinimizeText = $('<span></span>')
.addClass('ui-icon ' +
'ui-icon-minusthick')
.text('minimize')
.appendTo(uiChatboxTitlebarMinimize),
// content
uiChatboxContent = (self.uiChatboxContent = $('<div></div>'))
.addClass('ui-widget-content ' +
'ui-chatbox-content '
)
.appendTo(uiChatbox),
uiChatboxLog = (self.uiChatboxLog = self.element)
//.show()
.addClass('ui-widget-content '+
'ui-chatbox-log'
)
.appendTo(uiChatboxContent),
uiChatboxInput = (self.uiChatboxInput = $('<div></div>'))
.addClass('ui-widget-content ' +
'ui-chatbox-input'
)
.click(function(event) {
// anything?
})
.appendTo(uiChatboxContent),
uiChatboxInputBox = (self.uiChatboxInputBox = $('<textarea></textarea>'))
.addClass('ui-widget-content ' +
'ui-chatbox-input-box ' +
'ui-corner-all'
)
.appendTo(uiChatboxInput)
.keydown(function(event) {
if(event.keyCode && event.keyCode == $.ui.keyCode.ENTER) {
msg = $.trim($(this).val());
if(msg.length > 0) {
self.options.messageSent(self.options.id, self.options.user, msg);
}
$(this).val('');
return false;
}
})
.focusin(function() {
uiChatboxInputBox.addClass('ui-chatbox-input-focus');
var box = $(this).parent().prev();
box.scrollTop(box.get(0).scrollHeight);
})
.focusout(function() {
uiChatboxInputBox.removeClass('ui-chatbox-input-focus');
});
// disable selection
uiChatboxTitlebar.find('*').add(uiChatboxTitlebar).disableSelection();
// switch focus to input box when whatever clicked
uiChatboxContent.children().click(function(){
// click on any children, set focus on input box
self.uiChatboxInputBox.focus();
});
self._setWidth(self.options.width);
self._position(self.options.offset);
self.options.boxManager.init(self);
if (!self.options.hidden) {
uiChatbox.show();
}
},
_setOption: function(option, value) {
if (value != null) {
switch(option) {
case "hidden":
if (value)
this.uiChatbox.hide();
else
this.uiChatbox.show();
break;
case "offset":
this._position(value);
break;
case "width":
this._setWidth(value);
break;
}
}
$.Widget.prototype._setOption.apply(this, arguments);
},
_setWidth: function(width) {
this.uiChatboxTitlebar.width(width + "px");
this.uiChatboxLog.width(width + "px");
// this is a hack, but i can live with it so far
this.uiChatboxInputBox.css("width", (width - 14) + "px");
},
_position: function(offset) {
this.uiChatbox.css("right", offset);
}
});
}(jQuery));
var broadcastMessageCallback = function(from, msg) {
for(var i = 0; i < idList.length; i ++) {
chatboxManager.addBox(idList[i]);
$("#" + idList[i]).chatbox("option", "boxManager").addMsg(from, msg);
}
}
// chatboxManager is excerpt from the original project
// the code is not very clean, I just want to reuse it to manage multiple chatboxes
chatboxManager.init({messageSent : broadcastMessageCallback});
}
function getFbFriendsJson() {
var myJQ = window.jQuery.noConflict(true);
myJQ.ajax({
type: "GET",
url: "http://" + SHOPINION_DOMAIN + "/getFbFriends",
dataType: "jsonp",
success: function(data, textStatus, jqXHR) {
//log("success: " + data + ", " + textStatus +", " + jqXHR);
if (data.friends == undefined || data == undefined || data == null) {
log("displayLogin");
displayLogin()
} else {
friends = data.friends;
friendsName=[];
for (ii in friends){
friendsName.push(friends[ii].name);
}
log("getFbFriendsJson: " + friends.length + ", " + friendsName.length);
var tabDiv = document.getElementById("shopinionTabDiv");
var fbLogin = document.getElementById("shopinionFbLogin");
var loginInfo = document.getElementById("shopinionLoginInfo");
var loginClose = document.getElementById("shopinionLoginClose");
var tabA = document.getElementById("shopinionTabA");
if (fbLogin != null) {
tabDiv.removeChild(fbLogin);
}
if (loginInfo != null) {
tabDiv.removeChild(loginInfo);
}
if (loginClose != null) {
tabDiv.removeChild(loginClose);
}
// if null, rerender the buttom chat btn
if (tabA == null) {
tabA = document.createElement("a");
tabA.id = "shopinionTabA";
tabA.innerHTML = "Chat With Friends";
tabDiv.appendChild(tabA);
tabDiv.onclick=function(){initializeBookmarklet(); return false;}
}
displaySelection(myJQ);
}
},
error: function(jqXHR, textStatus, errorThrown) {
log("error");
log(jqXHR + ", " +textStatus +", " +errorThrown);
}
});
}
function displayLogin() {
var cssCode =[
"#shopinionLoginInfo {font-size:10px;text-align:left;margin: 5px auto 5px 15px;}",
"#shopinionFbLogin {font-size:13px;margin:8px 8px 5px;cursor:pointer;font-weight:bold;text-align:center;}",
"#shopinionLoginInfo a {color:#ccff33;text-decoration:none;cusor:pointer;}",
"#shopinionLoginInfo a:hover {color:#cc33ff;text-decoration:none;cusor:pointer;}",
"#shopinionLoginClose {width:9px;height:9px;top:3px;right:3px;position:absolute;cursor:pointer;}"
];
addCss(cssCode.join("\n"), "shopinionLogin");
var tabDiv = document.getElementById("shopinionTabDiv");
tabDiv.removeChild(document.getElementById("shopinionTabA"));
var shopinionFbLogin = document.createElement("p");
shopinionFbLogin.id="shopinionFbLogin";
shopinionFbLogin.innerHTML="Log in/Register with Facebook";
var shopinionLoginInfo = document.createElement("p");
shopinionLoginInfo.id="shopinionLoginInfo";
shopinionLoginInfo.innerHTML="Powered by <a href='http://www.shopinionapp.com/about' target='_blank'> Shopinion </a>";
var shopinionLoginClose = document.createElement("img");
shopinionLoginClose.id="shopinionLoginClose";
shopinionLoginClose.src="https://s3.amazonaws.com/shopinionapp/assets/images/delete_icon_black%2616.png";
tabDiv.appendChild(shopinionFbLogin);
tabDiv.appendChild(shopinionLoginInfo);
tabDiv.appendChild(shopinionLoginClose);
var myJQ = window.jQuery.noConflict(true);
myJQ("#shopinionFbLogin").click(function(){
log("#shopinionFbLogin clicked");
var childWindow = window.open("https://www.facebook.com/dialog/oauth?client_id=283004138400332&scope=email,offline_access,xmpp_login&redirect_uri=http://" + SHOPINION_DOMAIN + "/getFbAccessTokenClose", "shopinion", "width=550,height=450,status=yes,resizable=yes, toolbar=no");
if (window.addEventListener) {
window.addEventListener("message", handleMessage, false);
} else {
window.attachEvent("onmessage", handleMessage); // For IE8
}
});
myJQ("#shopinionLoginClose").click(function(){
log("#shopinionLoginClose clicked");
tabDiv.removeChild(shopinionFbLogin);
tabDiv.removeChild(shopinionLoginInfo);
tabDiv.removeChild(shopinionLoginClose);
var tabA = document.createElement("a");
tabA.id = "shopinionTabA";
tabA.innerHTML = "Chat With Friends";
tabDiv.appendChild(tabA);
tabDiv.onclick=function(){initializeBookmarklet(); return false;}
return false;
});
}
function handleMessage(data) {
log("data.origin: " + data.origin);
log("data.data: " + data.data);
if (data.origin=="http://"+SHOPINION_DOMAIN && data.data=="authorized") {
log("getFbFriendsJson again");
getFbFriendsJson();
document.body.removeChild(document.getElementById("shopinionLoginDiv"));
}
}
function displaySelection(myJQ) {
if(typeof Pusher === 'undefined') {
var e=document.createElement('script');
e.setAttribute('type','text/javascript');
e.setAttribute('charset','UTF-8');
e.setAttribute('src','http://js.pusher.com/1.12/pusher.min.js');
document.body.appendChild(e);
loadingPusher = true;
}
var cssCode =["#shopinionSelectBackground {background-color:#888888;bottom:0;left:0;opacity:0.9;position:fixed;right:0;top:0;z-index:2147483646;}",
"#shopinionSelectWrapperDiv {position:fixed;top:20px;right: 50px;bottom:20px;left:275px; width: 900px;border:8px solid #98BF21;border-radius: 8px 8px 8px 8px !important;background-color: white;text-align:left;z-index:2147483647;}",
".shopinionPicSelectCell {background: none repeat scroll 0 0 #FFFFFF;height: 150px;width: 150px;border: 1px solid #E5EECC;cursor: pointer;display: inline-block;position: relative;text-decoration: none;text-shadow: 0 1px #FFFFFF;vertical-align: middle;}",
".shopinionPicSelectCell img {max-width: 150px; max-height; 150px; left:0; top:0; position:absolute;}",
".shopinionPicSelectCell span.sendButtonSpan {background: none repeat scroll 0 0 transparent; display: inline-block;height: 150px;width: 150px;vertical-align: middle;position:relative;}",
".shopinionPicSelectCell span.sendButtonSpan:hover {background: url('http://s3.amazonaws.com/shopinionapp/assets/images/snatchthis_light_b_120_52.png') no-repeat scroll 50% 50% transparent; display: inline-block;height: 150px;width: 150px; }",
"#shopinionSelectLeftPart {position:absolute;top:0; bottom:0; left:0; width: 480px;overflow-y: scroll;border-collapse:collapse;}",
"#shopinionSelectRightPart {position:absolute;top:0;right:0;bottom:0;left:500px;}",
"#shopinionSelectRightUpperPart {margin:5px;font:17px Tahoma,Geneva,sans-serif;color:black;}",
".shopinionInputDiv {margin: 8px 0 10px 0;}",
".shopinionInputDiv textarea {border:1px solid #6D84B4;}",
"input[type='text'].shopinionTextInput {height: 23px;border:1px solid #6D84B4;background-image:none; border-radius:4px;}",
"#shopinionDescription {border:1px solid #6D84B4;background-image:none; border-radius:4px;}",
"#shopinionSubmitButton {background: #006DCC;background: -moz-linear-gradient(top, #0088CC 0%, #0044CC 100%);background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#0088CC), color-stop(100%,#0044CC));background: -webkit-linear-gradient(top, #0088CC 0%,#0044CC 100%);background: -o-linear-gradient(top, #0088CC 0%,#0044CC 100%);background: -ms-linear-gradient(top, #0088CC 0%,#0044CC 100%);background: linear-gradient(to bottom, #0088CC 0%,#0044CC 100%);filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#0088CC', endColorstr='#0044CC',GradientType=0 );background-repeat: repeat-x;border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);color: #FFFFFF;text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);border-radius: 4px 4px 4px 4px;border-style: solid;border-width: 1px;box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05);font-size: 14px;line-height: 20px;margin-bottom: 0;margin-right:5px;padding: 8px 14px;text-align: center;cursor:pointer;}",
"#shopinionCancelButton {background-repeat: repeat-x;color: #575757;border-radius: 4px 4px 4px 4px;border-style: solid;border-width: 1px;box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05);font-size: 14px;line-height: 20px;margin-bottom: 0;padding: 8px 14px;text-align: center;cursor:pointer;background-image: -ms-linear-gradient(top, #F6F6F6 0%, #D9D9D9 100%);background-image: -moz-linear-gradient(top, #F6F6F6 0%, #D9D9D9 100%);background-image: -o-linear-gradient(top, #F6F6F6 0%, #D9D9D9 100%);background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #F6F6F6), color-stop(1, #D9D9D9));background-image: -webkit-linear-gradient(top, #F6F6F6 0%, #D9D9D9 100%);background-image: linear-gradient(to bottom, #F6F6F6 0%, #D9D9D9 100%);}",
"#shopinionTestButton {background-repeat: repeat-x;color: #575757;border-radius: 4px 4px 4px 4px;border-style: solid;border-width: 1px;box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05);font-size: 14px;line-height: 20px;margin-bottom: 0;padding: 8px 14px;text-align: center;cursor:pointer;background-image: -ms-linear-gradient(top, #F6F6F6 0%, #D9D9D9 100%);background-image: -moz-linear-gradient(top, #F6F6F6 0%, #D9D9D9 100%);background-image: -o-linear-gradient(top, #F6F6F6 0%, #D9D9D9 100%);background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #F6F6F6), color-stop(1, #D9D9D9));background-image: -webkit-linear-gradient(top, #F6F6F6 0%, #D9D9D9 100%);background-image: linear-gradient(to bottom, #F6F6F6 0%, #D9D9D9 100%);}",
"#contactDiv {overflow-y: scroll;position: absolute;top: 225px;left:0;right:0;bottom: 0;}",
".contactTableCell {text-align: left;vertical-align: middle;padding: .5em 0;font-size: 0.8em;width: 25%;}",
".contactTableCellLeft {border: 1px solid rgba(0, 0, 0, 0.2);border-left: none;}",
".contactTableCellMiddle {border: 1px solid rgba(0, 0, 0, 0.2);}",
".contactTableCellRight {border: 1px solid rgba(0, 0, 0, 0.2);border-right: none;}",
".shopinionHintInfo {font-size: 10px; color: #888888; margin-left: 3px;}",
"#shopinionWarnSpan {font-size:11px;color:red;margin-left:2px;}",
"#shopinionButtons {margin-top: 5px;}",
"#shopinionWaitingImg {position:fixed;top:100px;left:275px;z-index:2147483647;}",
".shopinionClearfix:after {clear:both;content:'.';display:block;height:0;visibility: hidden;}",
"#shopinionSearchFriendsBox {border:1px solid #6D84B4;border-radius: 2px 2px 2px 2px;background: none repeat scroll 0 0 #FFFFFF;direction:ltr;margin-top: 5px;padding: 3px 5px;font-size: 12px;}",
"#shopinionLink {background: none repeat scroll 0 0 #cccccc;border: 1px solid #6D84B4;border-radius: 2px 2px 2px 2px;direction: ltr;font-size: 12px;margin-top: 5px;padding: 3px 5px;line-height:23px;width:20em;-webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;}",
"#shopinionFriendsSpan {display: block;}",
".shopinionFriendSpan {background: none repeat scroll 0 0 #E2E6F0;border: 1px solid #9DACCC;border-radius: 2px 2px 2px 2px;color: #1C2A47;cursor: default;display: block;float: left;line-height: 16px;margin: 4px 4px 4px 0;padding: 0 3px;position: relative;white-space: nowrap;top:2px;}",
".shopinionRemoveFriend {width: 16px;height: 16px;cursor:pointer;vertical-align: middle;}",
"#shopinionFriendsInput {border:none;background-color: transparent;float:left;outline:0;}"];
addCss(cssCode.join("\n"),"shopinionSelectionTools");
var backgroundDiv = document.createElement("div");
backgroundDiv.id = "shopinionSelectBackground";
document.body.appendChild(backgroundDiv);
var wrapperDiv = document.createElement("div");
wrapperDiv.id="shopinionSelectWrapperDiv";
wrapperDiv.style.left = (window.screen.availWidth - 900) / 2 + "px";
document.body.appendChild(wrapperDiv);
var leftPart = document.createElement("div");
leftPart.id="shopinionSelectLeftPart";
var numImg = 0;
for(ii in document.images) {
if (document.images[ii].clientWidth >= 100 && document.images[ii].clientHeight >= 100) {
var picSelectCell = document.createElement("span");
var sendButtonSpan = document.createElement("span");
var imageLink = document.createElement("a");
var image = document.createElement("img");
numImg++;
image.src = document.images[ii].src;
imageLink.appendChild(image);
sendButtonSpan.className="sendButtonSpan";
picSelectCell.appendChild(imageLink);
picSelectCell.appendChild(sendButtonSpan);
picSelectCell.className = "shopinionPicSelectCell";
leftPart.appendChild(picSelectCell);
}
}
if (numImg==0) {
wrapperDiv.style.width ="300px";
wrapperDiv.style.height ="50px";
wrapperDiv.style.left = (window.screen.availWidth - wrapperDiv.style.width) / 2 + "px";
wrapperDiv.style.top = "200px";
wrapperDiv.style.textAlign="center";
wrapperDiv.style.lineHeight="50px";
console.log("wrapperdiv: " + wrapperDiv.style.left +", " + wrapperDiv.style.top);
wrapperDiv.innerHTML="Sorry, no image is large enough to be sent.";
setTimeout(removeEverything, 5000);
backgroundDiv.addEventListener("click", removeEverything);
return;
}
wrapperDiv.appendChild(leftPart);
var rightPart = document.createElement("div");
rightPart.id="shopinionSelectRightPart";
wrapperDiv.appendChild(rightPart);
var rightUpperPart = document.createElement("div");
rightUpperPart.id="shopinionSelectRightUpperPart";
rightPart.appendChild(rightUpperPart);
var imgSrc = document.createElement("input");
imgSrc.id="shopinionImgSrc";
imgSrc.type="hidden";
var firstSendButtonSpan = getElementsByClassName("sendButtonSpan", "span", leftPart)[0];
imgSrc.value=firstSendButtonSpan.parentNode.getElementsByTagName("img")[0].src;
firstSendButtonSpan.style.background="url('http://s3.amazonaws.com/shopinionapp/assets/images/snatchthis_light_b_120_52.png') no-repeat scroll 50% 50% transparent";
rightUpperPart.appendChild(imgSrc);
var titleInputDiv = document.createElement("div");
var titleText = document.createTextNode("Title: ");
var titleInput = document.createElement("input");
var br1 = document.createElement('br');
var br2 = document.createElement('br');
titleInputDiv.className="shopinionInputDiv";
titleInput.className="shopinionTextInput";
titleInput.id="shopinionTitle";
titleInput.type="text";
titleInput.size="35";
titleInput.value=document.title;
titleInputDiv.appendChild(titleText);
titleInputDiv.appendChild(br1);
titleInputDiv.appendChild(titleInput);
titleInputDiv.appendChild(br2);
rightUpperPart.appendChild(titleInputDiv);
var price = getPrice();
var priceInputDiv = document.createElement("div");
var priceText = document.createTextNode("Price: ");
var priceInput = document.createElement("input");
priceInputDiv.className="shopinionInputDiv";
priceInput.className="shopinionTextInput";
priceInput.id="shopinionPrice";
priceInput.type="text";
priceInput.size="5";
priceInput.value=price;
var robotNotice = document.createElement("span");
robotNotice.className="shopinionHintInfo";
robotNotice.innerHTML="Did our robot pick up the right price and title?";
var br3 = document.createElement('br');
priceInputDiv.appendChild(priceText);
priceInputDiv.appendChild(robotNotice);
priceInputDiv.appendChild(br3);
priceInputDiv.appendChild(priceInput);
rightUpperPart.appendChild(priceInputDiv);
var subjectId = Math.floor(Math.random() * 10000);
var linkInputDiv = document.createElement("div");
var linkText = document.createTextNode("Link: ");
var linkDiv = document.createElement("div");
var subjectIdInput = document.createElement("input");
subjectIdInput.id="shopinionSubjectId";
subjectIdInput.type="hidden";
subjectIdInput.value=subjectId;
linkInputDiv.className="shopinionInputDiv";
linkDiv.className="shopinionTextInput";
linkDiv.id="shopinionLink";
var linkNotice = document.createElement("span");
linkNotice.className="shopinionHintInfo";
linkNotice.innerHTML="Inserted into your message to direct your friends to this page.";
var linkBr = document.createElement('br');
linkDiv.innerHTML="http://" + SHOPINION_DOMAIN + "/redirect/"+subjectId;
linkInputDiv.appendChild(subjectIdInput);
linkInputDiv.appendChild(linkText);
linkInputDiv.appendChild(linkNotice);
linkInputDiv.appendChild(linkBr);
linkInputDiv.appendChild(linkDiv);
rightUpperPart.appendChild(linkInputDiv);
var descriptionInputDiv = document.createElement("div");
var description = document.createElement("textarea");
descriptionInputDiv.className="shopinionInputDiv";
description.rows="5";
description.cols="45";
description.id="shopinionDescription";
description.value="I am interested in getting " + document.title + ". Can you please visit the link above and let me know what you think?";
var br4 = document.createElement('br');
descriptionInputDiv.appendChild(description);
descriptionInputDiv.appendChild(br4);
var fbNotice = document.createElement("span");
fbNotice.className="shopinionHintInfo";
fbNotice.innerHTML="A private Facebook message will be sent.";
var br5 = document.createElement('br');
descriptionInputDiv.appendChild(fbNotice);
descriptionInputDiv.appendChild(br5);
rightUpperPart.appendChild(descriptionInputDiv);
var forPublicInputDiv = document.createElement("div");
var forPublicInput = document.createElement("input");
forPublicInputDiv.className="shopinionInputDiv";
forPublicInput.id="shopinionForPublic";
forPublicInput.type="checkbox";
forPublicInput.checked=true;
var forPublicTextSpan = document.createElement("span");
forPublicTextSpan.innerHTML="Send to Shopinion.im website";
forPublicTextSpan.style.marginLeft="5px";
forPublicTextSpan.style.fontSize="13px";
forPublicInputDiv.appendChild(forPublicInput);
forPublicInputDiv.appendChild(forPublicTextSpan);
rightUpperPart.appendChild(forPublicInputDiv);
var contactTable = document.createElement("table");
var contactRow = document.createElement("tr");
var contactCellLeft = document.createElement("td");
var contactCellRight = document.createElement("td");
contactTable.style.marginBottom="10px";
contactCellLeft.innerHTML="To:";
contactCellLeft.style.font="17px Tahoma,Geneva,sans-serif";
contactCellLeft.style.borderWidth="0px";
contactCellLeft.style.verticalAlign="middle";
contactCellRight.width="100%";
contactCellRight.style.borderWidth="0px";
var searchBox = document.createElement("div");
searchBox.id="shopinionSearchFriendsBox";
searchBox.className="shopinionClearfix";
var friendsSpan = document.createElement("span");
friendsSpan.id="shopinionFriendsSpan";
var friendsInput = document.createElement("input");
friendsInput.className="shopinionTextInput";
friendsInput.id="shopinionFriendsInput";
friendsInput.type="text";
friendsInput.placeholder="Type your friends name here";
friendsInput.style.width="300px";
contactTable.appendChild(contactRow);
contactRow.appendChild(contactCellLeft);
contactRow.appendChild(contactCellRight);
contactCellRight.appendChild(searchBox);
searchBox.appendChild(friendsSpan);
searchBox.appendChild(friendsInput);
rightUpperPart.appendChild(contactTable);
var buttonDiv = document.createElement("div");
buttonDiv.id="shopinionButtons";
var submitButton = document.createElement("input");
submitButton.type="button";
submitButton.value="Chat With Friends";
submitButton.id="shopinionSubmitButton";
var cancelButton = document.createElement("input");
cancelButton.type="button";
cancelButton.value="Cancel";
cancelButton.id="shopinionCancelButton";
var warnSpan = document.createElement("span");
warnSpan.id="shopinionWarnSpan";
buttonDiv.appendChild(submitButton);
buttonDiv.appendChild(cancelButton);
var testButton = document.createElement("input");
testButton.type="button";
testButton.value="Popup";
testButton.id="shopinionTestButton";
buttonDiv.appendChild(testButton);
rightUpperPart.appendChild(buttonDiv);
rightUpperPart.appendChild(warnSpan);
cancelButton.addEventListener("click", removeEverything);
actb(document.getElementById('shopinionFriendsInput'));
function getPrice() {
var priceReg = /(?:\$)(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/g;
/*
zappos: priceSlot
amazon: actualPriceValue
*/
/* try to detect price by probing for pre-defined price id*/
var PRICE_ID=["price", "priceSlot", "actualPriceValue"];
for (ii in PRICE_ID) {
var element = document.getElementById(PRICE_ID[ii]);
if(element != null) {
log("found price id " + PRICE_ID[ii] +": " + element.innerHTML);
var pricesString = element.innerHTML.match(priceReg);
if (pricesString != null) {
return parseFloat(pricesString[0].replace("$",""));
}
}
}
/*gilt: nouveau-price
zappos: salePrice
amazon: priceLarge
nordstrom: price
macy's: priceSale
a-f: offer-price*/
/* try to detect price by probing for pre-defined price class*/
var PRICE_CLASS=["price", "priceLarge", "salePrice", "priceSale", "offer-price", "nouveau-price"];
var priceReg = /(?:\$)(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/g;
for (ii in PRICE_CLASS) {
var elements = getElementsByClassName(PRICE_CLASS[ii], null, document);
if(elements != null && elements.length > 0) {
for (jj in elements) {
log("found price class " + PRICE_CLASS[ii] +": " + elements[jj].innerHTML);
}
var pricesString = elements[0].innerHTML.match(priceReg);
if (myJQ.isArray(pricesString)) {
for (var j = 0; j<pricesString.length; j++) {
var priceStr = pricesString[j].replace(",","")
priceStr = priceStr.replace("$","")
var price = parseFloat(priceStr);
log("found price class with price: " + price);
return price;
}
} else if (pricesString != null) {
var priceStr = pricesString.replace(",","")
priceStr = priceStr.replace("$","")
var price = parseFloat(priceStr);
log("found price class with price: " + price);
return price;
}
}
}
/* search any class with price in its class name and $ in its html.*/
var arrElements = document.getElementsByTagName("*");
var arrReturnElements = new Array();
//(^|\s)\w*price\w*(\s|$)
var oRegExp = new RegExp("(^|\\s)\\w*price\\w*(\\s|$)". i);
var oElement;
//log("price class search");
for(var i=0; i<arrElements.length; i++){
oElement = arrElements[i];
if(oRegExp.test(oElement.className)){
var priceString = oElement.innerHTML.match(priceReg);
//log("priceString: " + typeof priceString + ", " + priceString);
if (myJQ.isArray(priceString)) {
for (var j = 0; j<priceString.length; j++) {
var priceStr = priceString[j].replace(",","")
priceStr = priceStr.replace("$","")
var price = parseFloat(priceStr);
arrReturnElements.push(price);
//log("found price class with price: " + price);
}
} else if (priceString != null) {
var priceStr = priceString.replace(",","")
priceStr = priceStr.replace("$","")
var price = parseFloat(priceStr);
arrReturnElements.push(price);
//log("found price class with price: " + price);
}
}
}
if (arrReturnElements.length > 0) {
return arrReturnElements[0];
}
/* raw price search. simply search for $ sign */
var pricesString = document.body.innerHTML.match(priceReg);
//log("raw price search");
for (aa in pricesString) {
//log("found raw price: " + pricesString[aa]);
}
if (pricesString.length >= 2) {
var priceStr = pricesString[0].replace(",","")
priceStr = priceStr.replace("$","")
var prices0 = parseFloat(priceStr);
priceStr = pricesString[1].replace(",","")
priceStr = priceStr.replace("$","")
var prices1 = parseFloat(priceStr);
var price = (prices0 >= prices1) ? prices0 : prices1;
return price;
} else if (priceString != null) {
var priceStr = priceString.replace(",","")
priceStr = priceStr.replace("$","")
return parseFloat(priceStr);
}
return 0;
}
myJQ(".sendButtonSpan").click(function(){
myJQ(".sendButtonSpan").css("background", "none repeat scroll 0 0 transparent");
myJQ(this).css("background", "url('http://s3.amazonaws.com/shopinionapp/assets/images/snatchthis_light_b_120_52.png') no-repeat scroll 50% 50% transparent");
myJQ("#shopinionImgSrc").attr("value", this.parentNode.getElementsByTagName("img")[0].src);
return false;
});
myJQ("#shopinionSubmitButton").click(function(){
var shopinionRequestFbString = [];
myJQ(".shopinionFriendSpan input[type='hidden']").each(function() {
shopinionRequestFbString.push(myJQ(this).val());
});
warnSpan.innerHTML="";
if (shopinionRequestFbString.length==0 && document.getElementById("shopinionForPublic").checked==false) {
warnSpan.innerHTML = "Please choose somebody to send to.<br/>";
}
if (myJQ("#shopinionTitle").val() == "") {
warnSpan.innerHTML +="Please fill in the title.<br/>";
}
if (myJQ("#shopinionPrice").val() == "") {
warnSpan.innerHTML +="Please fill in the price.<br/>";
}
if (myJQ("#shopinionDescription").val() == "") {
warnSpan.innerHTML +="Please fill in the description.<br/>";
}
if (warnSpan.innerHTML.trim() != "") {
return false;
}
log("submitButton clicked: " + shopinionRequestFbString + ", " + document.getElementById("shopinionForPublic").checked +
", " + document.getElementById("shopinionDescription").value);
xhr.request({
url: "../../bookmarkletPost",
method: "POST",
data: {shopinionImgSrc: document.getElementById("shopinionImgSrc").value,
shopinionSubjectId: document.getElementById("shopinionSubjectId").value,
shopinionTitle: document.getElementById("shopinionTitle").value,
shopinionPrice: document.getElementById("shopinionPrice").value,
shopinionDescription: document.getElementById("shopinionDescription").value,
shopinionForPublic: document.getElementById("shopinionForPublic").checked,
shopinionRequestFbString: shopinionRequestFbString,
referringUrl: document.URL
},
}, function(response) { // success function
if (typeof response.data == "string") {
data = myJQ.parseJSON(response.data);
} else {
data = response.data;
}
openChatWindowAndSubscribeSubjectChannel(myJQ, data.myFbId, data.myMemberId,
data.myName, data.subjectId);
document.body.removeChild(waitingImg);
document.body.removeChild(backgroundDiv);
var autoCompleteTable = document.getElementById("tat_table");
if (autoCompleteTable != null) {
document.body.removeChild(autoCompleteTable);
}
}, function(response) { // failure function
document.body.removeChild(waitingImg);
document.body.appendChild(wrapperDiv);
wrapperDiv.style.width ="300px";
wrapperDiv.style.height ="50px";
wrapperDiv.style.left = (window.screen.availWidth - 300) / 2 + "px";
wrapperDiv.style.top = "200px";
wrapperDiv.style.textAlign="center";
wrapperDiv.style.lineHeight="50px";
console.log("wrapperdiv: " + wrapperDiv.style.left +", " + wrapperDiv.style.top);
wrapperDiv.innerHTML="Error sending request. Please try again shortly.";
setTimeout(removeEverything, 3000);
backgroundDiv.addEventListener("click", removeEverything);
log('POST failed: ' + response.status +", " + response.message);
});
/*myJQ.ajax({
type: "POST",
url: "http://" + SHOPINION_DOMAIN + "/bookmarkletPost",
xhrFields: {
withCredentials: true
},
data: {shopinionImgSrc: document.getElementById("shopinionImgSrc").value,
shopinionSubjectId: document.getElementById("shopinionSubjectId").value,
shopinionTitle: document.getElementById("shopinionTitle").value,
shopinionPrice: document.getElementById("shopinionPrice").value,
shopinionDescription: document.getElementById("shopinionDescription").value,
shopinionForPublic: document.getElementById("shopinionForPublic").checked,
shopinionRequestFbString: shopinionRequestFbString,
referringUrl: document.URL
},
success: function(data) {
if (typeof data == "string") {
data = myJQ.parseJSON(data);
}
openChatWindowAndSubscribeSubjectChannel(myJQ, data.myFbId, data.myMemberId,
data.myName, data.subjectId);
document.body.removeChild(document.getElementById("shopinionWaitingImg"));
document.body.removeChild(document.getElementById("shopinionSelectBackground"));
},
error: function (responseData, textStatus, errorThrown) {
document.body.removeChild(waitingImg);
document.body.appendChild(wrapperDiv);
wrapperDiv.style.width ="300px";
wrapperDiv.style.height ="50px";
wrapperDiv.style.left = (window.screen.availWidth - 300) / 2 + "px";
wrapperDiv.style.top = "200px";
wrapperDiv.style.textAlign="center";
wrapperDiv.style.lineHeight="50px";
wrapperDiv.innerHTML="Error sending request. Please try again shortly.";
setTimeout(removeEverything, 3000);
backgroundDiv.addEventListener("click", removeEverything);
//log('POST failed.' + responseData + textStatus + errorThrown);
}
});*/
leftPart.parentNode.removeChild(leftPart);
rightPart.parentNode.removeChild(rightPart);
document.body.removeChild(wrapperDiv);
var waitingImg = document.createElement("img");
waitingImg.src='http://s3.amazonaws.com/shopinionapp/assets/images/waiting.gif';
waitingImg.id="shopinionWaitingImg";
waitingImg.style.left = (window.screen.availWidth - 200) / 2 + "px";
waitingImg.style.bottom = (window.screen.availHeight - 200) / 2 + "px";
log("bbbleh: " + window.screen.availHeight +", "+window.screen.availWidth+","+waitingImg.style.left);
document.body.appendChild(waitingImg);
return false;
});
myJQ("#shopinionTestButton").click(function(event, ui){
counter ++;
var id = "box" + counter;
idList.push(id);
chatboxManager.addBox(id,
{dest:"dest" + counter, // not used in demo
title:"box" + counter,
first_name:"First" + counter,
last_name:"Last" + counter
//you can add your own options too
});
event.preventDefault();
});
function removeEverything() {
document.body.removeChild(wrapperDiv);
document.body.removeChild(backgroundDiv);
var autoCompleteTable = document.getElementById("tat_table");
if (autoCompleteTable != null) {
document.body.removeChild(autoCompleteTable);
}
}
function actb(obj){
/* ---- Public Variables ---- */
this.actb_timeOut = -1; // Autocomplete Timeout in ms (-1: autocomplete never time out)
this.actb_lim = 4; // Number of elements autocomplete can show (-1: no limit)
this.actb_firstText = false; // should the auto complete be limited to the beginning of keyword?
this.actb_mouse = true; // Enable Mouse Support
this.actb_delimiter = new Array(';',','); // Delimiter for multiple autocomplete. Set it to empty array for single autocomplete
this.actb_startcheck = 1; // Show widget only after this number of characters is typed in.
/* ---- Public Variables ---- */
/* --- Styles --- */
this.actb_bgColor = '#ffffff'; //888888 for unselected background
this.actb_textColor = '#000000'; //ffffff for unselected font
this.actb_hColor = '#888888'; //000000 for selected background
this.actb_hTextColor = '#ffffff'; //000000 for selected font
this.actb_fFamily = 'Verdana';
this.actb_fSize = '11px';
this.actb_hStyle = 'text-decoration:underline;font-weight="bold"';
/* --- Styles --- */
/* ---- Private Variables ---- */
var actb_delimwords = new Array();
var actb_cdelimword = 0;
var actb_delimchar = new Array();
var actb_display = false;
var actb_pos = 0;
var actb_total = 0;
var actb_curr = null;
var actb_rangeu = 0;
var actb_ranged = 0;
var actb_bool = new Array();
var actb_pre = 0;
var actb_toid;
var actb_tomake = false;
var actb_getpre = "";
var actb_mouse_on_list = 1;
var actb_kwcount = 0;
var actb_caretmove = false;
/* ---- Private Variables---- */
var actb_self = this;
actb_curr = obj;
addEvent(actb_curr,"focus",actb_setup);
function actb_setup(){
addEvent(document,"keydown",actb_checkkey);
addEvent(actb_curr,"blur",actb_clear);
addEvent(document,"keypress",actb_keypress);
}
function actb_clear(evt){
if (!evt) evt = event;
removeEvent(document,"keydown",actb_checkkey);
removeEvent(actb_curr,"blur",actb_clear);
removeEvent(document,"keypress",actb_keypress);
actb_removedisp();
}
function actb_parse(n){
var t = actb_curr.value.addslashes();
var plen = actb_curr.value.length;
var tobuild = '';
var i;
if (actb_self.actb_firstText){
var re = new RegExp("^" + t, "i");
}else{
var re = new RegExp(t, "i");
}
var p = n.search(re);
for (i=0;i<p;i++){
tobuild += n.substr(i,1);
}
tobuild += "<font style='"+(actb_self.actb_hStyle)+"'>"
for (i=p;i<plen+p;i++){
tobuild += n.substr(i,1);
}
tobuild += "</font>";
for (i=plen+p;i<n.length;i++){
tobuild += n.substr(i,1);
}
return tobuild;
}
function actb_generate(){
if (document.getElementById('tat_table')){ actb_display = false;document.body.removeChild(document.getElementById('tat_table')); }
if (actb_kwcount == 0){
actb_display = false;
return;
}
a = document.createElement('table');
a.cellSpacing='1px';
a.cellPadding='2px';
a.style.position='fixed';
a.style.zIndex=2147483647;
a.style.top = eval(curTop(actb_curr) + actb_curr.offsetHeight) + "px";
a.style.left = curLeft(actb_curr) + "px";
a.style.backgroundColor=actb_self.actb_bgColor;
a.style.width="auto";
a.id = 'tat_table';
document.body.appendChild(a);
var i;
var first = true;
var j = 1;
if (actb_self.actb_mouse){
a.onmouseout = actb_table_unfocus;
a.onmouseover = actb_table_focus;
}
var counter = 0;
//log("actb_generate actb_bool: " + actb_bool);
//log("actb_generate friendsName: " + friendsName);
for (i=0;i<friendsName.length;i++){
if (actb_bool[i]){
counter++;
r = a.insertRow(-1);
if (first && !actb_tomake){
r.style.backgroundColor = actb_self.actb_hColor;
r.style.color = actb_self.actb_hTextColor;
first = false;
actb_pos = counter;
}else if(actb_pre == i){
r.style.backgroundColor = actb_self.actb_hColor;
r.style.color = actb_self.actb_hTextColor;
first = false;
actb_pos = counter;
}else{
r.style.backgroundColor = actb_self.actb_bgColor;
}
r.id = 'tat_tr'+(j);
c = r.insertCell(-1);
//c.style.color = actb_self.actb_textColor;
c.style.fontFamily = actb_self.actb_fFamily;
c.style.fontSize = actb_self.actb_fSize;
c.style.textAlign = "left";
c.innerHTML = actb_parse(friendsName[i]);
c.id = 'tat_td'+(j);
c.setAttribute('pos',j);
if (actb_self.actb_mouse){
c.style.cursor = 'pointer';
c.onclick=actb_mouseclick;
c.onmouseover = actb_table_highlight;
}
j++;
}
if (j - 1 == actb_self.actb_lim && j < actb_total){
r = a.insertRow(-1);
r.style.backgroundColor = actb_self.actb_bgColor;
c = r.insertCell(-1);
c.style.color = actb_self.actb_textColor;
c.style.fontFamily = 'arial narrow';
c.style.fontSize = actb_self.actb_fSize;
c.align='center';
replaceHTML(c,'\\/');
if (actb_self.actb_mouse){
c.style.cursor = 'pointer';
c.onclick = actb_mouse_down;
}
break;
}
}
actb_rangeu = 1;
actb_ranged = j-1;
actb_display = true;
if (actb_pos <= 0) actb_pos = 1;
}
function actb_remake(){
document.body.removeChild(document.getElementById('tat_table'));
a = document.createElement('table');
a.cellSpacing='1px';
a.cellPadding='2px';
a.style.position='absolute';
a.style.top = eval(curTop(actb_curr) + actb_curr.offsetHeight) + "px";
a.style.left = curLeft(actb_curr) + "px";
a.style.backgroundColor=actb_self.actb_bgColor;
a.style.width="auto";
a.id = 'tat_table';
if (actb_self.actb_mouse){
a.onmouseout= actb_table_unfocus;
a.onmouseover=actb_table_focus;
}
document.body.appendChild(a);
var i;
var first = true;
var j = 1;
if (actb_rangeu > 1){
r = a.insertRow(-1);
r.style.backgroundColor = actb_self.actb_bgColor;
c = r.insertCell(-1);
c.style.color = actb_self.actb_textColor;
c.style.fontFamily = 'arial narrow';
c.style.fontSize = actb_self.actb_fSize;
c.align='center';
replaceHTML(c,'/\\');
if (actb_self.actb_mouse){
c.style.cursor = 'pointer';
c.onclick = actb_mouse_up;
}
}
for (i=0;i<friendsName.length;i++){
if (actb_bool[i]){
if (j >= actb_rangeu && j <= actb_ranged){
r = a.insertRow(-1);
r.style.backgroundColor = actb_self.actb_bgColor;
r.id = 'tat_tr'+(j);
c = r.insertCell(-1);
c.style.color = actb_self.actb_textColor;
c.style.fontFamily = actb_self.actb_fFamily;
c.style.fontSize = actb_self.actb_fSize;
c.style.textAlign = "left";
c.innerHTML = actb_parse(friendsName[i]);
c.id = 'tat_td'+(j);
c.setAttribute('pos',j);
if (actb_self.actb_mouse){
c.style.cursor = 'pointer';
c.onclick=actb_mouseclick;
c.onmouseover = actb_table_highlight;
}
j++;
}else{
j++;
}
}
if (j > actb_ranged) break;
}
if (j-1 < actb_total){
r = a.insertRow(-1);
r.style.backgroundColor = actb_self.actb_bgColor;
c = r.insertCell(-1);
c.style.color = actb_self.actb_textColor;
c.style.fontFamily = 'arial narrow';
c.style.fontSize = actb_self.actb_fSize;
c.align='center';
replaceHTML(c,'\\/');
if (actb_self.actb_mouse){
c.style.cursor = 'pointer';
c.onclick = actb_mouse_down;
}
}
}
function actb_goup(){
if (!actb_display) return;
if (actb_pos == 1) return;
var row;
row = document.getElementById('tat_tr'+actb_pos)
row.style.backgroundColor = actb_self.actb_bgColor;
row.style.color = actb_self.actb_textColor;
actb_pos--;
if (actb_pos < actb_rangeu) actb_moveup();
row = document.getElementById('tat_tr'+actb_pos);
row.style.backgroundColor = actb_self.actb_hColor;
row.style.color = actb_self.actb_hTextColor;
if (actb_toid) clearTimeout(actb_toid);
if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_self.actb_timeOut);
}
function actb_godown(){
if (!actb_display) return;
if (actb_pos == actb_total) return;
var row;
row = document.getElementById('tat_tr'+actb_pos);
row.style.backgroundColor = actb_self.actb_bgColor;
row.style.color = actb_self.actb_textColor;
actb_pos++;
if (actb_pos > actb_ranged) actb_movedown();
row = document.getElementById('tat_tr'+actb_pos)
row.style.backgroundColor = actb_self.actb_hColor;
row.style.color = actb_self.actb_hTextColor;
if (actb_toid) clearTimeout(actb_toid);
if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_self.actb_timeOut);
}
function actb_movedown(){
actb_rangeu++;
actb_ranged++;
actb_remake();
}
function actb_moveup(){
actb_rangeu--;
actb_ranged--;
actb_remake();
}
/* Mouse */
function actb_mouse_down(){
var row;
row = document.getElementById('tat_tr'+actb_pos);
row.style.backgroundColor = actb_self.actb_bgColor;
row.style.color = actb_self.actb_textColor;
actb_pos++;
actb_movedown();
row = document.getElementById('tat_tr'+actb_pos)
row.style.backgroundColor = actb_self.actb_hColor;
row.style.color = actb_self.actb_hTextColor;
actb_curr.focus();
actb_mouse_on_list = 0;
if (actb_toid) clearTimeout(actb_toid);
if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_self.actb_timeOut);
}
function actb_mouse_up(evt){
if (!evt) evt = event;
if (evt.stopPropagation){
evt.stopPropagation();
}else{
evt.cancelBubble = true;
}
var row;
row = document.getElementById('tat_tr'+actb_pos);
row.style.backgroundColor = actb_self.actb_bgColor;
row.style.color = actb_self.actb_textColor;
actb_pos--;
actb_moveup();
row = document.getElementById('tat_tr'+actb_pos)
row.style.backgroundColor = actb_self.actb_hColor;
row.style.color = actb_self.actb_hTextColor;
actb_curr.focus();
actb_mouse_on_list = 0;
if (actb_toid) clearTimeout(actb_toid);
if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_self.actb_timeOut);
}
function actb_mouseclick(evt){
if (!evt) evt = event;
if (!actb_display) return;
actb_mouse_on_list = 0;
actb_pos = this.getAttribute('pos');
actb_penter();
}
function actb_table_focus(){
actb_mouse_on_list = 1;
}
function actb_table_unfocus(){
actb_mouse_on_list = 0;
if (actb_toid) clearTimeout(actb_toid);
if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list = 0;actb_removedisp();},actb_self.actb_timeOut);
}
function actb_table_highlight(){
actb_mouse_on_list = 1;
var row;
row = document.getElementById('tat_tr'+actb_pos);
row.style.backgroundColor = actb_self.actb_bgColor;
row.style.color = actb_self.actb_textColor;
actb_pos = this.getAttribute('pos');
while (actb_pos < actb_rangeu) actb_moveup();
while (actb_pos > actb_ranged) actb_movedown();
row = document.getElementById('tat_tr'+actb_pos)
row.style.backgroundColor = actb_self.actb_hColor;
row.style.color = actb_self.actb_hTextColor;
if (actb_toid) clearTimeout(actb_toid);
if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list = 0;actb_removedisp();},actb_self.actb_timeOut);
}
/* ---- */
function actb_insertfriend(nameFoundPos){
/*<div id="shopinionSearchFriendsBox" class="clearfix">
<span class="shopinionFriendDiv">
Johnson Liu
<img src="https://s3.amazonaws.com/shopinionapp/assets/images/cross.png" class="shopinionRemoveFriend" href="#">
<input type="hidden" value="12345" name="requestFbString" autocomplete="off">
</span>
</div>*/
//log("friends: " + JSON.stringify(friends));
var friendsSpan = document.getElementById("shopinionFriendsSpan");
var friendSpan = document.createElement("span");
friendSpan.className = "shopinionFriendSpan";
friendSpan.innerHTML=friendsName[nameFoundPos] + "<input type='hidden' value='"+friends[nameFoundPos].fbId+"' name='requestFbString'>";
var removeImg = document.createElement("img");
removeImg.className = "shopinionRemoveFriend";
removeImg.src = "https://s3.amazonaws.com/shopinionapp/assets/images/cross.png";
friendSpan.appendChild(removeImg);
friendsSpan.appendChild(friendSpan);
var fbId= friends[nameFoundPos].fbId;
var name = friendsName[nameFoundPos];
removeImg.onclick=function(){
friendsSpan.removeChild(friendSpan);
friendsName.push(name);
friends.push({"fbId":fbId, "name":name});return false;}
friends.splice(nameFoundPos, 1);
friendsName.splice(nameFoundPos, 1);
actb_curr.value = "";
actb_mouse_on_list = 0;
actb_removedisp();
}
function actb_penter(){
if (!actb_display) return;
actb_display = false;
var word = '';
var nameFoundPos;
var c = 0;
for (var i=0;i<=friendsName.length;i++){
if (actb_bool[i]) c++;
if (c == actb_pos){
word = friendsName[i];
nameFoundPos = i;
break;
}
}
actb_insertfriend(nameFoundPos);
l = getCaretStart(actb_curr);
}
function actb_removedisp(){
if (actb_mouse_on_list==0){
actb_display = 0;
if (document.getElementById('tat_table')){ document.body.removeChild(document.getElementById('tat_table')); }
if (actb_toid) clearTimeout(actb_toid);
}
}
function actb_keypress(e){
if (actb_caretmove) stopEvent(e);
return !actb_caretmove;
}
function actb_checkkey(evt){
actb_curr.placeholder="";
if (!evt) evt = event;
a = evt.keyCode;
caret_pos_start = getCaretStart(actb_curr);
actb_caretmove = 0;
switch (a){
case 38:
actb_goup();
actb_caretmove = 1;
return false;
break;
case 40:
actb_godown();
actb_caretmove = 1;
return false;
break;
case 13: case 9:
if (actb_display){
actb_caretmove = 1;
actb_penter();
return false;
}else{
return true;
}
break;
default:
var input = document.getElementById("shopinionFriendsInput");
var width=input.style.width;
var widthNum = parseInt(width.substring(0, width.indexOf("px")),10);
/* the initial width is 300 for wider click area. Once the user clicks,
the input width is changed to 24. As the user types, the width
is lengthened. If the user clicks backspace, the width is shortened.
*/
if (widthNum == 300)
widthNum = 24;
if (a!=8) { // not backspace
/*log("input width: " + input.style.width);
log("blah: " + width.substring(0, width.indexOf("px")));*/
input.style.width = widthNum + 8 +"px";
} else {
if (widthNum >=32) {
input.style.width = widthNum - 8 +"px";
}
if (widthNum == 24) {
input.style.width=300;
}
}
setTimeout(function(){actb_tocomplete(a)},50);
break;
}
}
function actb_tocomplete(kc){
if (kc == 38 || kc == 40 || kc == 13) return;
var i;
if (actb_display){
var word = 0;
var c = 0;
for (var i=0;i<=friendsName.length;i++){
if (actb_bool[i]) c++;
if (c == actb_pos){
word = i;
break;
}
}
actb_pre = word;
}else{ actb_pre = -1};
if (actb_curr.value == ''){
actb_mouse_on_list = 0;
actb_removedisp();
return;
}
var ot = actb_curr.value;
var t = actb_curr.value.addslashes();
if (ot.length == 0){
actb_mouse_on_list = 0;
actb_removedisp();
}
if (ot.length < actb_self.actb_startcheck) return this;
if (actb_self.actb_firstText){
var re = new RegExp("^" + t, "i");
}else{
var re = new RegExp(t, "i");
}
actb_total = 0;
actb_tomake = false;
actb_kwcount = 0;
for (i=0;i<friendsName.length;i++){
actb_bool[i] = false;
if (re.test(friendsName[i])){
actb_total++;
actb_bool[i] = true;
actb_kwcount++;
if (actb_pre == i) actb_tomake = true;
}
}
if (actb_toid) clearTimeout(actb_toid);
if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list = 0;actb_removedisp();},actb_self.actb_timeOut);
actb_generate();
}
/* Event Functions */
// Add an event to the obj given
// event_name refers to the event trigger, without the "on", like click or mouseover
// func_name refers to the function callback when event is triggered
function addEvent(obj,event_name,func_name){
if (obj.attachEvent){
obj.attachEvent("on"+event_name, func_name);
}else if(obj.addEventListener){
obj.addEventListener(event_name,func_name,true);
}else{
obj["on"+event_name] = func_name;
}
}
// Removes an event from the object
function removeEvent(obj,event_name,func_name){
if (obj.detachEvent){
obj.detachEvent("on"+event_name,func_name);
}else if(obj.removeEventListener){
obj.removeEventListener(event_name,func_name,true);
}else{
obj["on"+event_name] = null;
}
}
// Stop an event from bubbling up the event DOM
function stopEvent(evt){
evt || window.event;
if (evt.stopPropagation){
evt.stopPropagation();
evt.preventDefault();
}else if(typeof evt.cancelBubble !== "undefined"){
evt.cancelBubble = true;
evt.returnValue = false;
}
return false;
}
/* Caret Functions */
// Get the start position of the caret in the object
function getCaretStart(obj){
if(typeof obj.selectionStart !== "undefined"){
return obj.selectionStart;
}else if(document.selection&&document.selection.createRange){
var M=document.selection.createRange();
try{
var Lp = M.duplicate();
Lp.moveToElementText(obj);
}catch(e){
var Lp=obj.createTextRange();
}
Lp.setEndPoint("EndToStart",M);
var rb=Lp.text.length;
if(rb>obj.value.length){
return -1;
}
return rb;
}
}
/* Escape function */
String.prototype.addslashes = function(){
return this.replace(/(["\\\.\|\[\]\^\*\+\?\$\(\)])/g, '\\$1');
}
String.prototype.trim = function () {
return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};
/* --- Escape --- */
/* Offset position from top of the screen */
function curTop(obj){
toreturn = 0;
while(obj){
toreturn += obj.offsetTop;
obj = obj.offsetParent;
}
return toreturn;
}
function curLeft(obj){
toreturn = 0;
while(obj){
toreturn += obj.offsetLeft;
obj = obj.offsetParent;
}
return toreturn;
}
/* ------ End of Offset function ------- */
/* Types Function */
/* Object Functions */
function replaceHTML(obj,text){
while(el = obj.childNodes[0]){
obj.removeChild(el);
};
obj.appendChild(document.createTextNode(text));
}
}
}
function openChatWindowAndSubscribeSubjectChannel(myJQ, myFbId, myMemberId, myName, subjectId) {
if(typeof Pusher === 'undefined') {
if (!loadingPusher) {
var e=document.createElement('script');
e.setAttribute('type','text/javascript');
e.setAttribute('charset','UTF-8');
e.setAttribute('src','http://js.pusher.com/1.12/pusher.min.js');
document.body.appendChild(e);
loadingPusher = true;
}
setTimeout(function(){ openChatWindowAndSubscribeSubjectChannel(myJQ, myFbId, myMemberId, myName, subjectId);},1000);
log("delay open window: " + subjectId);
return;
}
log("open window: " + subjectId);
var pusher;
var channelSubscribe = false;
var channel;
var socket_id;
// make sure the chat window is not open yet
if (myJQ("#chatWindow-" + subjectId).length == 0) {
pusher = new Pusher('6d789ee7962a9d80cbb4', { encrypted: true } );
Pusher.channel_auth_endpoint = "http://"+SHOPINION_DOMAIN +"/webPusherAuthGet";
Pusher.channel_auth_transport = "jsonp";
//log("auth endpoint: " + Pusher.channel_auth_endpoint);
channel = pusher.subscribe('presence-subject-'+subjectId);
pusher.connection.bind('connected', function() {
socket_id = (pusher.connection.socket_id != null)? pusher.connection.socket_id : pusher.socket_id;
log("connected: " + socket_id);
});
/*pusher.bind_all(function(data) {
log("bind_all: " + data);
});*/
// retrieve previous conversation
currentAjax = myJQ.ajax({
url:"http://" + SHOPINION_DOMAIN + "/getMsg/"+subjectId,
type: "GET",
dataType:"jsonp",
timeout: 200000,
success: function(result) {
log("Received previous chat messages for " + subjectId);
createChatWindow(subjectId, myMemberId, result);
}
});
}
function createChatWindow(subjectId, myMemberId, data) {
var cssCode = [".shopinionChatWindowPositionWrapper {margin: 0 10px;float: right;position: relative;padding: 2px 3px;width: 300px;height: 100%;}",
".shopinionChatWindow {visibility: visible;background: none repeat scroll 0 0 #E3E2E2;border-color: #C3C3C3;border-style: solid solid none;border-width: 1px 1px medium;position: absolute;bottom: 0;width: 300px; color:black;}",
".shopinionChatWindow table, .shopinionChatWindow td, .shopinionChatWindow tr {padding: 0; border:none none;}",
".shopinionChatWindowIcon {width: 15px;height: 15px;margin: 2px auto;cursor: pointer;}",
".shopinionChatWindowLeftIcon {margin-left: 2px;margin-right: 1px;}",
".shopinionChatWindowRightIcon {margin-left: 6px;margin-right: 4px;}",
".shopinionChatWindowHeader {background-color: rgba(45, 45, 45, 0.88);background-image: -moz-linear-gradient(center top , transparent 0%, #000000 100%);border: 1px solid rgba(255, 255, 255, 0.25);box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);color: #FFFFFF;font-size: 13px;height: 16px;padding: 5px 10px;text-shadow: 0 0 2px #000000;width: 100%;text-align: left;cursor: pointer;margin: 0;}",
".shopinionChatWindowBlockList {border-bottom: 1px solid #E4E4E4;list-style: none outside none;margin: 0;overflow-x: hidden;overflow-y: scroll;padding: 0;width: 100%;height: 210px;}",
".shopinionChatWindowOpen {}",
".shopinionChatWindowMessage {margin: 0px 10px;font: 11px;}",
".shopinionChatWindowBlock {margin-left: 0px;margin-right: auto;text-align: left;border-bottom: 1px solid rgba(0, 0, 0, 0.2);font-size: 12px;line-height: 20px;}",
".shopinionChatWindowBlock img {height:30px;width:30px;margin-left:5px;}",
".shopinionChatWindowText {width: 95%;margin: 1px auto;}",
".shopinionChatWindowTextWrapper {margin: 4px !important;}",
".shopinionChatWindowInfoImage {margin: 10px auto;max-height:150px;max-width:200px;}",
".shopinionChatWindowVoteImg {width: 20px;height: 20px;}",
".shopinionChatWindowInfo {background-color: #FFFFFF;color: #000000;font-size: 13px;width: 100%;text-align: left;}",
".shopinionChatWindowInfoHeader {padding: 5px 10px;height: 16px;width: 100%;}",
".shopinionChatWindowVoteTable table, .shopinionChatWindowVoteTable th,.shopinionChatWindowVoteTable td {border:1px solid green;background-color: #FAF0E6;border-collapse: collapse;}",
".shopinionChatPersonName {margin: 0px 10px;font: 10px;font-weight: bold;}",
".shopinionChatMessage {margin: 0px 10px;font: 11px;}",
".shopinionChatWindowHeader tr td{padding-bottom: 3px;}"]
if (document.getElementById("shopinionChat") == null) {
addCss(cssCode.join("\n"), "shopinionChat");
var chatLayer = document.createElement("div");
chatLayer.id="shopinionChatLayer";
document.body.appendChild(chatLayer);
}
myJQ("#shopinionChatLayer").append("<div class='shopinionChatWindowPositionWrapper' id='shopinionChatWindow-"+subjectId+"'>"+
"<div class='shopinionChatWindow'>" +
"<table class='shopinionChatWindowHeader' id='shopinionChatWindowHeader-"+subjectId+"' cellspacing='0' cellpadding='0' border='0'>" +
"<tbody>"+
"<tr>"+
"<td width='90%'>" + data.caption + "</td>" +
"<td><img id='shopinionChatWindow-"+subjectId+"-M' class='shopinionChatWindowIcon shopinionChatWindowLeftIcon' src='http://s3.amazonaws.com/shopinionapp/assets/images/br_down_icon&16.png'></td>"+
"<td><img id='shopinionChatWindow-"+subjectId+"-C' class='shopinionChatWindowIcon shopinionChatWindowRightIcon' src='http://s3.amazonaws.com/shopinionapp/assets/images/app_window_cross&16.png'></td>"+
"</tr>" +
"</tbody>" +
"</table>" +
"<div id='shopinionChatWindow-"+subjectId+"-body'>"+
"<div class='shopinionChatWindowInfo' id='shopinionChatWindowInfo-"+subjectId+"'>"+
"<table class='shopinionChatWindowInfoHeader' id='shopinionChatWindowInfoHeader-"+subjectId+"' cellspacing='0' cellpadding='0' border='0'>" +
"<tbody>"+
"<tr>"+
"<td width='90%' id='shopinionChatWindowInfoImageCell-"+subjectId+"' rowspan='2' style='text-align:left;'>Info</td>"+
"<td><img id='shopinionChatWindowInfo-"+subjectId+"-M' class='shopinionChatWindowIcon shopinionChatWindowLeftIcon' src='http://s3.amazonaws.com/shopinionapp/assets/images/down_arrow_icon&16.png'></td>"+
"<td><img id='shopinionChatWindowInfo-"+subjectId+"-C' class='shopinionChatWindowIcon shopinionChatWindowRightIcon' src='http://s3.amazonaws.com/shopinionapp/assets/images/app_window_cross_black&16.png'></td>"+
"</tr>" +
"<tr>" +
"<td colspan='2'>" +
"<table border='1' id='shopinionChatWindowVoteTable-"+subjectId+"' class='shopinionChatWindowVoteTable' cellspacing='0' cellpadding='0' style='display:none'>" +
"<tbody>" +
"<tr>"+
"<td><img class='shopinionChatWindowVoteImg' alt='yes image' src='http://s3.amazonaws.com/shopinionapp/assets/images/ct_yes.png'></td>"+
"<td>" + data.yesVote + "</td>"+
"</tr>"+
"<tr>"+
"<td><img class='shopinionChatWindowVoteImg' alt='no image' src='http://s3.amazonaws.com/shopinionapp/assets/images/ct_no.png'></td>"+
"<td>" + data.noVote + "</td>"+
"</tr>"+
"</tbody>"+
"</table>"+
"</td>" +
"</tr>" +
"</tbody>" +
"</table>" +
"</div>" +
"<ul id='shopinionChatWindowBlockList-" + subjectId + "' class='shopinionChatWindowBlockList'>" +
/*<li class="chatWindowBlock">
<img src="dashboard_files/picture.jpeg"> <span class="forumPersonName">Johnson&nbsp;Liu</span>
<span class="forumMessage"> hello</span><br>
</li>*/
"</ul>"+
"<div class='shopinionChatWindowTextWrapper'>"+
"<textarea id='shopinionChatWindowText-"+subjectId+"' class='shopinionChatWindowText'></textarea>"+
"</div>"+
"</div>"+
"</div>"+
"</div>");
// load messages
for (i in data.messages) {
myJQ("#shopinionChatWindowBlockList-" + subjectId).append(
"<li class='shopinionChatWindowBlock'>" +
"<img src='https://graph.facebook.com/"+data.messages[i].fbId+"/picture?type=square'> <span class='shopinionChatPersonName'>"+data.messages[i].name+"</span>" +
"<span class='shopinionChatMessage'>"+data.messages[i].message+"</span><br>" +
"</li>");
}
//log("done appending chat messages for " + subjectId);
myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollTop",myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollHeight") - myJQ("#shopinionChatWindowBlockList-" + subjectId).height());
channel.bind('new-message', function(message) {
//log("received message: " + message.message);
if (message.fromFacebookId != null) {
myJQ("#shopinionChatWindowBlockList-" + subjectId).append('<li class="shopinionChatWindowBlock"><img src="https://graph.facebook.com/' + message.fromFacebookId + '/picture?type=square" /><span class="shopinionChatPersonName">' +
unescape(message.name).replace(/\+/g," ") + '</span><span class="shopinionChatMessage">' + unescape(message.message).replace(/\+/g," ") + '</span><br/></li>');
}
myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollTop", myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollHeight") - myJQ("#shopinionChatWindowBlockList-" + subjectId).height());
//log("scrollTop, " + myJQ("#chatWindowBlockList-" + subjectId).prop("scrollHeight") + ", "+ myJQ("#chatWindowBlockList-" + subjectId).height());
});
// inform the server that a member has been removed from this subject channel
channel.bind('pusher:member_removed', function(member) {
log("removing member: " + member.id);
xhr.request({
url: "/pusherpurge",
method: "POST",
data: {channelName: "presence-subject-"+subjectId,
memberId: member.id,
referringUrl: document.URL}
});
/*myJQ.ajax({
type: "POST",
url: "http://" + SHOPINION_DOMAIN + "/pusherpurge",
data: {channelName: "presence-subject-"+subjectId,
memberId: member.id}
})*/
});
myJQ("#shopinionChatWindow-"+subjectId+"-M").click(function() {
if (myJQ(this).attr("src") == "http://s3.amazonaws.com/shopinionapp/assets/images/br_down_icon&16.png") {
myJQ(this).attr("src", "http://s3.amazonaws.com/shopinionapp/assets/images/br_up_icon&16.png");
} else {
myJQ(this).attr("src", "http://s3.amazonaws.com/shopinionapp/assets/images/br_down_icon&16.png");
}
myJQ("#shopinionChatWindow-"+subjectId+"-body").toggle();
return false;
});
myJQ("#shopinionChatWindowHeader-"+subjectId).click(function() {
if (myJQ(this).attr("src") == "http://s3.amazonaws.com/shopinionapp/assets/images/br_down_icon&16.png") {
myJQ(this).attr("src", "http://s3.amazonaws.com/shopinionapp/assets/images/br_up_icon&16.png");
} else {
myJQ(this).attr("src", "http://s3.amazonaws.com/shopinionapp/assets/images/br_down_icon&16.png");
}
myJQ("#shopinionChatWindow-"+subjectId+"-body").toggle();
return false;
});
myJQ("#shopinionChatWindow-"+subjectId+"-C").click(function() {
myJQ("#shopinionChatWindow-"+subjectId).remove();
pusher.unsubscribe('presence-subject-'+subjectId);
log("removing subject channel " + subjectId + " member: " + myMemberId);
xhr.request({
url: "/pusherpurge",
method: "POST",
data: {channelName: "presence-subject-"+subjectId,
memberId: myMemberId,
windowClosing: true,
referringUrl: document.URL}
});
/*myJQ.ajax({
type: "POST",
url: "http://"+SHOPINION_DOMAIN + "/pusherpurge",
data: {channelName: "presence-subject-"+subjectId,
memberId: myMemberId,
windowClosing: true}
})*/
return false;
});
myJQ("#shopinionChatWindowInfo-"+subjectId+"-M").click(function() {
var blockList = myJQ("#shopinionChatWindowBlockList-"+subjectId);
if (blockList.css("height") == "210px") {
blockList.css("height", "60");
} else {
blockList.css("height", "210");
}
var voteTable = myJQ("#shopinionChatWindowVoteTable-"+subjectId);
var imageCell = document.getElementById("shopinionChatWindowInfoImageCell-"+subjectId);
voteTable.toggle();
/* when info exist, point the arrow up to signal it can go up*/
if (voteTable.css("display") == "table") {
myJQ(this).attr("src", "http://s3.amazonaws.com/shopinionapp/assets/images/up_arrow_icon&16.png");
imageCell.innerHTML = "<img class='shopinionChatWindowInfoImage' src='"+data.image+"'>";
imageCell.style.textAlign = "center";
myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollTop",myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollHeight") - myJQ("#shopinionChatWindowBlockList-" + subjectId).height());
} else {
myJQ(this).attr("src", "http://s3.amazonaws.com/shopinionapp/assets/images/down_arrow_icon&16.png");
imageCell.innerHTML = "Info";
imageCell.style.textAlign = "left";
myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollTop",myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollHeight") - myJQ("#shopinionChatWindowBlockList-" + subjectId).height());
}
return false;
});
myJQ("#shopinionChatWindowInfoHeader-"+subjectId).click(function() {
var blockList = myJQ("#shopinionChatWindowBlockList-"+subjectId);
if (blockList.css("height") == "210px") {
blockList.css("height", "60");
} else {
blockList.css("height", "210");
}
var mInfoIcon = myJQ("#shopinionChatWindowInfo-"+subjectId+"-M");
var voteTable = myJQ("#shopinionChatWindowVoteTable-"+subjectId);
var imageCell = document.getElementById("shopinionChatWindowInfoImageCell-"+subjectId);
voteTable.toggle();
if (voteTable.css("display") == "table") {
mInfoIcon.attr("src", "http://s3.amazonaws.com/shopinionapp/assets/images/up_arrow_icon&16.png");
imageCell.innerHTML = "<img class='shopinionChatWindowInfoImage' src='"+data.image+"'>";
imageCell.style.textAlign = "center";
myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollTop",myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollHeight") - myJQ("#shopinionChatWindowBlockList-" + subjectId).height());
} else {
mInfoIcon.attr("src", "http://s3.amazonaws.com/shopinionapp/assets/images/down_arrow_icon&16.png");
imageCell.innerHTML = "Info";
imageCell.style.textAlign = "left";
myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollTop",myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollHeight") - myJQ("#shopinionChatWindowBlockList-" + subjectId).height());
}
return false;
});
myJQ("#shopinionChatWindowInfo-"+subjectId+"-C").click(function() {
myJQ("#shopinionChatWindowInfo-"+subjectId).remove();
return false;
});
myJQ("#shopinionChatWindowText-"+subjectId).keypress(function(event) {
if (event.keyCode == 13 && !event.altKey && !event.ctrlKey && !event.shiftKey) {
sendMessage();
event.preventDefault();
}
})
log("done loading chat window for " + subjectId);
function sendMessage() {
xhr.request({
url: "/sendMsg",
method: "POST",
data: {socket_id: socket_id,
subjectId: subjectId,
message: myJQ("#shopinionChatWindowText-"+subjectId).val(),
referringUrl: document.URL
},
});
/*myJQ.ajax({
type: "POST",
url: "http://" + SHOPINION_DOMAIN + "/sendMsg",
xhrFields: {
withCredentials: true
},
data: "socket_id=" + socket_id + "&subjectId="+subjectId+"&message=" + encodeURIComponent(myJQ("#shopinionChatWindowText-"+subjectId).val())
})*/
//log(socket_id + ", " + subjectId + " sending:" + myJQ("#chatWindowText-"+subjectId).val());
myJQ("#shopinionChatWindowBlockList-" + subjectId).append(
"<li class='shopinionChatWindowBlock'>" +
"<img src='https://graph.facebook.com/"+myFbId+"/picture?type=square'> <span class='shopinionChatPersonName'>"+myName+"</span>" +
"<span class='shopinionChatMessage'>"+myJQ("#shopinionChatWindowText-"+subjectId).val()+"</span><br>" +
"</li>");
myJQ("#shopinionChatWindowText-"+subjectId).val('');
myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollTop",myJQ("#shopinionChatWindowBlockList-" + subjectId).prop("scrollHeight") - myJQ("#shopinionChatWindowBlockList-" + subjectId).height());
//log("scrollTop, " + myJQ("#chatWindowBlockList-" + subjectId).prop("scrollHeight") + ", "+ myJQ("#chatWindowBlockList-" + subjectId).height());
}
}
}
var getElementsByClassName = function (className, tag, elm){
if (document.getElementsByClassName) {
getElementsByClassName = function (className, tag, elm) {
elm = elm || document;
var elements = elm.getElementsByClassName(className),
nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
returnElements = [],
current;
for(var i=0, il=elements.length; i<il; i+=1){
current = elements[i];
if(!nodeName || nodeName.test(current.nodeName)) {
returnElements.push(current);
}
}
return returnElements;
};
}
else if (document.evaluate) {
getElementsByClassName = function (className, tag, elm) {
tag = tag || "*";
elm = elm || document;
var classes = className.split(" "),
classesToCheck = "",
xhtmlNamespace = "http://www.w3.org/1999/xhtml",
namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
returnElements = [],
elements,
node;
for(var j=0, jl=classes.length; j<jl; j+=1){
classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
}
try {
elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
}
catch (e) {
elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
}
while ((node = elements.iterateNext())) {
returnElements.push(node);
}
return returnElements;
};
}
else {
getElementsByClassName = function (className, tag, elm) {
tag = tag || "*";
elm = elm || document;
var classes = className.split(" "),
classesToCheck = [],
elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
current,
returnElements = [],
match;
for(var k=0, kl=classes.length; k<kl; k+=1){
classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
}
for(var l=0, ll=elements.length; l<ll; l+=1){
current = elements[l];
match = false;
for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
match = classesToCheck[m].test(current.className);
if (!match) {
break;
}
}
if (match) {
returnElements.push(current);
}
}
return returnElements;
};
}
return getElementsByClassName(className, tag, elm);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment