Skip to content

Instantly share code, notes, and snippets.

@angeloh
Created September 10, 2012 20:15
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/3693557 to your computer and use it in GitHub Desktop.
Save angeloh/3693557 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 = function(){
if(typeof jQuery === 'undefined' || 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");
}
// if(typeof jQuery.ui === 'undefined' || typeof jQuery.ui.version !== '1.8.23') {
// 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";
// head.appendChild(e);
// log("loading jQuery UI CSS");
// }
// }
} // -- window.onload END
//$(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.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");
}
}*/
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");
}
/* see if we need to load JSON */
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");
}
/* implementation for getElementsByClassName, all for IE */
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);
};
function log(statement) {
if (console != undefined && console != null &&
console.log != undefined && console.log != null) {
console.log(statement);
}
}
/* insert CSS code into the page */
function addCss(cssCode, id) {
if (document.getElementById(id) != null) {
log(id + " has been inserted before");
return;
}
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);
}
/* installFixedWidget: install "Chat With Friends" bar.*/
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: 170px; height: 100%;}",
"#shopinionTabDiv {width: 170px !important; background-color: #EF700B; border-radius: 3px 3px 0px 0px; font: bold 14px Trebuchet MS, Tahoma, Verdana, 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;}
}
/* getExistingChat and open chat windows */
function getExistingChat() {
jQuery.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(jQuery, myFbId, myMemberId, myName, subjectIds[ii].subjectId);
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
log("error");
log(jqXHR + ", " +textStatus +", " +errorThrown);
}
});
}
/* initialize: initialize is called after each script file is loaded. After all necessary
* files are loaded, start initializing: get existing chat, initialize cross domain
* communication.
*/
function initialize() {
if(initialized ||
typeof jQuery === 'undefined' ||
typeof jQuery.ajax === 'undefined' ||
// typeof jQuery.ui === 'undefined' ||
typeof jQuery.isArray === 'undefined' ||
typeof jQuery.parseJSON === 'undefined' ||
typeof easyXDM === 'undefined' ||
typeof JSON === 'undefined' || !JSON) {
return;
}
var cssCode =[
".shopinionReset {font-family:'Trebuchet MS', Helvetica, sans-serif;font-size: 12px;font-weight: normal;font-style: normal;color: black;line-height: normal;margin: 0;padding: 0;}",
".shopinionReset * {color: black;font: inherit;border: 0;margin: 0;padding: 0;border: 0;font-size: 100%;vertical-align: baseline;}",
".shopinionReset a {text-decoration: none;}",
".shopinionReset div,.shopinionReset pre {display: block;}",
".shopinionReset table {display: table;table-layout: auto;border-spacing: 0;border-collapse: collapse;}",
".shopinionReset tr {display: table-row;vertical-align: inherit;}",
".shopinionReset td, .shopinionReset th {display: table-cell;vertical-align: inherit;}",
".shopinionReset button,.shopinionReset textarea,.shopinionReset input {display: inline-block;}",
];
addCss(cssCode.join("\n"), "shopinionResetCSS");
xhr = new easyXDM.Rpc({
remote: "http://" + SHOPINION_DOMAIN + "/assets/html/cors.html",
}, {
remote: {
request:{}
}
});
getExistingChat();
initialized=true;
installFixedWidget();
}
/* initializeBookmarklet: handler for clicking and opening the bookmarklet popup window. */
function initializeBookmarklet() {
if(initialized) {
getFbFriendsJson();
} else {
// TODO should not happen, remove button?
initialize();
}
}
/* getFbFriendsJson: get friends list. If the friends list is null, ask the user to log in.
* If the list is not null, display the selection window.
*/
function getFbFriendsJson() {
jQuery.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();
}
},
error: function(jqXHR, textStatus, errorThrown) {
log("error");
log(jqXHR + ", " +textStatus +", " +errorThrown);
}
});
}
/* displayLogin: display login area so that the user can click to start logging in. */
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);
jQuery("#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
}
});
jQuery("#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;
});
}
/* handleLoginMessage: receive inter-window message. When data.data=authorized,
* the user is done facebook authenticating, and we can get the friends list.
*/
function handleLoginMessage(data) {
log("data.data: " + data.data);
if (data.origin=="http://"+SHOPINION_DOMAIN && data.data=="authorized") {
log("getFbFriendsJson again");
getFbFriendsJson();
}
}
/* handleLogoutMessage: receive inter-window message. When data.data=loggedout,
* the user is logged out.
*/
function handleLogoutMessage(data) {
log("data.data: " + data.data);
if (data.origin=="http://"+SHOPINION_DOMAIN && data.data=="loggedout") {
removeEverything();
}
}
/* displaySelection: display the main selection window so that the user can select picture and
* friends to chat with.
*/
function displaySelection() {
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:#666666;bottom:0;left:0;opacity:0.9;position:fixed;right:0;top:0;z-index:2147483646;}",
"#shopinionSelectWrapperDiv {position:fixed;top:20px;right: 50px;height:260px;left:275px; width: 760px;border-radius: 8px 8px 8px 8px !important;background-color: #dddddd;text-align:left;z-index:2147483647; font-family:'Trebuchet MS', Helvetica, sans-serif;box-shadow: 20px 20px 10px #222222;}",
"#shopinionSelectWrapperDiv table td {border:none; padding: 2px;margin:0;}",
"#shopinionSelectWrapperDiv table {margin: 0px;padding:0;}",
".shopinionPoweredSpan {font-size:12px;color:#666666;padding-left:10px;}",
"#shopinionSelectImageDiv img { max-width: 200px; max-height: 200px; }",
"#shopinionSelectImageDiv {text-align:center;vertical-align:middle;}",
".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;}",
"#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: 4px 4px 4px 4px;background: none repeat scroll 0 0 #FFFFFF;direction:ltr;margin-top: 5px;padding: 0px 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;}",
"a.shopinionAnchorClass:link {text-decoration:underline;}",
"a.shopinionAnchorClass:hover {text-decoration:none;}",
];
addCss(cssCode.join("\n"),"shopinionSelectionCSS");
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 - 760) / 2 + "px";
var temp = (window.screen.availHeight - 260) / 2 - 100;
if (temp < 0) {
temp = 30;
}
wrapperDiv.style.top=temp + "px";
document.body.appendChild(wrapperDiv);
var imageArray=[];
var currentImage = 0;
for(ii in document.images) {
if (document.images[ii].clientWidth >= 100 && document.images[ii].clientHeight >= 100) {
imageArray.push(document.images[ii].src);
}
}
if (imageArray.length==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";
wrapperDiv.innerHTML="Sorry, no image is large enough to be sent.";
setTimeout(removeEverything, 5000);
backgroundDiv.addEventListener("click", removeEverything);
return;
}
wrapperDiv.innerHTML="<img id='shopinionCancelButton' src='https://s3.amazonaws.com/shopinionapp/assets/images/cross_64.png'>" +
"<input id='shopinionImgSrc' type='hidden'>" +
"<table style='margin-bottom: 10px;'>" +
"<tr>" +
"<td style='vertical-align:middle;'>" +
"<table height='100%' width='270px'>" +
"<tr>" +
"<td width='25px;' style='text-align:center;vertical-align:middle;'>" +
"<img id='shopinionPreviousImageArrow' src='https://s3.amazonaws.com/shopinionapp/assets/images/previous_24.png' style='cursor:pointer;'>" +
"</td>" +
"<td width='210px' height='210px' id='shopinionSelectImageDiv'>" +
"<img id='shopinionSelectImageDisplay'>" +
"</td>" +
"<td width='25px;' style='text-align:center;vertical-align:middle;'>" +
"<img id='shopinionNextImageArrow' src='https://s3.amazonaws.com/shopinionapp/assets/images/next_24.png' style='cursor:pointer;'>" +
"</td>" +
"</tr>" +
"<tr>" +
"<td colspan='3' style='line-height: 14px;'>" +
"<span class='shopinionPoweredSpan'>Powered by <a href='http://www.shopinion.me' target='_blank' class='shopinionAnchorClass'>Shopinion</a></span>" +
"</td>" +
"</tr>" +
"</table>" +
"</td>" +
"<td style='border-width: 0px;' width='95%'>" +
"<table>" +
"<tr>" +
"<td class='shopinionTitleSpan' style='border-width: 0px; vertical-align: middle;'>To:</td>" +
"<td style='border-width: 0px;text-align:left;' width='90%'>" +
"<div class='shopinionClearfix' id='shopinionSearchFriendsBox'>" +
"<span id='shopinionFriendsSpan'></span><input style='width: 250px;' placeholder='Enter your friends name here' id='shopinionFriendsInput' class='shopinionTextInput' type='text'>" +
"</div>" +
"</td>" +
"<td width='10%'></td>" +
"</tr>" +
"</table>" +
"<table class='shopinionInputDiv'>" +
"<tr>" +
"<td>" +
"<span class='shopinionTitleSpan'>Title:</span>" +
"</td>" +
"<td>" +
"</td>" +
"<td>" +
"<span class='shopinionTitleSpan'>Price:</span><span class='shopinionHintInfo'>&nbsp Is this right?</span>" +
"</td>" +
"</tr>" +
"<tr>" +
"<td style='width:320px;'>" +
"<input style='width:300px;' id='shopinionTitle' class='shopinionTextInput' type='text'>" +
"</td>" +
"<td>" +
"</td>" +
"<td style='width:200px;'>" +
"<input id='shopinionPrice' style='width:50px;' class='shopinionTextInput' type='text'>" +
"</td>" +
"</tr>" +
"</table>" +
"<table>" +
"<tr>" +
"<td rowspan='2'>" +
"<div class='shopinionInputDiv'>" +
"<textarea id='shopinionDescription' style='width:300px;height:100px;'></textarea><br>" +
"<span class='shopinionHintInfo' style='font-size:12px;color:black;'>A private Facebook message will be sent.</span>" +
"</div>" +
"</td>" +
"<td style='vertical-align:top;'>" +
"<div id='shopinionButtons'>" +
"<input id='shopinionSubmitButton' value='Chat With Friends' type='button'>" +
"<span id='shopinionWarnSpan'></span>" +
"</div>" +
"</td>" +
"</tr>" +
"<tr>" +
"<td style='vertical-align:bottom;text-align:right;padding-right:5px;'>" +
"<a class='shopinionHintInfo shopinionAnchorClass' id='shopinionLogout' href='javascript:void(0)' style='color:#888888'>Log Out</a>" +
"</td>" +
"</tr>" +
"</table>" +
"</td>" +
"</tr>" +
"</table>";
var image = document.getElementById("shopinionSelectImageDisplay");
image.src = imageArray[currentImage];
var imgSrc = document.getElementById("shopinionImgSrc");
imgSrc.value = imageArray[currentImage];
var title = document.getElementById("shopinionTitle");
title.value = document.title;
var price = document.getElementById("shopinionPrice");
price.value = getPrice();
var description = document.getElementById("shopinionDescription");
description.value = "I am interested in getting " + document.title + ". Chat with me!";
var previousImageArrow = document.getElementById("shopinionPreviousImageArrow");
previousImageArrow.addEventListener("click", function() {previousImage();displayCurrentImage();});
var nextImageArrow = document.getElementById("shopinionNextImageArrow");
nextImageArrow.addEventListener("click", function() {nextImage();displayCurrentImage();});
var cancelButton = document.getElementById("shopinionCancelButton");
cancelButton.addEventListener("click", removeEverything);
var logoutButton = document.getElementById("shopinionLogout");
logoutButton.addEventListener("click", logout);
actb(document.getElementById('shopinionFriendsInput'));
/* nextImage: increment currentImage counter. */
function nextImage() {
log("nextImage");
currentImage++;
if (currentImage >= imageArray.length) {
currentImage = 0;
}
}
/* previousImage: decrement currentImage counter. */
function previousImage() {
log("previousImage");
currentImage--;
if (currentImage < 0) {
currentImage = imageArray.length - 1;
}
}
/* displayCurrentImage: diplay current image according to currentImage counter. */
function displayCurrentImage() {
var image = document.getElementById("shopinionSelectImageDisplay");
image.src = imageArray[currentImage];
var imgSrc = document.getElementById("shopinionImgSrc");
imgSrc.value = imageArray[currentImage];
}
/* getPrice: go through the page to get the most likely price for the current item.
*/
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 (jQuery.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 (jQuery.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;
}
jQuery(".sendButtonSpan").click(function(){
jQuery(".sendButtonSpan").css("background", "none repeat scroll 0 0 transparent");
jQuery(this).css("background", "url('http://s3.amazonaws.com/shopinionapp/assets/images/snatchthis_light_b_120_52.png') no-repeat scroll 50% 50% transparent");
jQuery("#shopinionImgSrc").attr("value", this.parentNode.getElementsByTagName("img")[0].src);
return false;
});
jQuery("#shopinionSubmitButton").click(function(){
var shopinionRequestFbString = [];
var warnSpan = document.getElementById("shopinionWarnSpan");
jQuery(".shopinionFriendSpan input[type='hidden']").each(function() {
shopinionRequestFbString.push(jQuery(this).val());
});
warnSpan.innerHTML="";
//if (shopinionRequestFbString.length==0 && document.getElementById("shopinionForPublic").checked==false) {
if (shopinionRequestFbString.length==0) {
warnSpan.innerHTML = "Please choose somebody to send to.<br/>";
}
if (jQuery("#shopinionTitle").val() == "") {
warnSpan.innerHTML +="Please fill in the title.<br/>";
}
if (jQuery("#shopinionPrice").val() == "") {
warnSpan.innerHTML +="Please fill in the price.<br/>";
}
if (jQuery("#shopinionDescription").val() == "") {
warnSpan.innerHTML +="Please fill in the description.<br/>";
}
if (warnSpan.innerHTML.trim() != "") {
return false;
}
log("submitButton clicked: " + shopinionRequestFbString + ", " + document.getElementById("shopinionDescription").value);
/*log("submitButton clicked: " + shopinionRequestFbString + ", " + document.getElementById("shopinionForPublic").checked +
", " + document.getElementById("shopinionDescription").value);*/
xhr.request({
url: "../../bookmarkletPost",
method: "POST",
data: {shopinionImgSrc: document.getElementById("shopinionImgSrc").value,
shopinionTitle: document.getElementById("shopinionTitle").value,
shopinionPrice: document.getElementById("shopinionPrice").value,
shopinionDescription: document.getElementById("shopinionDescription").value,
shopinionPlugin: true,
shopinionRequestFbString: shopinionRequestFbString,
referringUrl: document.URL
},
}, function(response) { // success function
if (typeof response.data == "string") {
data = jQuery.parseJSON(response.data);
} else {
data = response.data;
}
openChatWindowAndSubscribeSubjectChannel(jQuery, 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);
});
/*jQuery.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 = jQuery.parseJSON(data);
}
openChatWindowAndSubscribeSubjectChannel(jQuery, 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);
}
});*/
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;
});
function logout(){
var childWindow = window.open("http://" + SHOPINION_DOMAIN + "/logoutInside", "shopinion", "width=550,height=450,status=yes,resizable=yes, toolbar=no");
if (window.addEventListener) {
window.addEventListener("message", handleLogoutMessage, false);
} else {
window.attachEvent("onmessage", handleLogoutMessage); // For IE8
}
};
/* auto complete for friends name */
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));
}
}
}
/* remove everything on the page */
function removeEverything() {
var wrapperDiv = document.getElementById("shopinionSelectWrapperDiv");
var backgroundDiv = document.getElementById("shopinionSelectBackground");
var autoCompleteTable = document.getElementById("tat_table");
if (wrapperDiv != null) {
document.body.removeChild(wrapperDiv);
}
if (backgroundDiv != null) {
document.body.removeChild(backgroundDiv);
}
if (autoCompleteTable != null) {
document.body.removeChild(autoCompleteTable);
}
}
function openChatWindowAndSubscribeSubjectChannel(jQuery, 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(jQuery, 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 (jQuery("#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 = jQuery.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: 250px;height: 100%;}",
".shopinionChatWindow {visibility: visible;background: none repeat scroll 0 0 white; border-color: #C3C3C3;border-style: solid solid none;border-width: 1px 1px medium;position: absolute;bottom: 0;width: 250px; color:black;}",
".shopinionChatWindow table, .shopinionChatWindow td, .shopinionChatWindow tr {padding: 0; border:none none;}",
// header
".shopinionChatWindowHeader { background: #313131 url(http://s3.amazonaws.com/shopinionapp/assets/images/chat_header_bg.png) repeat-y 0 0; color: #ffffff;" +
" font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; text-align: left;" +
" border-bottom-width:1px; border-bottom-style: dashed;}",
".shopinionChatWindowHeaderIcon {color: white; float: right;}",
// header icons
".shopinionChatWindowIcon {width: 16px; height: 16px; cursor: pointer; float: right; display: block; text-indent: -99999px; overflow: hidden;}",
".shopinionChatWindowMinusIcon {background-image: url('http://s3.amazonaws.com/shopinionapp/assets/images/ui-icons_ffffff_256x240.png'); background-position: -64px -128px; background-repeat: no-repeat;}",
".shopinionChatWindowCloseIcon {background-image: url('http://s3.amazonaws.com/shopinionapp/assets/images/ui-icons_ffffff_256x240.png'); background-position: -96px -128px; background-repeat: no-repeat;}",
".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; margin-top: 5px; border: 1px solid #666;" +
" border-top-left-radius: 10px; -moz-border-radius-topleft: 10px; -webkit-border-top-left-radius: 10px;" +
" border-bottom-right-radius: 10px; -moz-border-radius-bottomright: 10px; -webkit-border-bottom-right-radius: 10px;" +
" border-bottom-left-radius: 10px;-moz-border-radius-bottomleft: 10px; -webkit-border-bottom-left-radius: 10px;}",
".shopinionChatWindowText {width: 95%; margin: 1px auto; font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; font-size: 1em; resize: none;}",
".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; border-bottom-width:1px; border-bottom-style: dashed;}",
".shopinionChatWindowInfoHeader {padding: 5px 10px;height: 16px;width: 100%;}",
".shopinionInfoImageText {font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif;font-size: 1em;}",
".shopinionChatWindowVoteTable table, .shopinionChatWindowVoteTable th,.shopinionChatWindowVoteTable td {border:1px solid green;background-color: #FAF0E6;border-collapse: collapse;}",
".shopinionChatPersonName {font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; margin: 0px 10px; font: 10px;font-weight: bold;}",
".shopinionChatMessage {font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; 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);
}
jQuery("#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><a href='#' id='shopinionChatWindow-"+subjectId+"-M' class='shopinionChatWindowHeaderIcon' role='button'><span class='shopinionChatWindowIcon shopinionChatWindowMinusIcon'>minimize</span></a></td>"+
"<td><a href='#' id='shopinionChatWindow-"+subjectId+"-C' class='shopinionChatWindowHeaderIcon' role='button'><span class='shopinionChatWindowIcon shopinionChatWindowCloseIcon'>close</span></a></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='100%' id='shopinionChatWindowInfoImageCell-"+subjectId+"' rowspan='2' style='text-align:left;' class='shopinionInfoImageText'>See Detail</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) {
var split = data.messages[i].name.split(" ");
var name = split[0];
jQuery("#shopinionChatWindowBlockList-" + subjectId).append(
"<li class='shopinionChatWindowBlock'>" +
"<img src='https://graph.facebook.com/"+data.messages[i].fbId+"/picture?type=square'/> <span class='shopinionChatPersonName'>"+name+"</span>" +
"<span class='shopinionChatMessage'>"+data.messages[i].message+"</span><br>" +
"</li>");
}
//log("done appending chat messages for " + subjectId);
jQuery("#shopinionChatWindowBlockList-" + subjectId).prop("scrollTop",jQuery("#shopinionChatWindowBlockList-" + subjectId).prop("scrollHeight") - jQuery("#shopinionChatWindowBlockList-" + subjectId).height());
channel.bind('new-message', function(message) {
//log("received message: " + message.message);
if (message.fromFacebookId != null) {
var split = unescape(message.name).replace(/\+/g," ").split(" ");
var name = split[0];
jQuery("#shopinionChatWindowBlockList-" + subjectId).append('<li class="shopinionChatWindowBlock"><img src="https://graph.facebook.com/' + message.fromFacebookId + '/picture?type=square" /><span class="shopinionChatPersonName">' +
name + '</span><span class="shopinionChatMessage">' + unescape(message.message).replace(/\+/g," ") + '</span><br/></li>');
}
jQuery("#shopinionChatWindowBlockList-" + subjectId).prop("scrollTop", jQuery("#shopinionChatWindowBlockList-" + subjectId).prop("scrollHeight") - jQuery("#shopinionChatWindowBlockList-" + subjectId).height());
//log("scrollTop, " + jQuery("#chatWindowBlockList-" + subjectId).prop("scrollHeight") + ", "+ jQuery("#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}
});
/*jQuery.ajax({
type: "POST",
url: "http://" + SHOPINION_DOMAIN + "/pusherpurge",
data: {channelName: "presence-subject-"+subjectId,
memberId: member.id}
})*/
});
jQuery("#shopinionChatWindow-"+subjectId+"-M").click(function() {
jQuery("#shopinionChatWindow-"+subjectId+"-body").toggle();
return false;
});
jQuery("#shopinionChatWindow-"+subjectId+"-C").click(function() {
jQuery("#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}
});
/*jQuery.ajax({
type: "POST",
url: "http://"+SHOPINION_DOMAIN + "/pusherpurge",
data: {channelName: "presence-subject-"+subjectId,
memberId: myMemberId,
windowClosing: true}
})*/
return false;
});
jQuery("#shopinionChatWindowHeader-"+subjectId).click(function() {
jQuery("#shopinionChatWindow-"+subjectId+"-body").toggle();
return false;
});
jQuery("#shopinionChatWindowInfoImageCell-"+subjectId).click(function() {
if (jQuery(this).attr("class") === "shopinionInfoImageText") {
jQuery(this).html("<img class='shopinionChatWindowInfoImage' src='"+data.image+"'/>");
jQuery(this).css('text-align','center');
} else {
jQuery(this).html("See Detail");
jQuery(this).css('text-align','left');
}
jQuery(this).toggleClass("shopinionInfoImageOn");
});
// jQuery("#shopinionChatWindowInfoHeader-"+subjectId).click(function() {
// var blockList = jQuery("#shopinionChatWindowBlockList-"+subjectId);
// if (blockList.css("height") == "210px") {
// blockList.css("height", "60");
// } else {
// blockList.css("height", "210");
// }
// var mInfoIcon = jQuery("#shopinionChatWindowInfo-"+subjectId+"-M");
// var voteTable = jQuery("#shopinionChatWindowVoteTable-"+subjectId);
// var imageText = document.getElementById("shopinionChatWindowInfoImageText-"+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";
// jQuery("#shopinionChatWindowBlockList-" + subjectId).prop("scrollTop",jQuery("#shopinionChatWindowBlockList-" + subjectId).prop("scrollHeight") - jQuery("#shopinionChatWindowBlockList-" + subjectId).height());
// } else {
// mInfoIcon.attr("src", "http://s3.amazonaws.com/shopinionapp/assets/images/down_arrow_icon&16.png");
// imageCell.innerHTML = "Click to See Image";
// imageCell.style.textAlign = "left";
// jQuery("#shopinionChatWindowBlockList-" + subjectId).prop("scrollTop",jQuery("#shopinionChatWindowBlockList-" + subjectId).prop("scrollHeight") - jQuery("#shopinionChatWindowBlockList-" + subjectId).height());
// }
// return false;
// });
jQuery("#shopinionChatWindowInfo-"+subjectId+"-C").click(function() {
jQuery("#shopinionChatWindowInfo-"+subjectId).remove();
return false;
});
jQuery("#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: jQuery("#shopinionChatWindowText-"+subjectId).val(),
referringUrl: document.URL
},
});
/*jQuery.ajax({
type: "POST",
url: "http://" + SHOPINION_DOMAIN + "/sendMsg",
xhrFields: {
withCredentials: true
},
data: "socket_id=" + socket_id + "&subjectId="+subjectId+"&message=" + encodeURIComponent(jQuery("#shopinionChatWindowText-"+subjectId).val())
})*/
//log(socket_id + ", " + subjectId + " sending:" + jQuery("#chatWindowText-"+subjectId).val());
jQuery("#shopinionChatWindowBlockList-" + subjectId).append(
"<li class='shopinionChatWindowBlock'>" +
"<img src='https://graph.facebook.com/"+myFbId+"/picture?type=square'/> <span class='shopinionChatPersonName'>"+myName+"</span>" +
"<span class='shopinionChatMessage'>"+jQuery("#shopinionChatWindowText-"+subjectId).val()+"</span><br>" +
"</li>");
jQuery("#shopinionChatWindowText-"+subjectId).val('');
jQuery("#shopinionChatWindowBlockList-" + subjectId).prop("scrollTop",jQuery("#shopinionChatWindowBlockList-" + subjectId).prop("scrollHeight") - jQuery("#shopinionChatWindowBlockList-" + subjectId).height());
//log("scrollTop, " + jQuery("#chatWindowBlockList-" + subjectId).prop("scrollHeight") + ", "+ jQuery("#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);
};
if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]==obj){
return i;
}
}
return -1;
}
}
var 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
};
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment