EventLogger = function(filter) {
this.logEnabled = [];
this.registered = [];
this.logAll = (filter == 'all');
if (!this.logAll) {
for (var i = 0; i < filter.length; i++)
this.logEnabled[filter[i]] = true;
}
}
EventLogger.prototype.addEventLogger = function(element, name, observer, useCapture) {
if (this.logAll || this.logEnabled[name]) {
var eventObserver = function () {
var id = element.id;
var nodeName = element.nodeName;
var elementDescr = id ? (element + id) : (element + nodeName);
_a=0;
}
this.registered.push(
{
element: element,
name: name,
observer: observer,
useCapture: useCapture,
eventObserver: eventObserver
});
if (element.addEventListener)
element.addEventListener(name, eventObserver, useCapture);
else if (element.attachEvent)
element.attachEvent('on' + name, eventObserver);
}
}
EventLogger.prototype.removeEventLogger = function(element, name, observer, useCapture) {
if (this.logAll || this.logEnabled[name]) {
var ind = 0;
while (
ind < this.registered.length && (
this.registered[ind].element != element ||
this.registered[ind].name != name ||
this.registered[ind].observer != observer ||
this.registered[ind].useCapture != useCapture)) {
ind++;
}
if (ind == this.registered.length) {
_a=0;
return;
}
if (element.removeEventListener) {
element.removeEventListener(name, this.registered[ind].eventObserver, useCapture);
} else if (element.detachEvent) {
element.detachEvent('on' + name, this.registered[ind].eventObserver);
}
this.registered.splice(ind, 1);
}
}
eventLogger = undefined;
function Browser() {
agt=navigator.userAgent.toLowerCase();
this.win = false;
this.mac = false;
this.lin = true;
if ( agt.indexOf('win') != -1 ) {
this.win = true;
this.lin = false;
} else if ( agt.indexOf('mac') != -1 ) {
this.mac = true;
this.lin = false;
}
this.exclude = true;
this.ie = false; this.ie4 = false; this.ie5 = false; this.ie6 = false;
this.op5 = false; this.op6 = false; this.op7 = false;
this.ns4 = false; this.ns6 = false; this.ns7 = false;
this.mz7 = false;
this.kde = false;
this.saf = false;
if ( typeof navigator.vendor!="undefined" && navigator.vendor=="KDE" ) {
var splitKDE=agt.split("konqueror/");
var aKDE=splitKDE[1].split("; ");
var KDEn=parseFloat(aKDE[0]);
if ( KDEn >= 2.2 ) {
this.kde = true;
this.ns6 = true;
this.exclude = false;
}
} else if ( agt.indexOf('webtv') != -1 ) {
this.exclude = 1;
} else if ( typeof window.opera!="undefined" ) {
this.exclude = false;
if(/opera[\/ ][5]/.test(agt)) { this.op5 = true; }
if(/opera[\/ ][6]/.test(agt)) { this.op6 = true; }
if(/opera[\/ ][7-9]/.test(agt)) { this.op7 = true; }
} else if ( typeof document.all != "undefined" && !this.kde ) {
this.exclude = false;
this.ie = true;
if ( typeof document.getElementById != "undefined" ) {
this.ie5 = true;
if ( agt.indexOf("msie 6") != -1 ) { this.ie6 = true; }
} else { this.ie4 = true; }
} else if ( typeof document.getElementById != "undefined" ) {
this.exclude = false;
if ( agt.indexOf("netscape/6") != -1 || agt.indexOf("netscape6")!=-1 ) { this.ns6 = true; }
else if ( agt.indexOf("netscape/7") != -1 || agt.indexOf("netscape7") != -1 ) { this.ns6= true; this.ns7 = true; }
else if(agt.indexOf("gecko")!=-1){ this.ns6 = true; this.mz7 = true; }
if(agt.indexOf("safari")!=-1 || (typeof document.childNodes!="undefined" && typeof document.all=="undefined" && typeof navigator.taintEnabled=="undefined")){ this.mz7 = false; this.ns6 = true; this.saf = true; }
} else if ( (agt.indexOf('mozilla') != -1) && (parseInt(navigator.appVersion) >= 4) ) {
this.exclude = false;
this.ns4 = true;
if (typeof navigator.mimeTypes['*'] == "undefined") {
this.exclude = true;
this.ns4 = false;
}
}
if ( agt.indexOf('escape') != -1) { this.exclude = true; this.ns4 = false; }
if (typeof navigator.__ice_version != "undefined") { this.exclude = true; this.ie4 = false; }
this.isCSS = (document.body && document.body.style) ? true : false;
this.isW3C = (this.isCSS && document.getElementById) ? true : false;
this.eventNames = new Array();
if (this.ie) {
this.eventNames['MOUSE_DOWN'] = "onmousedown";
this.eventNames['MOUSE_MOVE'] = "onmousemove";
this.eventNames['MOUSE_UP']   = "onmouseup";
} else {
this.eventNames['MOUSE_DOWN'] = "mousedown";
this.eventNames['MOUSE_MOVE'] = "mousemove";
this.eventNames['MOUSE_UP']   = "mouseup";
}
}
Browser.SAFARI_TOP_HEIGHT = 0;
Browser.prototype.getAjaxTransporter = function() {
var transporter = false;
if (this.ie) {
try {
transporter = new ActiveXObject('Msxml2.XMLHTTP');
} catch (err) {
try {
transporter = new ActiveXObject('Microsoft.XMLHTTP')
} catch (err) { }
}
} else {
try {
transporter = new XMLHttpRequest();
} catch (err) { }
}
return(transporter);
}
Browser.prototype.addEventListener = function(node, event, callback) {
if (this.ie) {
node.attachEvent(this.eventNames[event], callback);
} else {
node.addEventListener(this.eventNames[event], callback, true);
}
}
Browser.prototype.removeEventListener = function(node, event, callback) {
if (this.ie) {
node.detachEvent(this.eventNames[event], callback);
} else {
node.removeEventListener(this.eventNames[event], callback, true);
}
}
Browser.prototype.preventDefault = function(event) {
if (this.ie) {
window.event.returnValue = false;
} else {
event.preventDefault();
}
}
Browser.prototype.stopPropagation = function(event) {
if (this.ie) {
window.event.cancelBubble = true;
} else {
event.stopPropagation();
}
}
Browser.prototype.getObject = function(obj) {
if (typeof obj == "string")
return $(obj);
else
return obj;
}
Browser.prototype.setNodeAttribute = function(obj, name, value) {
var theObj = this.getObject(obj);
if (theObj) {
if (this.ie) {
for (var i = 0; i < theObj.attributes.length; i++) {
if (theObj.attributes[i].name == name) {
theObj.attributes[i].value = value;
}
}
} else {
theObj.setAttribute(name, value);
}
}
}
Browser.prototype.setZIndex = function(obj, value) {
var theObj = this.getObject(obj);
if (theObj)
theObj.style.zIndex = value;
}
Browser.prototype.setVisibility = function(obj, visibility) {
var theObj = this.getObject(obj);
if (theObj) {
if (visibility.toLowerCase() == "visible" || visibility.toLowerCase() == "show") {
theObj.style.visibility = "visible";
theObj.style.display = "block";
} else {
theObj.style.visibility = "hidden";
theObj.style.display = "none";
}
}
}
Browser.prototype.getVisibility = function(obj) {
var theObj = this.getObject(obj);
if (theObj)
return theObj.style.visibility;
}
Browser.prototype.show = function(obj) {
var theObj = this.getObject(obj);
if (theObj)
theObj.style.display = "";
}
Browser.prototype.hide = function(obj) {
var theObj = this.getObject(obj);
if (theObj)
theObj.style.display = "none";
}
Browser.prototype.getRelativeLeft = function(obj) {
var theObj = this.getObject(obj);
if (theObj)
return parseInt(theObj.style.left);
else
return 0;
}
Browser.prototype.getRelativeTop = function(obj) {
var theObj = this.getObject(obj);
if (theObj)
if (theObj.style)
return parseInt(theObj.style.top);
else
return parseInt(theObj.top);
else
return 0;
}
Browser.prototype.getAbsoluteLeft = function(obj) {
var theObj = this.getObject(obj);
if (theObj)
return parseInt(theObj.offsetLeft);
else
return 0;
}
Browser.prototype.getAbsoluteTop = function(obj) {
var theObj = this.getObject(obj);
if (theObj)
return parseInt(theObj.offsetTop);
else
return 0;
}
Browser.prototype.getWidth = function(obj) {
var theObj = this.getObject(obj);
if (!theObj)
return 0;
else if(theObj.style.width)
return parseInt(theObj.style.width);
else
return parseInt(theObj.offsetWidth);
}
Browser.prototype.getHeight = function(obj) {
var theObj = this.getObject(obj);
if (!theObj)
return 0;
else if(theObj.style.height)
return parseInt(theObj.style.height);
else
return parseInt(theObj.offsetHeight);
}
Browser.prototype.setPositioning = function(obj, value) {
var theObj = this.getObject(obj);
if (theObj) {
if (value.toLowerCase() == "relative")
theObj.style.position = 'relative';
else
theObj.style.position = 'absolute';
}
}
Browser.prototype.setLeft = function(obj, value) {
var theObj = this.getObject(obj);
if (theObj)
theObj.style.left = value;
}
Browser.prototype.setTop = function(obj, value) {
var theObj = this.getObject(obj);
if (theObj)
theObj.style.top = value;
}
Browser.prototype.setWidth = function(obj, value) {
var theObj = this.getObject(obj);
if (theObj)
theObj.style.width = value + "px";
}
Browser.prototype.setHeight = function(obj, value) {
var theObj = this.getObject(obj);
if (theObj)
theObj.style.height = value + "px";
}
Browser.prototype.setOpacity = function(obj, value) {
var theObj = this.getObject(obj);
if (theObj) {
if (this.ie)
theObj.style.filter = "alpha(opacity=" + (value * 100) + ")";
else
theObj.style.opacity = value;
}
}
Browser.prototype.setBackgroundColor = function(obj, color) {
var theObj = this.getObject(obj);
if (theObj) {
theObj.style.backgroundColor = color;
}
}
Browser.prototype.moveBy = function(obj, x, y) {
if (obj) {
x = parseInt(x);
y = parseInt(y);
this.setLeft(obj, this.getRelativeLeft(obj) + x);
this.setTop(obj, this.getRelativeTop(obj) + y);
}
}
Browser.prototype.getCaretPos = function(elem) {
if (elem.selectionStart != undefined) {
return elem.selectionStart;
}
else if (this.ie){
var bookmark = "~";
var orig = elem.value;
var range = document.selection.createRange();
range.text = bookmark;
var pos = elem.value.indexOf( bookmark );
range.moveStart('character', -1);
range.text='';
return pos;
}
else {
throw new Error("Unable to get the caret position");
}
}
Browser.prototype.moveCaret = function(control, pos) {
if (control.setSelectionRange) {
control.setSelectionRange(pos, pos);
}
else if (this.ie) {
var range = control.createTextRange();
range.collapse(false);
var curPos = this.getCaretPos(control);
range.moveStart('character', pos - curPos);
range.moveEnd('character', pos - curPos);
range.select();
}
else {
throw new Error("Unable to change the caret position");
}
}
Browser.prototype.getStyleSheetRule = function( cssFileName, ruleSelector )
{
var foundIt = false;
var sheet;
for( var i = 0; i < document.styleSheets.length; i++ )
{
sheet = document.styleSheets[i];
if( !sheet || !sheet.href ) continue;
if( sheet.href.indexOf( cssFileName ) > -1 )
{
foundIt = true;
break;
}
}
if( !foundIt )
{
return null;
}
foundIt = false;
var rule;
var rules = this.ie ? sheet.rules : sheet.cssRules;
for( var i = 0, len = rules.length; i < len; i++)
{
rule = rules[i];
if( rule.selectorText == ruleSelector )
{
foundIt = true;
break;
}
}
if( !foundIt )
{
return null;
}
else
{
return rule;
}
}
Browser.prototype.isCompatible = function() {
var agt = navigator.userAgent.toLowerCase();
if (this.ie6) {
return true;
}
else if (this.mz7) {
var majorIndex = agt.indexOf("firefox") + 8;
var minorIndex = agt.indexOf("firefox") + 10;
if ( parseInt(agt.charAt(majorIndex)) >= 2 ) {
return true;
}
else if ( parseInt(agt.charAt(majorIndex)) >= 1) {
return (parseInt(agt.charAt(minorIndex)) >= 5);
}
else {
return false;
}
}
else if (this.saf) {
var majorIndex = agt.indexOf("safari") + 7;
return ( parseInt(agt.charAt(majorIndex)) >= 4 );
}
else {
return false;
}
}
SmartObject = function() {
this.objectDestroyed = false;
}
SmartObject.prototype.destroyAll = function() {
this.destroy(true);
}
SmartObject.prototype.destroy = function(all) {
if( this.objectDestroyed ) return;
this.objectDestroyed = true;
for( var attr in this ) {
try {
var initialType = typeof this[attr];
if( attr == 'objectDestroyed')
{
continue;
}
else if( initialType == 'object' )
{
if( this[attr].tagName && this[attr].nodeName )
{
_a=0;
this[attr] = null;
}
else if( this[attr].destroy && all )
{
_a=0;
this[attr].destroy();
this[attr] = null;
}
else
{
this[attr] = null;
_a=0;
}
}
else if( initialType == 'function' )
{
}
else
{
this[attr] = null;
_a=0;
}
} catch(e) {
}
}
}
SmartObjectChild = function() {
this.testObject = new Object();
this.testDiv = document.createElement('div');
this.testImage = document.createElement('img');
this.testString = "string";
this.testSmartObj = new SmartObject();
}
Object.extend( SmartObjectChild.prototype, SmartObject.prototype );
function intToSeqNum(n) {
var str = n.toString(36);
if (str.length == 1) {
str = "S00" + str;
}
else if (str.length == 2) {
str = "S0" + str;
}
else {
str = "S" + str;
}
return str.toUpperCase();
}
function seqNumToInt(str) {
try {
return parseInt(str.substr(1), 36);
} catch (e) { e.logError(); }
}
String.prototype.trim = function () {
var trimmed = this.replace(/^\s+/, '');
trimmed = trimmed.replace(/\s+$/, '');
return trimmed;
}
Error.prototype.printStackTrace = function() {
_a=0;
}
Error.prototype.logError = function() {
var error_txt = '<b>Types</b>: <font color="red">' + $A(this.types).inspect() + '</font><br/>';
try {
error_txt += '<b>Message</b>: <font color="red">' + this.message + '</font><br/>';
error_txt += '<b>Line</b>: ' + this.lineNumber + '<br/>';
error_txt += '<b>File</b>: ' + this.fileName + '<br/>';
error_txt += '<b>Stack</b>:<pre>' + this.stack.replace(/\n/g, "\n\t") + '</pre>';
} catch(e) {}
_a=0;
}
String.prototype.encode = function() {
s = this.replace(/</g, '&lt;');
s = s.replace(/>/g, '&gt;');
return s;
}
String.prototype.escapeQuotes = function(single) {
if( single ) {
return this.replace(/'/g, '');
} else {
return this.replace(/"/g, '');
}
}
String.prototype.replaceAll = function(findStr,repStr) {
var lastInd = 0;
var ind = this.indexOf(findStr, lastInd);
var newStr = "";
while (ind != -1) {
newStr += this.substring(lastInd, ind);
newStr += repStr;
lastInd = ind + findStr.length;
ind = this.indexOf(findStr, lastInd);
}
newStr += this.substring(lastInd, this.length);
return newStr;
}
Object.extend(Event, {
stopBubble: function(event) {
if( event.preventDefault ) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
preventDefaults: function(event) {
if( event.preventDefault ) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
});
Array.prototype.contains = function(obj) {
for (var i = 0; i < this.length; i++)
if (this[i] == obj)
return true;
return false;
}
Exception = function(message, type) {
Object.extend( this, new Error(message) );
this.types = new Array();
this.message = message;
var curType = type;
while( curType ) {
this.types.push( curType );
curType = Exception.PARENT_MAP[curType];
}
}
Object.extend(Error.prototype, {
types: ['Error'],
isType: function(type) {
for( var i=0; i<this.types.length; i++ ) {
if( type == this.types[i] ) return true;
}
return false;
}
});
Object.extend(Exception.prototype, Error.prototype);
Exception.PARENT_MAP = {
Error:           null,
ServiceError:    'Error',
TokenError:      'ServiceError',
DataNotReady:    'Error',
PageNotReady:    'DataNotReady',
EndPageNotReady: 'PageNotReady',
BoxNotReady:     'PageNotReady',
PageNotDisplayed: 'Error'
};
EventDispatcher = function() {
this.eventListenerMap = new Array();
}
EventDispatcher.prototype.fireEvent = function(id, newValue, oldValue) {
_a=0;
var listeners = this.eventListenerMap[id];
if( listeners ) {
for(var i=0; i < listeners[0].length; i++) {
try {
eval('listeners[0][i].' + listeners[1][i] + '(id, newValue, oldValue);');
}
catch(e) { e.logError(); }
}
}
}
EventDispatcher.prototype.addListener = function(id, obj, listener) {
if (!this.eventListenerMap[id])
this.eventListenerMap[id] = new Array(new Array(), new Array());
var myEvent = this.eventListenerMap[id];
if(myEvent[0].indexOf(obj) < 0) {
myEvent[0].push(obj);
myEvent[1].push(listener);
_a=0;
} else {
_a=0;
}
}
EventDispatcher.prototype.removeListener = function(id, obj, listener) {
if((listeners = this.eventListenerMap[id]) &&
(i = listeners[0].indexOf(obj)) >= 0) {
listeners[0][i] = listeners[0].last();
listeners[1][i] = listeners[1].last();
listeners[0].pop();
listeners[1].pop();
_a=0;
}
}
AssociativeArray = function() {
this.indexes = new Array();
this.elements = new Object();
}
AssociativeArray.prototype.put = function(key, val) {
if( !this.elements[key] ) {
this.indexes.push(key);
}
this.elements[key] = val;
}
AssociativeArray.prototype.get = function(key) {
return this.elements[key];
}
AssociativeArray.prototype.remove = function(key) {
for( var i=0; i<this.indexes.length; i++ ) {
if( this.indexes[i] == key ) {
this.indexes.splice(i, 1);
delete(this.elements[key]);
break;
}
}
}
AssociativeArray.prototype.getLength = function() {
return this.indexes.length;
}
AssociativeArray.prototype.each = function(iterator, index) {
var index_copy = new Array();
if( index ) {
index_copy = index;
} else {
for( var i=0; i<this.indexes.length; i++ ) {
index_copy[i] = this.indexes[i];
}
}
for( var i=0; i<index_copy.length; i++ ) {
var key = index_copy[i];
var val = this.elements[key];
try {
iterator(val, key);
} catch( e ) {
if( e == $continue ) {
continue;
} else if( e == $break ) {
break;
} else {
throw e;
}
}
}
}
AssociativeArray.prototype.eachSorted = function(iterator, sortFunction) {
var index_copy =
sortFunction ? this.indexes.sort(sortFunction) : this.indexes.sort();
this.each(iterator, index_copy);
}
AssociativeArray.prototype.inspect = function() {
var result = "[";
var sep = '';
this.each(function(val, key) {
result += sep + key + "=>" + val;
sep = ', ';
});
result += "]";
return result;
}
JSONCom = function(browser) {
this.callback = function(jsoncom) {
};
this.data = {};
this.key = "";
this.url = "";
this.params = "";
this.isHTML = false;
this.async = true;
}
JSONCom.prototype.setIsHTML = function( isHTML ) {
this.isHTML = isHTML;
}
JSONCom.prototype.setURL = function( url ) {
this.url = url;
}
JSONCom.prototype.setKey = function( key ) {
this.key = key;
}
JSONCom.prototype.getKey = function() {
return this.key;
}
JSONCom.prototype.setParams = function( params ) {
this.params = params;
}
JSONCom.prototype.setCallback = function( callback ) {
this.callback = callback;
}
JSONCom.prototype.getCallback = function() {
return this.callback;
}
JSONCom.prototype.isError = function() {
return this.data["is_error"] == 1;
}
JSONCom.prototype.getErrorCode = function() {
return this.data["errorCode"];
}
JSONCom.prototype.getError = function() {
return this.data["error"];
}
JSONCom.prototype.setError = function( error ) {
this.data["error"] = error;
}
JSONCom.prototype.getData = function() {
return this.data["data"];
}
JSONCom.prototype.setAsynchronous = function(async) {
this.async = async;
}
JSONCom.prototype.isAsynchronous = function() {
return this.async;
}
JSONCom.prototype.sendRequest = function() {
new Ajax.Request(
this.url,
{
method: 'get',
parameters: $H(this.params).toQueryString(),
onComplete: this.onAjaxSuccess.bind(this),
onFailure: this.onAjaxFailure.bind(this),
asynchronous: this.async
});
}
JSONCom.prototype.onAjaxSuccess = function( response ) {
try {
this.processSuccess( response.responseText);
} catch(e) {
e.logError();
}
}
JSONCom.prototype.onAjaxFailure = function( error ) {
if( !this.isHTML ) {
this.parseData_("");
} else {
this.data["data"] = "";
}
this.setError( PAGE_NOT_FOUND );
}
JSONCom.prototype.processSuccess = function( text ) {
if( !this.isHTML ) {
this.parseData_(text);
} else {
this.data["data"] = text;
}
if( this.callback )
this.callback(this);
}
JSONCom.prototype.parseData_ = function( data_string ) {
try {
this.data = eval( '(' + data_string + ')' );
} catch(error) {
error.logError();
_a=0;
}
if( this.data["json"] != 1 ) {
this.data["is_error"] = 1;
this.data["error"] = "Not proper JSON message: " + ((data_string.length > 0) ? data_string : "[EMPTY STRING]");
this.data["data"] = "";
this.data["errorCode"] = "JSON_ERROR";
}
}
JSONComBatch = function() {
this.requests = new Array();
this.setURL( Config.getServiceBatchURL() );
this.setCallback( this.onSuccess.bind(this) );
}
JSONComBatch.prototype = new JSONCom();
JSONComBatch.prototype.sendJSONRequest = JSONCom.prototype.sendRequest;
JSONComBatch.prototype.addRequest = function(j) {
this.requests.push(j);
}
JSONComBatch.prototype.sendRequest = function() {
var params = new Array();
for(var i = 0; i < this.requests.length; ++i) {
var r_params = $H(this.requests[i].params);
r_params.keys().each(function(key) {
params[i + '-' + key] = r_params[key];
});
}
this.setParams( params );
this.sendJSONRequest();
}
JSONComBatch.prototype.onSuccess = function(response) {
var data = $H(this.data["data"]);
for(var i = 0; i < this.requests.length; ++i) {
try {
this.requests[i].processSuccess( data[i] );
} catch(e) { e.logError(); }
}
}
SmartTextArea = function( options ) {
this.controlId = SmartTextArea.NEXT_ID;
SmartTextArea.NEXT_ID++;
if(!options) options = {};
if( !options.mainStyle ) options.mainStyle = 'smart_textarea';
if( !options.hiddenStyle ) options.hiddenStyle = 'smart_textarea_hidden';
if( options.disabled == undefined ) options.disabled = false;
this.options = options;
this.elements = {};
this.initialized = false;
Object.extend(this, new EventDispatcher());
}
Object.extend(SmartTextArea.prototype, SmartObject.prototype);
SmartTextArea.NEXT_ID = 1;
SmartTextArea.LINE_HEIGHT = 15;
SmartTextArea.prototype.getHTML = function() {
var extraStyle = '';
if( this.options.backgroundColor ) {
extraStyle += ' style="background-color: '+this.options.backgroundColor+';"';
}
if( this.options.disabled )
extraStyle += ' disabled="true"';
if( browser.ie )
extraStyle+= ' onselectstart="return true;" ondragstart="return true;"';
var html = '<textarea id="smedit_'+this.controlId+'" class="'+this.options.mainStyle+'"' + extraStyle + '></textarea>' +
'<textarea id="smedit_hidden_'+this.controlId+'" class="'+this.options.hiddenStyle+'" style="height:15px;"></textarea>' +
'<div class="'+this.options.hiddenStyle+'" id="smedit_div_'+this.controlId+'">&nbsp;</div>'
if( this.initialized || $('smedit_'+this.controlId) ) {
throw new Error("Elements already exist in page, do not call this twice");
}
return html;
}
SmartTextArea.prototype.init = function() {
this.elements.textArea = $('smedit_'+this.controlId);
this.elements.textAreaHidden = $('smedit_hidden_'+this.controlId);
this.elements.divHidden = $('smedit_div_'+this.controlId);
if( !this.elements.textArea ) {
throw new Error("HTML not inserted properly. Element doesn't exist");
}
this.initialized = true;
Event.observe(this.elements.textArea, 'keyup', this.updateTextArea.bind(this));
}
SmartTextArea.prototype.setValue = function(value, skipFireChange) {
_a=0;
this.elements.textArea.value = value;
this.updateTextArea(null);
if (!skipFireChange)
this.fireEvent('change', value);
}
SmartTextArea.prototype.getValue = function() {
return this.elements.textArea.value;
}
SmartTextArea.prototype.focus = function() {
this.elements.textArea.focus();
}
SmartTextArea.prototype.getTextArea = function() {
return this.elements.textArea;
}
SmartTextArea.prototype.setWidth = function(width) {
browser.setWidth(this.elements.textArea, width);
this.updateTextArea();
}
SmartTextArea.prototype.setColor = function(color) {
this.options.backgroundColor = color;
$('smedit_'+this.controlId).style.backgroundColor = color;
}
SmartTextArea.prototype.updateTextArea = function(event) {
this.refreshUI();
var oldHeight = browser.getHeight(this.elements.textArea);
var newHeight;
if( browser.saf == true ) {
var text = this.elements.textArea.value;
text = text.replace(/[\n\r]/g, "<br/>");
text = text.replace(/\s{2}/g, "&nbsp;&nbsp;");
this.elements.divHidden.innerHTML = text;
newHeight = browser.getHeight(this.elements.divHidden);
}
else {
this.elements.textAreaHidden.value = this.elements.textArea.value;
newHeight = this.elements.textAreaHidden.scrollHeight;
this.elements.textAreaHidden.scrollTop = newHeight;
}
if( oldHeight < SmartTextArea.LINE_HEIGHT ) {
oldHeight = SmartTextArea.LINE_HEIGHT;
}
if( newHeight < SmartTextArea.LINE_HEIGHT )
newHeight = SmartTextArea.LINE_HEIGHT;
var changed = newHeight - oldHeight;
if( newHeight != oldHeight ) {
var oldWidth = browser.getWidth(this.elements.textArea);
browser.setHeight(this.elements.textArea, newHeight);
if (browser.getWidth(this.elements.textArea) != oldWidth)
browser.setWidth(this.elements.textArea, oldWidth)
this.fireEvent('heightChange', newHeight, oldHeight);
}
this.fireEvent('change', this.elements.textArea.value);
}
SmartTextArea.prototype.refreshUI = function() {
browser.setWidth(this.elements.textAreaHidden, browser.getWidth(this.elements.textArea));
browser.setWidth(this.elements.divHidden, browser.getWidth(this.elements.textArea)-18);
}
TagListControl = function(options) {
this.control_id = TagListControl.NEXT_ID;
TagListControl.NEXT_ID++;
this.options = options;
this.smartTextArea = new SmartTextArea(options);
this.isEditing = false;
this.callbacks = {
blur:  this.onBlur.bind(this),
focus: this.onFocus.bind(this),
click: this.onClick.bind(this),
keyup: this.onKeyUp.bind(this),
keypress: this.onKeyPress.bind(this)
};
}
Object.extend(TagListControl.prototype, SmartObject.prototype);
TagListControl.prototype.parent = SmartObject.prototype;
TagListControl.NEXT_ID = 1;
TagListControl.MAX_AUTOCOMPLETE_LEN = 10;
TagListControl.prototype.getHTML = function() {
var extraStyle = "";
if( this.options.backgroundColor ) {
extraStyle += ' style="background-color: '+this.options.backgroundColor+';"';
}
var html =
'<div id="taglist_div_' + this.control_id + '" class="taglist_div">'+
this.smartTextArea.getHTML() +
'<div id="taglist_view_' + this.control_id + '" class="taglist_view"'+extraStyle+'>&nbsp;' +
'</div>' +
'<div id="taglist_autocomplete_' + this.control_id + '">&nbsp;' +
'</div>'
'</div>';
return html;
}
TagListControl.prototype.init = function() {
this.smartTextArea.init();
this.tagsEdit = this.smartTextArea.getTextArea();
this.tagsView = $('taglist_view_' + this.control_id);
this.autoList = $('taglist_autocomplete_' + this.control_id);
this.listControl = new ListControl(this, this.autoList);
if( !this.options.disabled ) {
Event.observe(this.tagsEdit, 'blur', this.callbacks.blur, false);
Event.observe(this.tagsEdit, 'focus', this.callbacks.focus, false);
Event.observe(this.tagsView, 'click', this.callbacks.click, false);
Event.observe(this.tagsEdit, 'keypress', this.callbacks.keypress, false);
Event.observe(this.tagsEdit, 'keyup', this.callbacks.keyup, false);
}
this.listControl.refresh();
this.showView();
}
TagListControl.prototype.destroy = function() {
if( !this.options.disabled ) {
Event.stopObserving(this.tagsEdit, 'blur', this.callbacks.blur, false);
Event.stopObserving(this.tagsEdit, 'focus', this.callbacks.focus, false);
Event.stopObserving(this.tagsView, 'click', this.callbacks.click, false);
Event.stopObserving(this.tagsEdit, 'keypress', this.callbacks.keypress, false);
Event.stopObserving(this.tagsEdit, 'keyup', this.callbacks.keyup, false);
}
this.parent.destroy.call(this);
}
TagListControl.prototype.getSmartTextArea = function () {
return this.smartTextArea;
}
TagListControl.prototype.showEdit = function() {
Element.show(this.tagsEdit);
Element.hide(this.tagsView);
this.tagsView.style.position="absolute";
this.tagsEdit.style.position="relative";
this.tagsEdit.focus();
if (this.editData)
this.smartTextArea.setValue(this.editData, true);
this.tagsView.innerHTML = "";
browser.moveCaret(this.tagsEdit, this.tagsEdit.value.length);
this.isEditing = true;
}
TagListControl.prototype.showView = function() {
Element.show(this.tagsView);
Element.hide(this.tagsEdit);
this.tagsView.style.position="relative";
this.tagsEdit.style.position="absolute";
this.listControl.hide();
if (this.viewData) {
var oldWidth = browser.getWidth(this.tagsView);
this.tagsView.innerHTML = this.viewData;
if (browser.getWidth(this.tagsView) != oldWidth)
browser.setWidth(this.tagsView, oldWidth);
}
this.tagsEdit.value = "";
this.isEditing = false;
}
TagListControl.prototype.setWidth = function(width) {
this.getSmartTextArea().setWidth(width);
browser.setWidth(this.tagsView, width);
}
TagListControl.prototype.setColor = function(color) {
this.options.backgroundColor = color;
this.getSmartTextArea().setColor(color);
this.tagsView.style.backgroundColor = color;
}
TagListControl.prototype.updateTagManager = function () {
var tagList = this.getTags();
for (var i = 0; i < tagList.length; i++) {
var index = this.tagListBeforeUpdate.indexOf(tagList[i]);
if (index != -1) {
this.tagListBeforeUpdate.splice(index, 1);
tagList[i] = undefined;
}
}
for (var i = 0; i < tagList.length; i++) {
if (tagList[i] != undefined)
tagManager.addTag(tagList[i]);
}
}
TagListControl.prototype.getTags = function() {
if (this.isEditing)
return this.tagsEdit.value.split(/\s*,\s*/);
else
return this.editData.split(/\s*,\s*/);
}
TagListControl.prototype.setTags = function(tagList) {
this.viewData = this.getViewHTML( tagList );
this.editData = this.getEditHTML( tagList );
if (!this.viewData)
this.viewData = "&nbsp;";
if (this.isEditing)
this.showEdit();
else
this.showView();
}
TagListControl.prototype.getCurrentTagIndex = function() {
var pos = browser.getCaretPos(this.tagsEdit);
var line = this.tagsEdit.value;
var ind = 0;
for (var i = 0; i < pos; i++)
if (line.charAt(i) == ',')
ind++;
return ind;
}
TagListControl.prototype.getEndTagPosition = function(tagIndex) {
var pos = 0;
var ind = 0;
var line = this.tagsEdit.value;
while (pos < line.length && ind <= tagIndex) {
if (line.charAt(pos) == ',')
ind++;
pos++;
}
return pos == line.length ? pos : pos - 1;
}
TagListControl.prototype.completeTag = function() {
if (this.listControl.getSelectedIndex() >= 0) {
this.tagsEdit.focus();
var ind = this.getCurrentTagIndex();
var tags = this.getTags();
tags[ind] = this.listControl.getSelected();
this.tagsEdit.value = this.getEditHTML( tags );
browser.moveCaret(this.tagsEdit, this.getEndTagPosition(ind));
this.listControl.hide();
}
}
TagListControl.prototype.getViewHTML = function( tagList ) {
var viewHTML = '';
var hasTag = false;
for (var i = 0; i < tagList.length; i++) {
var tag = tagList[i].trim();
if (tag != "") {
if (hasTag) {
viewHTML += ", ";
}
var searchTag = "javascript:reader.search.tagSearch('" + tag + "')";
viewHTML +=
'<a href="#" onclick="' + searchTag +'">' +
tag.escapeHTML().replace(/\s/g, "&nbsp;") +
'</a>';
hasTag = true;
}
}
return viewHTML;
}
TagListControl.prototype.getEditHTML = function( tagList ) {
for (var i = 0; i < tagList.length; i++) {
tagList[i] = tagList[i].trim();
}
return tagList.join( ', ' );
}
TagListControl.prototype.onClick = function(event) {
if (Event.element(event) == this.tagsView) {
this.showEdit();
}
}
TagListControl.getViewHTML = TagListControl.prototype.getViewHTML;
TagListControl.getEditHTML = TagListControl.prototype.getEditHTML;
TagListControl.prototype.onFocus = function(event) {
this.tagListBeforeUpdate = this.getTags();
}
TagListControl.prototype.onBlur = function(event) {
try {
this.updateTagManager();
if (browser.ie && this.listControl.isJustClicked())
return;
this.listControl.hide();
var tagList = this.getTags();
this.setTags(tagList);
if (browser.mz7)
setTimeout(this.showView.bind(this), 100);
else
this.showView();
}
catch (e) {
e.logError();
}
}
TagListControl.prototype.onKeyUp = function(event) {
try {
_a=0;
if (event.keyCode == Event.KEY_DOWN ||
event.keyCode == Event.KEY_UP ||
event.keyCode == Event.KEY_LEFT ||
event.keyCode == Event.KEY_RIGHT ||
event.keyCode == Event.KEY_RETURN ||
event.keyCode == Event.KEY_TAB ||
event.keyCode == 16 ||
event.keyCode == 17)
return;
var ind = this.getCurrentTagIndex();
var tag = this.getTags()[ind];
if (tag == "") {
this.listControl.hide();
}
else {
var data = tagManager.getClosestMatches(tag, TagListControl.MAX_AUTOCOMPLETE_LEN);
if (data.length == 0)
this.listControl.hide();
else {
this.listControl.setData(data);
this.listControl.show();
}
}
}
catch (e) {
e.logError();
}
}
TagListControl.prototype.onKeyPress = function(event) {
try {
switch (event.keyCode) {
case Event.KEY_DOWN:
this.listControl.goDown();
Event.stop(event);
return;
case Event.KEY_UP:
this.listControl.goUp();
Event.stop(event);
return;
case Event.KEY_TAB:
if (this.listControl.isHidden())
return;
case Event.KEY_RETURN:
this.completeTag()
Event.stop(event);
return;
}
}
catch (e) {
e.logError();
}
}
TagListControl.prototype.refreshTextArea = function() {
if (this.tagsEdit.style.display != "none") {
this.smartTextArea.updateTextArea();
this.smartTextArea.refreshUI();
}
}
BoxDiv = function( divManager ) {
this.divManager = divManager;
this.div = document.createElement("div");
this.pageDiv = undefined;
browser.setPositioning(this.div, "absolute");
browser.setOpacity(this.div, 0.5);
this.release();
}
Object.extend(BoxDiv.prototype, SmartObject.prototype);
BoxDiv.prototype.toString = function () {
return "{BoxDiv " + this.id + "} on [" + this.page + ":" + this.word + "] (" + this.free + ") pD=" + this.pageDiv;
}
BoxDiv.prototype.assign = function( page, word ) {
var skipCreate = (this.page == page);
this.page = page;
this.word = word;
this.free = false;
var pageObj = this.divManager.reader.pageManager.getPageObj(this.page);
this.pageDiv = pageObj.getPageDiv();
var boxes = pageObj.getBoxes();
if( boxes[word] ) {
if( this.div.parentNode && this.div.parentNode == this.pageDiv ) {
} else if( this.div.parentNode ) {
this.div.parentNode.removeChild(this.div);
this.pageDiv.appendChild(this.div);
} else {
this.pageDiv.appendChild(this.div);
}
Element.show(this.div);
this.setVisibility( 'show' );
boxes[word].div = this.div;
boxes[word].boxDiv = this;
} else {
_a=0;
}
}
BoxDiv.prototype.release = function(useLazyDeletion) {
if( useLazyDeletion == undefined ) useLazyDeletion = true;
Element.hide(this.div);
this.setVisibility( 'hidden' );
if( this.page ) {
var pageObj = this.divManager.reader.pageManager.getPageObj(this.page);
pageObj.boxes[this.word].div = undefined;
pageObj.boxes[this.word].boxDiv = undefined;
}
this.free = true;
}
BoxDiv.prototype.setLeft = function (left) {
browser.setLeft(this.div, left);
}
BoxDiv.prototype.setTop = function (top) {
browser.setTop(this.div, top);
}
BoxDiv.prototype.setWidth = function (width) {
browser.setWidth(this.div, width);
}
BoxDiv.prototype.setHeight = function (height) {
browser.setHeight(this.div, height);
}
BoxDiv.prototype.setVisibility = function (state) {
browser.setVisibility(this.div, state);
}
BoxDiv.prototype.setBackgroundColor = function (color) {
browser.setBackgroundColor(this.div, color);
}
BoxDiv.prototype.setOpacity = function (value) {
browser.setOpacity(this.div, value);
}
DivManager = function(reader, parentDiv, size, delta) {
this.first = undefined;
_a=0;
this.blockSize = size;
this.delta = delta;
this.parentDiv = parentDiv;
this.reader = reader;
this.boxDivs = new Array();
this.pageDivs = new Array();
this.pageUsed = new Array();
this.pageUsedNum = new Array();
for (var ii=0; ii<this.blockSize; ii++) {
this.boxDivs[ii] = new BoxDiv(this,  ii);
}
this.old_divs = 0;
this.new_divs = 0;
this.rid_divs = 0;
this.reused_divs = 0;
}
Object.extend(DivManager.prototype, SmartObject.prototype);
DivManager.prototype.showStatus = function(str) {
_a=0;
var total = 0;
for (var ii=0; ii<this.boxDivs.length; ii++) {
if( !this.boxDivs[ii].free ) total++;
}
_a=0;
_a=0;
}
DivManager.prototype.initEventListeners = function() {
_a=0;
}
DivManager.prototype.allocateDiv = function(page, word) {
this.allocateDivs(page, word, word);
}
DivManager.prototype.allocateDivs = function(page, word0, word1) {
if( this.pageDivs[page] == undefined ) {
this.pageDivs[page] = new Array();
}
var currentBoxDiv = 0;
for( var i=word0; i<=word1; i++ ) {
if( this.pageDivs[page][i] ) {
continue;
}
while( !this.boxDivs[currentBoxDiv].free )
{
currentBoxDiv++;
if( currentBoxDiv == this.boxDivs.length )
{
_a=0;
for( var ii=0; ii<this.delta; ii++ ) {
this.boxDivs.push( new BoxDiv(this) );
}
}
}
this.boxDivs[currentBoxDiv].assign(page, i);
this.pageDivs[page][i] = this.boxDivs[currentBoxDiv];
}
}
DivManager.prototype.freeDiv = function( div, useLazyDeletion ) {
if( !div ) return;
this.rid_divs++;
this.pageDivs[div.page][div.word] = undefined;
div.release(useLazyDeletion);
}
DivManager.prototype.allocatePageDivs = function(page, word0, word1) {
this.allocateDivs( page, word0, word1 );
_a=0;
}
DivManager.prototype.freePageDivs = function(page) {
var freed = 0;
var pageObj = this.reader.pageManager.getPageObj(page);
if( this.pageDivs[page] ) {
for (var ii=0; ii < pageObj.boxes.length; ii++) {
if( this.pageDivs[page][ii] != undefined ) {
freed++;
this.freeDiv( this.pageDivs[page][ii], false );
}
}
_a=0;
}
}
DivManager.prototype.getDivByIndex = function(index) {
return this.boxDivs[index];
}
DivManager.prototype.setBlockSize = function(size) {
this.blockSize = size;
}
DivManager.prototype.onPageLoad = function(event, pageObj) {
_a=0;
this.testLoad();
}
DivManager.prototype.onPageUnload = function(event, pageObj) {
_a=0;
this.testUnload();
}
DivManager.prototype.testLoad = function(page) {
if (this.first == undefined) {
this.first = 1;
this.rotate = 3;
this.test_round = 0;
this.test_divs = new Array();
for (var ii=0; ii<rotate; ii++) {
this.test_divs[ii] = new Array();
_a=0;
}
}
_a=0;
this.allocatePageDivs(page, 50, 125);
this.test_round++;
}
DivManager.prototype.testUnload = function(page) {
_a=0;
this.freePageDivs(page);
}
try {
PageManager = function(asin, zoom, viewerDiv, reader, initPage ) {
Object.extend(this, new EventDispatcher());
this.reader = reader;
this.asin = asin;
this.viewerDiv = viewerDiv;
this.zoom = zoom;
this.displayZoom = zoom;
this.initPage = initPage;
this.requestQueue = new RequestQueue();
this.width = 0;
this.PM_NUM_PAGES = 3;
if( Config.getReaderPermissions().pm_caching ) {
this.PM_PAGES_FORWARD = 2;
this.PM_PAGES_BACK = 1;
this.PM_PAGES_MAX = 3;
} else {
this.PM_PAGES_FORWARD = 0;
this.PM_PAGES_BACK = 0;
this.PM_PAGES_ACTIVE = 0;
this.PM_PAGES_MAX = 3;
}
this.cache = new Array();
this.inUse = new Array();
this.lastCachingTime = undefined;
this.waitingForRefresh = false;
this.pages = new Array(this.PM_NUM_PAGES);
for (var i = 0; i < this.PM_NUM_PAGES; i++) {
this.pages[i] = new Page(this, viewerDiv, $('annotationHolder'));
}
this.pageLoaded = new Array();
this.pageMap = Config.getPageMap();
this.displayedBoxError = false;
}
Object.extend(PageManager.prototype, SmartObject.prototype);
PageManager.prototype.parent = SmartObject.parent;
PageManager.prototype.destroy = function() {
_a=0;
for( var i=0; i<this.pages.length; i++ ) {
this.pages[i].destroy();
}
this.parent.destroy.call(this);
}
PageManager.prototype.init = function() {
}
PageManager.prototype.createPage = function(pageNum, checksum) {
var page;
if( this.isPageInCache(pageNum) ) {
page = this.getPageFromCache(pageNum);
} else {
page = this.getFreePage();
page.load(pageNum, checksum, 10);
this.addPageToCache(page);
}
this.addPageInUse(page);
this.enforceCaching();
return page;
}
PageManager.prototype.releasePage = function(pageObj) {
this.removePageInUse(pageObj);
this.garbageCollect();
}
PageManager.prototype.getZoom = function() {
return this.zoom;
}
PageManager.prototype.getLogicalPageNumber = function( pageNum, logicalPageNum ) {
if( this.pageMap[pageNum] )
return this.pageMap[pageNum];
else if( logicalPageNum ) {
this.pageMap[pageNum] = logicalPageNum;
return logicalPageNum;
}
else
return seqNumToInt(pageNum);
}
PageManager.prototype.getPhysicalPageNumber = function(logicalPage) {
for( var physical in this.pageMap ) {
var logical = this.pageMap[physical];
if( logicalPage == logical ) {
return physical;
}
}
return -1;
}
PageManager.prototype.clearCache = function() {
var removePages = new Array();
for(var i=0; i<this.cache.length; i++ ) {
var cachePage = this.cache[i];
var pageInUse = false;
for(var j=0; j<this.inUse.length; j++) {
var usePage = this.inUse[j];
if( cachePage.getPageNum() == usePage.getPageNum() ) {
pageInUse = true;
break;
}
}
if( !pageInUse )
removePages.push(cachePage);
}
for(var i=0; i<removePages.length; i++ ) {
this.removePageFromCache(removePages[i]);
}
}
PageManager.prototype.setZoom = function(zoom) {
this.zoom = zoom;
this.clearCache();
}
PageManager.prototype.resetWidth = function() {
this.width = 0;
}
PageManager.prototype.getPageObj = function(pageNum) {
return this.getPageFromCache(pageNum);
}
PageManager.prototype.comp = function(a, b) {
return a.getPageNum() - b.getPageNum();
}
PageManager.prototype.getPage = function(pageNum) {
for (var i = 0; i < this.pages.length; i++) {
if (this.pages[i].getPageNum() == pageNum) {
return this.pages[i];
}
}
return undefined;
}
PageManager.prototype.getFreePage = function() {
try {
for (var i = 0; i < this.pages.length; i++) {
if (this.pages[i].getCached() == false) {
_a=0;
return this.pages[i];
}
}
var page = new Page( this, this.viewerDiv, $('annotationHolder') );
this.pages[this.pages.length] = page;
return page;
}
catch (e) { e.logError(); }
}
PageManager.prototype.getPageInUse = function(pageNum) {
for (var i = 0; i < this.inUse.length; i++) {
if (this.inUse[i].getPageNum() == pageNum) {
return this.inUse[i];
}
}
return undefined;
}
PageManager.prototype.addPageInUse = function(pageObj) {
if(this.getPageInUse(pageObj.getPageNum())==undefined)
this.inUse[this.inUse.length] = pageObj;
}
PageManager.prototype.removePageInUse = function(pageObj) {
for (var i = 0; i < this.inUse.length; i++) {
if (this.inUse[i] == pageObj) {
this.inUse.splice(i, 1);
return;
}
}
}
PageManager.prototype.getPageFromCache = function(pageNum) {
for (var i = 0; i < this.cache.length; i++) {
if (this.cache[i].getPageNum() == pageNum) {
return this.cache[i];
}
}
throw new Exception(pageNum + " is not cached", 'PageNotReady');
}
PageManager.prototype.isPageInCache = function(pageNum) {
for (var i = 0; i < this.cache.length; i++) {
if (this.cache[i].getPageNum() == pageNum) {
return true;
}
}
return false;
}
PageManager.prototype.addPageToCache = function(pageObj) {
try {
var page = this.getPageFromCache(pageObj.getPageNum());
} catch(e) {
if( e.isType('PageNotReady') && this.getZoom() == pageObj.getZoom() ) {
this.cache[this.cache.length] = pageObj;
pageObj.setCached(true);
pageObj.setID("Page " + pageObj.getPageNum());
}
}
}
PageManager.prototype.removePageFromCache = function(pageObj) {
for (var i = 0; i < this.cache.length; i++) {
if (this.cache[i].getPageNum() == pageObj.getPageNum()) {
this.fireEvent('pageUnload', pageObj);
pageObj.clear();
this.cache.splice(i, 1);
return;
}
}
}
PageManager.prototype.enforceCaching = function() {
var pagesToCache = new Array();
var pagesForward = this.PM_PAGES_FORWARD;
var pagesBackward = this.PM_PAGES_BACK;
var currentPageNum = this.reader.GetCurrentPage();
if( !this.isPageInCache(currentPageNum) ) {
_a=0;
return;
}
var lastPage = this.getPageFromCache(currentPageNum);
while( pagesForward > 0 ) {
var pageNum = lastPage.getNextPage();
if( !pageNum ) break;
if( !this.isPageInCache(pageNum) ) {
pagesToCache.push(pageNum);
break;
}
lastPage = this.getPageFromCache(pageNum);
pagesForward--;
}
currentPageNum = this.reader.GetCurrentPage();
var lastPage = this.getPageFromCache(currentPageNum);
while( pagesBackward > 0 ) {
var pageNum = lastPage.getPrevPage();
if( !pageNum ) break;
if( !this.isPageInCache(pageNum) ) {
pagesToCache.push(pageNum);
break;
}
lastPage = this.getPageFromCache(pageNum);
pagesBackward--;
}
pagesToCache.each((function(pageNum) {
if(!pageNum)
throw $continue;
_a=0;
var newPage = this.getFreePage();
newPage.load(pageNum, null, 2);
this.addPageToCache(newPage);
}).bind(this) );
}
PageManager.prototype.garbageCollect = function() {
_a=0;
var pagesToRemove = new Array();
this.cache.each((function(page) {
if( this.getDistanceFromCurrentPage(page.getPageNum()) > this.PM_PAGES_MAX
&& !this.getPageInUse(page.getPageNum()) )
pagesToRemove.push(page);
}).bind(this));
pagesToRemove.each((function(page) {
_a=0;
this.removePageInUse(page);
this.removePageFromCache(page);
}).bind(this));
}
PageManager.prototype.getDistanceFromCurrentPage = function(pageNum) {
var currentPageNum = this.reader.GetCurrentPage();
var forward = true;
if( currentPageNum > pageNum )
forward = false;
var distance = 0;
while(true) {
if( currentPageNum == pageNum ) break;
if( !this.isPageInCache(currentPageNum) ) {
distance = -1;
break;
}
var page = this.getPageFromCache(currentPageNum);
currentPageNum = forward ? page.getNextPage() : page.getPrevPage();
distance++;
}
return distance;
}
PageManager.prototype.numWords = function (page) {
return this.getPageObj(page).getBoxes().length;
}
PageManager.prototype.createBoxDivsIfNeeded = function(page, index0, index1) {
var pageObj = this.getPageObj(page);
var pageBoxes = pageObj.getBoxes();
this.reader.divManager.allocateDivs(page, index0, index1);
for( var i=index0; i<=index1; i++ ) {
pageBoxes[i].div.style.overflow = "hidden";
browser.setTop( pageBoxes[i].div, pageBoxes[i].top );
browser.setHeight( pageBoxes[i].div, pageBoxes[i].height );
if( pageBoxes[i].new_row) {
browser.setLeft( pageBoxes[i].div, pageBoxes[i].left );
browser.setWidth( pageBoxes[i].div, pageBoxes[i].width );
} else {
browser.setLeft( pageBoxes[i].div, pageBoxes[i-1].left + pageBoxes[i-1].width );
browser.setWidth( pageBoxes[i].div, pageBoxes[i].left + pageBoxes[i].width - (pageBoxes[i-1].left + pageBoxes[i-1].width) );
}
}
}
PageManager.prototype.changeBoxTypeRef = function( page, index0, index1, type, delta ) {
var pageObj = this.getPageObj(page);
var boxes = pageObj.getBoxes();
if( delta > 0 )
this.createBoxDivsIfNeeded( page, index0, index1 );
var boxesToFree = new Array();
for( var i=index0; i<=index1; i++ ) {
boxes[i].types[type] += delta;
if( boxes[i].types[type] < 0 ) boxes[i].types[type] = 0;
var topType=0;
while( boxes[i].types[topType]==0 && topType < Indicator.MAX_TYPES ) {
topType++;
}
if( topType > 0 && topType < Indicator.MAX_TYPES ) {
browser.setBackgroundColor( boxes[i].div, Indicator.getColor(topType) );
} else {
boxesToFree.push(i);
}
}
for( var i=0; i<boxesToFree.length; i++ ) {
this.reader.divManager.freeDiv( boxes[boxesToFree[i]].boxDiv, false );
}
}
PageManager.prototype.getBoxesForRange = function(page, startX, startY, endX, endY) {
var pageObj = this.getPageFromCache(page);
var rows = pageObj.rows;
var topToBottom = (startY < endY);
var rowStart = topToBottom ? 0 : rows.length-1;
var rowLimit = topToBottom ? rows.length : -1;
var rowIncrement = topToBottom ? 1 : -1;
var boxes = new Array();
for( var i=rowStart; i != rowLimit; i+= rowIncrement )
{
var row = rows[i];
var leftToRight = (startX < endX);
if( (topToBottom && endY < row.yMin) ||
(!topToBottom && startY < row.yMin) )
continue;
if( (topToBottom && startY > row.yMax) ||
(!topToBottom && endY > row.yMax) )
continue;
var continueFromPreviousLine = false;
if( topToBottom && startY < row.yMin && endY > row.yMin
&& endX > row.xMin && endX < row.xMax ) {
leftToRight = true;
continueFromPreviousLine = true;
} else if( !topToBottom && startY > row.yMax && endY < row.yMax &&
endX > row.xMin && endX < row.xMax ) {
leftToRight = false;
continueFromPreviousLine = true;
}
var continueToNextLine = false;
if( topToBottom && startY < row.yMax && endY > row.yMax &&
startX > row.xMin && startX < row.xMax ) {
leftToRight = true;
continueToNextLine = true;
} else if( !topToBottom && startY > row.yMin && endY < row.yMin &&
startX > row.xMin && startX < row.xMax ) {
leftToRight = false;
continueToNextLine = true;
}
var columnStart = leftToRight ? 0 : row.columns.length-1;
var columnLimit = leftToRight ? row.columns.length : -1;
var columnIncrement = leftToRight ? 1 : -1;
var selectRestOfRow = false;
for( var j=columnStart; j != columnLimit; j += columnIncrement )
{
var box = row.columns[j];
if( selectRestOfRow ) {
boxes.push(box.itemID);
continue;
}
var intercept = this.getInterceptPosition(startX, startY, endX, endY, box);
if( intercept == 'I' ) {
boxes.push(box.itemID);
} else if( continueToNextLine && (
(leftToRight && intercept == 'L') ||
(!leftToRight && intercept == 'R') ) )
{
boxes.push(box.itemID);
selectRestOfRow = true;
} else if( continueFromPreviousLine && (
(leftToRight && intercept == 'R') ||
(!leftToRight && intercept == 'L') ) )
{
boxes.push(box.itemID);
}
}
}
return boxes;
}
PageManager.prototype.getInterceptPosition = function(startX, startY, endX, endY, box)
{
var boxRight = box.left + box.width;
if( startX < box.left && endX < box.left ) {
return 'L';
} else if( startX > boxRight && endX > boxRight ) {
return 'R';
} else {
return 'I';
}
}
PageManager.prototype.getBoxFromCoordinates = function(page, x, y) {
var pageObj = this.getPageFromCache(page);
if( !pageObj || !pageObj.rows || !pageObj.rows.length ) return;
var rows = pageObj.rows;
var row = 0;
var found = false;
if( !rows ) return null;
while (row < rows.length) {
found = (y < rows[row].yMin);
if (found) break;
row++;
}
row--;
if (!found)
found = (y < rows[row].yMax);
if (!found || row<0) return undefined;
var col = 0;
while (col < rows[row].columns.length) {
found = (x < rows[row].columns[col].left);
if (found) break;
col++;
}
col--;
if (!found)
found = (x < rows[row].columns[col].left + rows[row].columns[col].width);
if (!found || col<0) return undefined;
var box = rows[row].columns[col];
return box.itemID;
}
} catch(e) {
e.logError();
}RequestQueue = function() {
this.queueItems = new Array();
this.pendingItems = new Array();
this.requestsPending = 0;
this.requestsAllowed = 2;
this.stopTimer = false;
this.timer = setTimeout(this.processQueue.bind(this), 300);
}
Object.extend(RequestQueue.prototype, SmartObject.prototype);
RequestQueue.prototype.parent = SmartObject.prototype;
RequestQueue.prototype.destroy = function() {
this.stopTimer = true;
this.parent.destroy.call(this);
}
RequestQueue.prototype.addItem = function(page, jsoncom, priority) {
var queueItem = new QueueItem(page, jsoncom, priority);
this.queueItems.push(queueItem);
}
RequestQueue.prototype.removeItem = function(page) {
var indexToDelete = null;
this.queueItems.each((function(item,index) {
if( item.page == page ) {
indexToDelete = index;
throw $break;
}
}).bind(this));
if( indexToDelete ) {
this.queueItems.splice(indexToDelete, 1);
}
}
RequestQueue.prototype.getItems = function() {
return this.queueItems;
}
RequestQueue.prototype.processQueue = function() {
if( this.requestsPending > this.requestsAllowed ||
this.queueItems.length == 0 )
{
if( this.stopTimer )
return;
this.timer = setTimeout(this.processQueue.bind(this), 300);
return;
}
var index = this.getTopPriorityIndex();
var queueItem = this.queueItems[index];
this.queueItems.splice(index, 1);
this.pendingItems.push(queueItem);
var oldCallback = queueItem.jsoncom.getCallback();
queueItem.jsoncom.setCallback((function(jsoncom) {
this.onAjaxComplete(jsoncom);
oldCallback(jsoncom);
}).bind(this));
queueItem.jsoncom.sendRequest();
this.requestsPending++;
this.processQueue();
}
RequestQueue.prototype.onAjaxComplete = function(jsoncom) {
var indexToDelete = null;
this.pendingItems.each((function(item,index) {
if( item.jsoncom == jsoncom ) {
indexToDelete = index;
}
}).bind(this));
this.pendingItems.splice(indexToDelete,1);
this.requestsPending--;
}
RequestQueue.prototype.getTopPriorityIndex = function() {
var maxPriority = 0;
var maxIndex = 0;
this.queueItems.each((function(item,index) {
if( item.priority > maxPriority ) {
maxPriority = item.priority;
maxIndex = index;
}
}).bind(this));
return maxIndex;
}
QueueItem = function(page, jsoncom, priority) {
this.page = page;
this.jsoncom = jsoncom;
this.priority = priority;
}
Viewer = function( ) {
}
Viewer.prototype.initViewer = function( reader ) {
this.div = reader.div;
this.reader = reader;
this.pages = this.reader.pages;
this.pageManager = this.reader.pageManager;
this.releaseAll();
this.reader.addListener( 'pageChange', this, 'onPageChange' );
this.pageManager.addListener('pageLoad', this, 'onPageLoad');
this.pageManager.addListener('pageError', this, 'onPageError');
this.pendingPageNum = undefined;
this.lastValidPageNum = undefined;
this.lastValidChecksum = undefined;
this.customInitialization();
}
Object.extend(Viewer.prototype, SmartObject.prototype);
Viewer.prototype.parent = SmartObject.prototype;
Viewer.prototype.customInitialization = function() {
}
Viewer.prototype.destroy = function() {
this.reader.removeListener( 'pageChange', this, 'onPageChange' );
this.pageManager.removeListener('pageLoad', this, 'onPageLoad');
this.pageManager.removeListener('pageError', this, 'onPageError');
this.releaseAll();
this.parent.destroy.call(this);
}
Viewer.prototype.onPageLoad = function( event, page ) {
if( this.pendingPageNum == page.getPageNum() ) {
this.displayImage(page);
}
}
Viewer.prototype.makeCurrentPageVisible = function() {
this.reader.setScrollTop(0);
}
Viewer.prototype.displayImage = function( page ) {
var pageNum = page.getPageNum();
this.pages.put(pageNum, page);
this.hideMessage();
page.setLeft( 0 );
page.setTop( 0 );
this.reader.onScroll();
page.show();
this.reader.setCurrentPage( page.getPageNum(), page.getChecksum() );
this.reader.fireScreenEvent( page, true );
this.reader.adjustViewerSize();
this.reader.updateWingVisibility();
}
Viewer.prototype.onPageError = function( event, page ) {
if( this.pendingPageNum == page.getPageNum() )
this.displayError(page);
}
Viewer.prototype.displayError = function( page ) {
var logicalPage = this.pageManager.getLogicalPageNumber( page.getPageNum() );
var pageNumStr = page.isSurpriseMe?"random":page.getPageNum();
if( page.getErrorCode() == "AUTH" ) {
window.location = Config.getReaderURL() + "?asin=" + this.reader.asin + "&v=strip-auth&pageID=" + pageNumStr + "&checkSum=" + page.getChecksum();
}
else {
this.pageManager.releasePage(page);
this.cleanup(page);
if( page.getErrorCode().match( 'SERVICE' ) )
{
_a=0;
displayErrorDialog( 'Book temporarily unavailable, <a href="#">try again</a>' );
}
else
{
_a=0;
displayErrorDialog( page.getErrorStr(), undefined, this.errorCallback );
}
}
}
Viewer.prototype.releaseAll = function() {
var pagesToRemove = new Array();
this.pages.each((function(page,pageNum) {
pagesToRemove.push(pageNum);
}).bind(this));
this.releasePages( pagesToRemove );
}
Viewer.prototype.releasePage = function(pageNum) {
this.releasePages( [pageNum] );
}
Viewer.prototype.releasePages = function(pages) {
pages.each((function(pageNum) {
var page = this.pages.get(pageNum);
if( !page ) throw $continue;
this.reader.fireScreenEvent( page, false );
page.hide();
this.pageManager.releasePage( page );
this.pages.remove(pageNum);
_a=0;
}).bind(this) );
}
Viewer.prototype.setInitialPage = function( pageNum, checksum, isSurpriseMe, errorCallback ) {
try {
this.errorCallback = errorCallback;
var page = this.pageManager.createPage( pageNum, checksum );
this.releaseAll();
page.isSurpriseMe = isSurpriseMe;
var logicalPage = this.pageManager.getLogicalPageNumber(pageNum);
if( !page.imageLoaded && !page.getErrorCode() ) {
this.showMessage( 'Getting page' + (this.reader.permissions == 'SITBpaid' ? ' ' + logicalPage : '') );
this.pendingPageNum = pageNum;
return false;
} else if( page.getErrorCode() ) {
this.displayError( page );
return false;
}
this.displayImage( page );
return true;
}
catch (e) { e.logError(); }
}
Viewer.prototype.cleanup = function(page) {
var pagesToRemove = new Array();
this.pages.each((function(val, key) {
if( key != page.getPageNum() )
{
pagesToRemove.push(key);
val.hide();
this.pageManager.releasePage(val);
}
}).bind(this));
pagesToRemove.each((function(pageNum) {
this.pages.remove(pageNum);
}).bind(this));
}
Viewer.prototype.getFirstPage = function() {
var firstPage = null;
this.pages.each(function(page,pageNum) {
if( firstPage == null || pageNum < firstPage ) {
firstPage = pageNum;
}
});
return this.pages.get(firstPage);
}
Viewer.prototype.getLastPage = function() {
var lastPage = null;
this.pages.each(function(page,pageNum) {
if( lastPage == null || pageNum > lastPage )
lastPage = pageNum;
});
return this.pages.get(lastPage);
}
Viewer.prototype.onPageChange = function() {
if( this.reader.permissions == 'SITBpaid' )
{
this.reader.selector.clearTextSelection();
}
}
Viewer.prototype.showMessage = function(msg) {
var left = this.reader.getViewerLeft() + 20;
var top = this.reader.getViewerTop() + 20;
extras.showLoader();
}
Viewer.prototype.hideMessage = function() {
extras.hideLoader();
}
ContinuousViewer = function() {
this.isLoading = false;
this.fillingPages = false;
this.pendingPage = undefined;
this.messageShown = false;
this.isVisible = true;
this.onWindowResizeCallback = this.onWindowResize.bind(this);
this.onKeyPressCallback = this.onKeyPress.bind(this);
this.onMouseWheelCallback = this.onMouseWheel.bind(this);
Object.extend(this, new EventDispatcher());
}
Object.extend(ContinuousViewer.prototype, Viewer.prototype);
ContinuousViewer.prototype.parent = SmartObject.prototype;
ContinuousViewer.MAX_PAGE_TO_SHOW = 10;
ContinuousViewer.LINE_HEIGHT = 20;
ContinuousViewer.prototype.customInitialization = function() {
Event.observe( window, 'resize', this.onWindowResizeCallback, false );
if( browser.ie )
{
Event.observe( $('layoutBody'), 'keypress', this.onKeyPressCallback, false );
Event.observe( $('layoutBody'), 'mousewheel', this.onMouseWheelCallback, false );
}
else
{
Event.observe( document, 'keypress', this.onKeyPressCallback, false );
Event.observe( $('layoutBody'), 'DOMMouseScroll', this.onMouseWheelCallback, false );
Event.observe( $('annotationHolder'), 'DOMMouseScroll', this.onMouseWheelCallback, false );
}
}
ContinuousViewer.prototype.destroy = function() {
Event.stopObserving( window, 'resize', this.onWindowResizeCallback, false );
if( browser.ie )
{
Event.stopObserving( $('layoutBody'), 'keypress', this.onKeyPressCallback, false );
Event.stopObserving( $('layoutBody'), 'mousewheel', this.onMouseWheel.bind(this), false );
}
else
{
Event.stopObserving( document, 'keypress', this.onKeyPressCallback, false );
Event.stopObserving( $('layoutBody'), 'DOMMouseScroll', this.onMouseWheelCallback, false );
Event.stopObserving( $('annotationHolder'), 'DOMMouseScroll', this.onMouseWheelCallback, false );
}
this.reader.removeListener( 'pageChange', this, 'onPageChange' );
this.pageManager.removeListener('pageLoad', this, 'onPageLoad');
this.pageManager.removeListener('pageError', this, 'onPageError');
this.releaseAll();
this.parent.destroy.call(this);
}
ContinuousViewer.prototype.onPageLoad = function( event, page ) {
if( this.pendingPageNum == page.getPageNum() ) {
this.displayImage( page );
}
}
ContinuousViewer.prototype.onWindowResize = function( event ) {
this.manualScroll(0);
}
ContinuousViewer.prototype.onKeyPress = function( event ) {
var tag = Event.element(event).tagName;
switch( tag )
{
case 'SELECT':
case 'TEXTAREA':
return;
}
var key = 0;
if( event.charCode )
key = event.charCode;
else if( event.keyCode )
key = event.keyCode;
else if( event.which )
key = event.which;
else
return;
var scrollAmount = 0;
switch( key )
{
case 33:
scrollAmount = -document.body.clientHeight + ContinuousViewer.LINE_HEIGHT;
break;
case 34:
scrollAmount = document.body.clientHeight - ContinuousViewer.LINE_HEIGHT;;
break;
case Event.KEY_UP:
scrollAmount = -ContinuousViewer.LINE_HEIGHT;
break;
case Event.KEY_DOWN:
scrollAmount = ContinuousViewer.LINE_HEIGHT;
break;
default:
return;
}
if( scrollAmount )
{
Event.stop( event );
this.manualScroll( scrollAmount );
}
}
ContinuousViewer.prototype.onMouseWheel = function( event ) {
var scrollAmount = 0;
if( event.detail )
scrollAmount = event.detail * 20;
else if( event.wheelDelta )
scrollAmount = -(event.wheelDelta >> 1);
else
return;
this.manualScroll( scrollAmount );
if( event.preventDefault ) {
event.preventDefault();
} else {
event.returnVal = false;
}
return false;
}
ContinuousViewer.prototype.displayImage = function( page ) {
this.hideMessage();
var pageNum = page.getPageNum();
if( this.pages.getLength() == 0 ) {
page.setLeft(0);
page.setTop(0);
this.reader.setCurrentPage( page.getPageNum(), page.getChecksum() );
}
else if( this.getFirstPage().getPrevPage() == pageNum ) {
var currentPage = this.pages.get( page.getNextPage() );
page.setLeft( currentPage.getAbsoluteLeft() );
page.setTop( currentPage.getAbsoluteTop() - page.getHeight() - 5 );
}
else if( this.getLastPage().getNextPage() == pageNum )  {
page.setLeft( this.getLastPage().getAbsoluteLeft() );
page.setTop( this.getLastPage().getAbsoluteTop() + this.getLastPage().getHeight() + 5 );
}
else {
_a=0;
return;
}
page.show();
this.pages.put(pageNum, page);
this.reader.fireScreenEvent(page, true);
this.isLoading = false;
this.pendingPage = undefined;
this.pendingPageNum = undefined;
this.reader.adjustViewerSize();
}
ContinuousViewer.prototype.onPageError = function( event, page ) {
if( this.pendingPageNum == page.getPageNum() )
this.displayError( page );
}
ContinuousViewer.prototype.displayError = function( page ) {
var logicalPage = this.pageManager.getLogicalPageNumber( page.getPageNum() );
var pageNumStr = page.isSurpriseMe?"random":page.getPageNum();
if( page.getErrorCode() == "AUTH" ) {
window.location = Config.getReaderURL() + "?asin=" + this.reader.asin + "&v=strip-auth&pageID=" + pageNumStr + "&checkSum=" + page.getChecksum();
}
else {
this.pageManager.releasePage(page);
this.cleanup(page);
if( page.getErrorCode().match( 'SERVICE' ) )
{
_a=0;
displayErrorDialog( 'Book temporarily unavailable, <a href="#">try again</a>', 300 );
}
else
{
_a=0;
displayErrorDialog( page.getErrorStr(), undefined, this.errorCallback );
}
}
this.isLoading = false;
this.pendingPage = undefined;
this.pendingPageNum = undefined;
}
ContinuousViewer.prototype.setInitialPage = function( pageNum, checksum, isSurpriseMe, errorCallback ) {
this.errorCallback = errorCallback;
this.releaseAll();
this.div.scrollTop = 0;
var page = this.reader.pageManager.createPage( pageNum, checksum );
page.isSurpriseMe = isSurpriseMe;
var logicalPage =  this.reader.pageManager.getLogicalPageNumber(pageNum);
if( !page.imageLoaded && !page.getErrorCode() ) {
this.showMessage( 'Getting page' + (this.reader.permissions == 'SITBpaid' ? ' ' + logicalPage : '') );
this.pendingPageNum = pageNum;
this.isLoading = true;
return false;
} else if( page.getErrorCode() ) {
this.displayError( page );
return false;
}
else {
this.displayImage( page );
this.fillPagesBottom();
this.fillPagesTop();
return true;
}
}
ContinuousViewer.prototype.makeCurrentPageVisible = function() {
var pageNum = this.reader.GetCurrentPage();
var page = this.reader.getDisplayedPage(pageNum);
var offset = page.getAbsoluteTop() - this.reader.getAbsoluteTop();
this.manualScroll(offset);
}
ContinuousViewer.prototype.manualScroll = function(scrollY) {
if( this.pages.getLength() == 0 || !this.isVisible)
return;
var minTop = 1000;
var maxBottom = 0;
var maxHeight = 0;
var maxHeightPage = 0;
var maxHeightChecksum = undefined;
this.pages.each( (function(page,pageNum) {
var pageTop = page.getAbsoluteTop();
var pageBottom = page.getHeight() + page.getAbsoluteTop();
if( pageTop < minTop ) {
minTop = pageTop;
minTopPage = page;
}
if( pageBottom > maxBottom ) {
maxBottom = pageBottom;
maxBottomPage = page;
}
}).bind(this) );
if( scrollY >= 0 && maxBottom-scrollY < this.reader.getClientHeight() ) {
scrollY = maxBottom - this.reader.getClientHeight();
if( !this.isLoading ) this.fillPagesBottom();
} else if( scrollY <= 0 && minTop-scrollY > 0 ) {
scrollY = minTop - 0;
if( !this.isLoading ) this.fillPagesTop();
}
if( scrollY == 0 ) return;
this.pages.each( (function(page,pageNum) {
page.moveBy(0, -scrollY);
var pageTop = page.getAbsoluteTop();
var pageBottom = page.getHeight() + page.getAbsoluteTop();
if( pageTop > this.reader.getClientHeight() + 50 || pageBottom < -50 ) {
this.releasePage(pageNum);
throw $continue;
}
var topShowing = pageTop < 0 ? 0 : pageTop;
var bottomShowing = pageBottom > this.reader.getClientHeight() ?
this.reader.getClientHeight() : pageBottom;
if( bottomShowing - topShowing > maxHeight )
{
maxHeight = bottomShowing - topShowing;
maxHeightPage = pageNum;
maxHeightChecksum= page.getChecksum();
}
}).bind(this) );
if( maxHeightPage != this.reader.GetCurrentPage() ) {
this.reader.setCurrentPage( maxHeightPage, maxHeightChecksum );
}
}
ContinuousViewer.prototype.fillPagesTop = function() {
if( this.isLoading )
return;
this.pendingPageNum = this.getFirstPage().getPrevPage();
if( !this.pendingPageNum ) {
return;
}
this.pendingPage = this.pageManager.createPage(
this.pendingPageNum, this.getFirstPage().getPrevPageChecksum() );
_a=0;
var logicalPage =  this.reader.pageManager.getLogicalPageNumber(this.pendingPageNum);
if( !this.pendingPage.imageLoaded ) {
this.showMessage( 'Getting page' +
(this.reader.permissions == 'SITBpaid' ? ' ' + logicalPage : "") );
this.isLoading = true;
return false;
}
else if( this.pendingPage.getErrorCode() ) {
this.displayError( this.pendingPage );
return false;
}
else {
this.displayImage( this.pendingPage );
}
}
ContinuousViewer.prototype.fillPagesBottom = function() {
if( this.isLoading )
return;
this.pendingPageNum = this.getLastPage().getNextPage();
_a=0;
if( this.pendingPageNum == '' ) {
return;
}
this.pendingPage = this.pageManager.createPage(
this.pendingPageNum, this.getLastPage().getNextPageChecksum() );
var logicalPage =  this.reader.pageManager.getLogicalPageNumber(this.pendingPageNum);
if( !this.pendingPage.imageLoaded ) {
this.showMessage( 'Getting page' +
(this.reader.permissions == 'SITBpaid' ? ' ' + logicalPage : "") );
this.isLoading = true;
return false;
}
else if( this.pendingPage.getErrorCode() ) {
this.displayError( this.pendingPage );
return false;
}
else {
this.displayImage( this.pendingPage );
}
}
function Page( pageManager, viewerDiv, annotationHolder ) {
Object.extend(this, new EventDispatcher());
this.pageManager = pageManager;
this.requestQueue = pageManager.requestQueue;
this.pageNum = null;
this.zoom = null;
this.viewerDiv = viewerDiv;
this.annotationHolder = $('annotationHolder');
this.errorCode = 0;
this.errorStr = "";
this.cached = false;
this.prevPage = "";
this.nextPage = "";
this.logicalPage = 0;
this.prevPageChecksum = "";
this.nextPageChecksum = "";
this.width = 0;
this.height = 0;
this.rightMargin = 0;
this.imgURL = "";
this.pageDiv = document.createElement("div");
this.imgNode = document.createElement("img");
this.wordDivs = document.createElement("div");
this.annotDiv = document.createElement("div");
this.pageDiv.className = "page-image";
this.imgNode.className = "image";
this.wordDivs.className = "words";
this.annotDiv.className = "annot-page";
browser.setPositioning(this.pageDiv, "absolute");
browser.setPositioning(this.imgNode, "relative");
browser.setPositioning(this.annotDiv, "absolute");
this.setLeft(0);
this.setTop(0);
this.rows = new Array();
this.boxes = new Array();
this.pageDiv.appendChild(this.imgNode);
this.pageDiv.appendChild(this.wordDivs);
this.viewerDiv.appendChild(this.pageDiv);
this.annotationHolder.appendChild(this.annotDiv);
this.retrieving = false;
this.imgNode.onmousedown = function(){ return false; };
this.imgNode.onmousemove = function(){ return false; };
this.hide();
this.imageLoaded = false;
this.boxLoaded = false;
this.onLoadHandlerInstance = this.onImageLoad.bind(this);
}
Object.extend(Page.prototype, SmartObject.prototype);
Page.prototype.setID = function(id) {
browser.setNodeAttribute( this.pageDiv, "id", id);
}
Page.prototype.clear = function() {
this.imageLoaded = false;
this.boxLoaded = false;
this.errorCode = 0;
this.errorStr = "";
this.cached = false;
this.boxes = new Array();
this.rows = new Array();
this.width = 0;
this.height = 0;
browser.setNodeAttribute(this.imgNode, "src", "");
this.imgNode.style.backgroundImage = "none";
this.hide();
this.prevPage = "";
this.nextPage = "";
this.prevPageChecksum = "";
this.nextPageChecksum = "";
this.setRetrieving(false);
this.setImgURL(null);
this.pageNum = -1;
this.zoom = -1;
this.pageDiv.removeChild(this.wordDivs);
this.wordDivs = document.createElement("div");
this.wordDivs.className = "words";
this.pageDiv.appendChild(this.wordDivs);
}
Page.prototype.load = function(pageNum, checksum, priority) {
this.clear();
var asin = this.pageManager.asin;
this.setPageNum(pageNum);
this.setZoom(this.pageManager.zoom);
if(checksum != undefined) {
this.setChecksum(checksum);
}
if( !priority ) priority = 5;
if( this.isRetrieving() ) {
return false;
}
this.setRetrieving( true );
_a=0;
var jBatch = new JSONComBatch();
if( Config.getReaderPermissions().load_box_data )
{
var tokenParams = { action: "tokens", p1: asin, p2: pageNum, p3: this.getZoom() };
var jsonTokens = new JSONCom( browser );
jsonTokens.setCallback( this.boxDataCallback.bind(this) );
jsonTokens.setURL( Config.getServiceURL() );
jsonTokens.setParams( tokenParams );
jBatch.addRequest(jsonTokens);
}
var imgParams = { action: "page",
p1: asin,
p2: pageNum,
p3: this.getZoom(),
checksum: this.getChecksum() };
this.pageManager.fireEvent('pageLoading', this, jBatch);
var json = new JSONCom( browser );
json.setCallback( this.imageDataCallback.bind(this) );
json.setURL( Config.getServiceURL() );
json.setParams( imgParams );
jBatch.addRequest(json);
this.requestQueue.addItem(pageNum, jBatch, priority);
}
Page.prototype.getBoxes = function() {
if( !this.boxLoaded ) {
throw new Exception("", "BoxNotReady");
}
return this.boxes;
}
Page.prototype.getRows = function() {
if( !this.boxLoaded ) {
throw new Exception("", "BoxNotReady");
}
return this.rows;
}
Page.prototype.getOnScreen = function() {
return this.onScreen;
}
Page.prototype.setOnScreen = function(value) {
this.onScreen = value;
}
Page.prototype.setPageNum = function(pageNum) {
this.pageNum = pageNum;
}
Page.prototype.getPageNum = function() {
return this.pageNum;
}
Page.prototype.setZoom = function(zoom) {
this.zoom = zoom;
}
Page.prototype.getZoom = function() {
return this.zoom;
}
Page.prototype.setPrevPage = function(prevPage) {
this.prevPage = prevPage;
}
Page.prototype.setNextPage = function(nextPage) {
this.nextPage = nextPage;
}
Page.prototype.getPrevPage = function() {
return this.prevPage;
}
Page.prototype.getNextPage = function() {
return this.nextPage;
}
Page.prototype.setLogicalPage = function(logicalPage) {
this.logicalPage = logicalPage;
}
Page.prototype.getLogicalPage = function() {
return this.logicalPage;
}
Page.prototype.setPrevPageChecksum = function(checksum) {
this.prevPageChecksum = checksum;
}
Page.prototype.setNextPageChecksum = function(checksum) {
this.nextPageChecksum = checksum;
}
Page.prototype.getPrevPageChecksum = function() {
return this.prevPageChecksum;
}
Page.prototype.getNextPageChecksum = function() {
return this.nextPageChecksum;
}
Page.prototype.getChecksum = function() {
return this.checksum;
}
Page.prototype.setChecksum = function(checksum) {
this.checksum = checksum;
}
Page.prototype.activate = function() {
this.prepare();
this.imgNode.setAttribute("src", this.imgURL);
this.imgNode.setAttribute("width", this.width);
this.imgNode.setAttribute("height", this.height);
}
Page.prototype.setImgURL = function(url) {
this.imgURL = url;
this.imageLoaded = false;
}
Page.prototype.isImageLoaded = function() {
return this.imageLoaded && this.isImageReady();
}
Page.prototype.setError = function(errorCode, errorStr) {
this.errorCode = errorCode;
this.errorStr = errorStr;
if( errorCode || errorStr != "" ) {
this.pageManager.fireEvent("pageError", this);
}
}
Page.prototype.getErrorCode = function () {
return this.errorCode;
}
Page.prototype.getErrorStr = function() {
return this.errorStr;
}
Page.prototype.setCached = function(cached) {
this.cached = cached;
}
Page.prototype.getCached = function() {
return this.cached;
}
Page.prototype.isRetrieving = function() {
return this.retrieving;
}
Page.prototype.setRetrieving = function(retrieve) {
this.retrieving = retrieve;
}
Page.prototype.getPageDiv = function() {
return this.pageDiv;
}
Page.prototype.boxDataCallback = function(jsoncom) {
if( this.boxLoaded ) {
return;
}
if( jsoncom.isError() ) {
_a=0;
_a=0;
_a=0;
_a=0;
if( !this.pageManager.displayedBoxError )
{
if (jsoncom.getError() == 'PAID_VIEW_PERMISSION' || jsoncom.getError() == 'SITB_VIEW_PERMISSION') {
this.setError(jsoncom.getErrorCode(), jsoncom.getError());
}
else {
displayErrorDialog( 'Selection and annotations are temporarily unavailable, you may continue reading or <a href="'
+ Config.getReaderURL() + '?asin=' + this.pageManager.asin + '">try again</a>.' );
this.pageManager.displayedBoxError = true;
}
}
} else {
this.boxes = eval(jsoncom.getData());
if( Config.getReaderPermissions().load_box_data )
{
this.prepareBoxes( this.boxes );
}
else
{
this.prepareSearchBoxes( this.boxes );
}
if( this.getErrorCode() == 0 ) {
this.setError(0,"");
}
}
this.boxLoaded = true;
if( this.imageLoaded ) {
_a=0;
this.pageManager.fireEvent('pageLoad', this);
}
}
Page.prototype.imageDataCallback = function(jsoncom) {
if( jsoncom.isError() ) {
this.setError(jsoncom.getErrorCode(), jsoncom.getError());
}
else {
var data = jsoncom.getData();
this.setPrevPage(data["prevPage"]);
this.setNextPage(data["nextPage"]);
this.setPrevPageChecksum(data["prevPageChecksum"]);
this.setNextPageChecksum(data["nextPageChecksum"]);
this.setWidth(data["width"]);
this.setHeight(data["height"]);
this.setImgURL(data["url"]);
this.setLogicalPage( this.pageManager.getLogicalPageNumber(this.getPageNum(), data.logicalPage) );
if( this.getErrorCode() == 0 ) {
this.setError(0,"");
}
Event.observe(this.imgNode, 'load', this.onLoadHandlerInstance);
}
this.setRetrieving(false);
this.activate();
this.pageManager.enforceCaching();
}
Page.prototype.onImageLoad = function() {
Event.stopObserving(this.imgNode, 'load', this.onLoadHandlerInstance);
this.imageLoaded = true;
this.imgNode.style.backgroundImage = "url(" + this.imgURL + ")";
browser.setNodeAttribute(this.imgNode, "src", Config.getGeneralMediaURL("x-locale/common/transparent-pixel"));
if( this.boxLoaded || !Config.getReaderPermissions().load_box_data ) {
_a=0;
this.pageManager.fireEvent('pageLoad', this);
}
}
Page.prototype.setLocation = function(left, top) {
browser.setLocation(this.pageDiv, left, top);
browser.setLocation(this.annotDiv, left, top);
}
Page.prototype.setRightMargin = function(right) {
this.rightMargin = right;
}
Page.prototype.getRightMargin = function() {
return this.rightMargin;
}
Page.prototype.hide = function() {
browser.hide(this.pageDiv);
browser.hide(this.annotDiv);
}
Page.prototype.show = function() {
browser.show(this.pageDiv);
browser.show(this.annotDiv);
}
Page.prototype.getWidth = function() {
return this.width;
}
Page.prototype.getHeight = function() {
return this.height;
}
Page.prototype.setWidth = function(width) {
this.width = width;
}
Page.prototype.setHeight = function(height) {
this.height = height;
}
Page.prototype.setLeft = function(l) {
browser.setLeft(this.pageDiv, l+"px");
browser.setLeft(this.annotDiv, l+"px");
}
Page.prototype.setTop = function(t) {
browser.setTop(this.pageDiv, t+"px");
browser.setTop(this.annotDiv, t+"px");
}
Page.prototype.moveBy = function(x, y) {
browser.moveBy(this.pageDiv, x, y);
browser.moveBy(this.annotDiv, x, y);
}
Page.prototype.getAbsoluteLeft = function() {
return browser.getRelativeLeft(this.pageDiv);
}
Page.prototype.getAbsoluteTop = function() {
return browser.getRelativeTop(this.pageDiv);
}
Page.prototype.prepare = function() {
this.setTop(-2000);
this.setLeft(-2000);
this.show();
}
Page.prototype.prepareBoxes = function( boxes ) {
var total_height = 0;
for (var jj=0; jj<boxes.length; jj++) {
total_height += boxes[jj].height;
}
var avg_height = total_height / boxes.length;
var ymin = -1, ymax = -1;
var first_row = true;
var xmin = 9999, xmax =  0;
var new_row_index = 0;
var new_paragraph = true;
this.rows = new Array();
var rowIndex = 0;
for( var jj=0; jj<boxes.length; jj++ ) {
boxes[jj].div = undefined;
boxes[jj].types = new Array();
for (var topType=0; topType < Indicator.MAX_TYPES; topType++) {
boxes[jj].types[topType] = 0;
}
if( boxes[jj].top > ymax || (boxes[jj].top+boxes[jj].height) < ymin ) {
if( boxes[jj].top - ymax > (3 * avg_height / 2) ||
boxes[jj].left > xmax + 10 ) {
new_paragraph = true;
} else {
new_paragraph = false;
}
if( first_row ) {
first_row = false;
} else {
this.rows[rowIndex] = new Row(boxes, this.getPageNum(), rowIndex, xmin, xmax, ymin, ymax, new_row_index, jj);
for( var kk=new_row_index; kk<jj; kk++ ) {
boxes[kk].top = ymin;
boxes[kk].height = ymax - ymin;
boxes[kk].row = rowIndex;
}
rowIndex++;
}
new_row_index = jj;
if( first_row || new_paragraph ) {
ymin = boxes[jj].top;
} else {
ymin = ymax;
}
ymax = boxes[jj].top +  boxes[jj].height;
boxes[jj].new_row = true;
xmin = boxes[jj].left;
xmax = boxes[jj].left + boxes[jj].width;
} else {
if( (first_row || new_paragraph) && boxes[jj].top < ymin )
ymin = boxes[jj].top;
if( boxes[jj].top + boxes[jj].height > ymax )
ymax = boxes[jj].top + boxes[jj].height;
boxes[jj].new_row = false;
if( boxes[jj].left < xmin ) xmin = boxes[jj].left;
if( boxes[jj].left + boxes[jj].width > xmax ) xmax = boxes[jj].left + boxes[jj].width;
}
}
this.rows[rowIndex] = new Row(boxes, this.getPageNum(), rowIndex, xmin, xmax, ymin, ymax, new_row_index, jj);
for (var kk=new_row_index; kk<jj; kk++) {
boxes[kk].top = ymin;
boxes[kk].height = ymax - ymin;
boxes[kk].row = rowIndex;
}
}
Page.prototype.prepareSearchBoxes = function( boxes ) {
for( var jj=0; jj<boxes.length; jj++ ) {
boxes[jj].div = undefined;
boxes[jj].types = new Array();
for (var topType=0; topType < Indicator.MAX_TYPES; topType++) {
boxes[jj].types[topType] = 0;
boxes[jj].new_row = true;
}
}
}
compareTop = function (box0, box1) {
return (box0.top < box1.top)?-1:(box0.top==box1.top)?0:1;
}
compareLeft = function (box0, box1) {
return (box0.left < box1.left)?-1:(box0.left==box1.left)?0:1;
}
Row = function( sortedBoxes, page, rowID, xMin, xMax, yMin, yMax, startIndex, endIndex ) {
this.rowID = rowID;
this.xMin = xMin;
this.xMax = xMax;
this.yMin = yMin;
this.yMax = yMax;
this.endIndex = endIndex;
this.columns = new Array();
var colIndex = 0;
for (var ii=startIndex; ii<endIndex; ii++) {
try {
this.columns[colIndex] = sortedBoxes[ii];
} catch(e) {
throw e;
}
colIndex++;
}
this.columns.sort(compareLeft);
}
Page.prototype.rescale = function(pseudoZoom) {
if (!this.isImageReady()) {
return;
}
return;
if( pseudoZoom > 300 ) {
pseudoZoom = 300;
}
else if( pseudoZoom < 50 ) {
pseudoZoom = 50;
}
var width = this.getWidth() * pseudoZoom / this.displayZoom;
var height = this.getHeight() * pseudoZoom / this.displayZoom;
this.displayZoom = pseudoZoom;
browser.setWidth( this.imgNode, width );
browser.setHeight( this.imgNode, height );
}
Reader = function( div, asin, pageNum, checksum, keywords, permissions, viewID ) {
this.div = $('layoutBody');
this.viewerDiv = $('viewer');
this.annotationHolder = $('annotationHolder');
this.initComplete = false;
this.zoom = 100;
this.asin = asin;
this.keywords = keywords;
this.viewID = viewID;
Object.extend(this, new EventDispatcher());
this.pages = new AssociativeArray();
this.currentPage = pageNum;
this.currentChecksum = checksum;
this.pageChanged = true;
this.permissions = permissions;
this.annotationEnabled = Config.getReaderPermissions().annotations_enabled;
this.selectionEnabled = Config.getReaderPermissions().selection_enabled;
this.dragging = false;
this.dragX = 0;
this.dragY = 0;
this.mouseOver = false;
this.pageDelta = 1;
this.viewer = null;
this.citation = "";
this.waitingForSurpriseMe = false;
this.copyRequest1 = "";
this.copyRequest2 = "";
this.copyResponse1 = "";
this.copyResponse2 = "";
this.copyRequestCount = 0;
this.copyResponseCount = 0;
userSettings.load( this.onSettingsReady.bind(this) );
this.backButtonArmed = false;
this.bbFrameInit();
extras.init("layoutSidebar");
try {
this.sidebar = new Sidebar(asin);
this.pageManager = new PageManager( this.asin, this.zoom, this.viewerDiv, this );
if( this.annotationEnabled ) {
this.annotationManager = new AnnotationManager( this, this.asin );
}
this.pageManager.init();
this.search = new Search(this);
this.divManager = new DivManager(this, this.viewerDiv, 1000, 200);
this.DisplayRandomPageCallbackConduit = function(jsoncom) {
self.DisplayRandomPageCallback(jsoncom);
}
if( this.selectionEnabled ) {
this.selector = new Selector( this.viewerDiv, this );
cursor.setCursor("text");
}
this.scroller = new Scroller(this);
} catch(e) { e.logError(); }
toolbar.addListener('zoomInRequest', this, 'onToolbarAction');
toolbar.addListener('zoomOutRequest', this, 'onToolbarAction');
toolbar.addListener('singlePageRequest', this, 'onToolbarAction');
toolbar.addListener('continuousRequest', this, 'onToolbarAction');
toolbar.addListener('printRequest', this, 'onToolbarAction');
toolbar.addListener('copyRequest', this, 'onToolbarAction');
toolbar.addListener('leftColumnRequest', this, 'onToolbarAction');
toolbar.addListener('miniBookshelfRequest', this, 'onToolbarAction');
toolbar.addListener('contentsRequest', this, 'onToolbarAction');
toolbar.addListener('reportAProblemRequest', this, 'onToolbarAction');
this.addListener('pageChange', toolbar, 'onPageChange');
this.addListener('pageChange', userSettings, 'onPageChange');
this.addListener('pageChange', this.scroller, 'onPageChange');
if( this.annotationEnabled )
this.addListener('pageChange', this, 'onPageChange');
Event.observe( window, 'resize', this.onWindowResize.bind(this), false );
Event.observe( this.div, 'scroll', this.onScroll.bind(this), false );
if( browser.saf ) {
this.lastAvailHeight = window.outerHeight;
}
this.onWindowResize();
this.onScroll();
if (this.annotationEnabled)
this.annotationManager.initEventListeners();
this.initComplete = true;
if( userSettings.isLoaded() ) {
this.onSettingsReady();
}
}
Object.extend(Reader.prototype, SmartObject.prototype);
Reader.prototype.onSettingsReady = function() {
if( !this.initComplete ) {
_a=0;
return;
}
try {
this.SetViewer(userSettings.get("viewMode"));
this.sidebar.setOpen(userSettings.get("sidebar"));
if( this.annotationEnabled )
{
this.annotationManager.setPrivateAnnotationDisplayFilter(userSettings.get("showAnnotations"));
this.annotationManager.setDefaultAnnotationScope(userSettings.get("defaultAnnotationScope"));
}
if( userSettings.get('showIncompatibleBrowserDialog') )
this.checkBrowserCompatibility();
if( this.keywords && this.viewID == "search-inside" ) {
this.search.asin = this.asin;
this.search.keywords = this.keywords;
this.search.stripSearch();
}
} catch(e) { e.logError(); }
}
Reader.prototype.fireScreenEvent = function( page, pageOn ) {
_a=0;
page.setOnScreen(pageOn);
if( pageOn ) {
this.fireEvent('pageOnScreen', page);
} else {
this.fireEvent('pageOffScreen', page);
}
}
Reader.prototype.SetViewer = function( type ) {
if( this.viewerType == type ) return;
this.viewerType = type;
if( this.viewer )
this.viewer.destroy();
switch(type) {
case "single":
this.viewer = new Viewer();
this.pageDelta = 1;
this.viewer.initViewer(this);
this.DisplayPage(this.GetCurrentPage(), this.currentChecksum);
$("singlePage_check").src = Toolbar.IMG_CHECK;
$("continuous_check").src = Toolbar.IMG_SPACER;
break;
case "continuous":
this.viewer = new ContinuousViewer();
this.pageDelta = 1;
this.viewer.initViewer(this);
this.DisplayPage(this.GetCurrentPage(), this.currentChecksum);
$("continuous_check").src = Toolbar.IMG_CHECK;
$("singlePage_check").src = Toolbar.IMG_SPACER;
if( browser.saf ) {
this.viewer.manualScroll(1);
this.viewer.manualScroll(-1);
}
break;
}
this.setViewerVisibility(true);
}
Reader.prototype.DisplayPage = function( pageNum, checksum, hideSearchHighlights, isSurpriseMe, errorCallback ) {
if( !pageNum ) return;
_a=0;
try {
if( hideSearchHighlights != undefined && hideSearchHighlights )
this.search.deactivate();
this.search.hideSearch();
this.setScrollTop(0);
this.viewer.setInitialPage( pageNum, checksum, isSurpriseMe, errorCallback );
this.unloadPrintView();
} catch( e ) { e.logError(); }
return false;
}
Reader.prototype.DisplayLastValidPage = function() {
this.DisplayPage(this.currentPage, this.currentChecksum);
}
Reader.prototype.DisplayRandomPageCallback = function (jsoncom) {
_a=0;
if( this.waitingForSurpriseMe ) {
if( jsoncom.isError() ) {
_a=0;
displayErrorDialog( 'Surprise Me! temporarily unavailable, try again later.', 350 );
}
else {
var data = jsoncom.getData();
this.DisplayPage( data[0], data[1], true, true );
}
this.waitingForSurpriseMe = false;
}
return false;
}
Reader.prototype.DisplayRandomPage = function() {
_a=0;
if( !this.waitingForSurpriseMe ) {
this.waitingForSurpriseMe = true;
var params = { action: "getRandomSeqNum", asin: this.asin, requestID: Math.floor(Math.random() * 9999999) };
var json = new JSONCom( browser );
json.setCallback( this.DisplayRandomPageCallback.bind(this) );
json.setURL( Config.getServiceURL() );
json.setParams( params );
json.sendRequest();
}
}
Reader.prototype.SetZoom = function( zoom ) {
if( zoom == this.zoom )
return;
this.viewer.releaseAll();
this.pageManager.setZoom( zoom );
if( this.selectionEnabled )
this.selector.clearTextSelection();
_a=0;
this.DisplayPage(this.GetCurrentPage(), this.currentChecksum);
this.fireEvent('zoomChange', zoom, this.zoom);
this.zoom = zoom;
}
Reader.prototype.GetZoom = function() {
return this.zoom;
}
Reader.prototype.GetCurrentPage = function() {
return this.currentPage;
}
Reader.prototype.NextPage = function () {
var pageNum;
var lastPage = this.pages.get(this.currentPage);
if( !lastPage ) return;
for( var i=1; i<this.pageDelta; i++ ) {
lastPage = this.pages.get(lastPage.getNextPage());
if( !lastPage ) return;
}
if( lastPage.getNextPage() == '' ) {
return;
}
this.DisplayPage( lastPage.getNextPage(), lastPage.getNextPageChecksum() );
return false;
}
Reader.prototype.PreviousPage = function() {
var pageNum;
var firstPage = this.pages.get(this.currentPage);
if( !firstPage ) return;
for( var i=1; i<this.pageDelta; i++ ) {
if( this.pages.get(firstPage.getPrevPage()) ) {
firstPage = this.pages.get(firstPage.getPrevPage());
if( !firstPage ) return;
}
}
if( firstPage.getPrevPage() == '' ) {
return;
}
this.DisplayPage( firstPage.getPrevPage(), firstPage.getPrevPageChecksum() );
return false;
}
Reader.prototype.GetMode = function() {
return this.mode;
}
Reader.prototype.hScrollVisible = function() {
return (this.div.scrollWidth > this.div.offsetWidth);
}
Reader.prototype.printPage = function () {
try {
if ($("viewerOverlay").style.display == "none") {
extras.showLoader();
var params = { action: "getPrintAccess", p1: this.asin, p2: this.GetCurrentPage() };
var json = new JSONCom( browser );
json.setKey(this.GetCurrentPage());
json.setCallback( this.printPageCallback.bind(this) );
json.setURL( Config.getServiceURL() );
json.setParams( params );
json.sendRequest();
}
else {
print();
}
} catch (e) { e.logError(); }
}
Reader.prototype.printPageCallback = function(jsoncom) {
try {
if( jsoncom.isError() ) {
extras.hideLoader();
if( jsoncom.getErrorCode().match( 'SERVICE' ) )
{
_a=0;
displayErrorDialog( 'The Print feature is temporarily unavailable, try again later.' );
}
else if( jsoncom.getErrorCode() == 'PRINT_LIMIT_EXCEEDED' )
{
_a=0;
displayErrorDialog( jsoncom.getError() );
}
}
else {
var data = jsoncom.getData();
var page = jsoncom.getKey();
var url = data.url;
if( userSettings.get('showPrintDialog') )
{
var text = 'You may only print the current page you are viewing.<br/><br/>' +
'<input type="checkbox" id="showPrintDialogCheck"/>&nbsp;' +
'Do not show this message again';
var dialogOptions = {
message: text,
width: 300,
title: " Please note",
okAction: (function(page) {
if( $('showPrintDialogCheck').checked ) {
userSettings.set('showPrintDialog', false);
}
this.loadPrintView(page, url);
}).bind(this, page)
};
displayMessageDialog( dialogOptions );
} else {
this.loadPrintView(page, url);
}
}
} catch (e) { e.logError(); }
}
Reader.prototype.loadPrintView = function (pageNum, url) {
if (this.pageManager.getPage(pageNum) == undefined) {
_a=0;
return;
}
var naturalHeight = this.pageManager.getPage(pageNum).getHeight();
var naturalWidth = this.pageManager.getPage(pageNum).getWidth();
var aspectRatio = naturalHeight / naturalWidth;
var image = $("printImage");
image.style.display = "block";
if( aspectRatio >= 1 )
{
image.style.height = '96%';
image.style.width  = '';
}
else
{
image.style.height = '';
image.style.width  = '100%';
}
image.setAttribute("src", url);
$("printBookInfo").innerHTML = this.getCitation(pageNum);
$("printWarning").style.display = "none";
$("printBookInfo").style.display = "block";
if( browser.saf )
{
$('printView').style.width = "700px";
$('printView').style.height = "1050px";
$('printView').style.marginTop = "50px";
}
image.onload = this.imageComplete.bind(this);
}
Reader.prototype.imageComplete = function()
{
$('printImage').onload = null;
extras.hideLoader();
print();
}
Reader.prototype.unloadPrintView = function() {
if( $('printWarning') )
$("printWarning").style.display = "block";
if( $('printImage') )
$('printImage').style.display = "none";
if( $('printBookInfo') )
$('printBookInfo').style.display = "none";
}
Reader.prototype.copyText = function () {
if( this.selector.isSelected() ) {
extras.showLoader();
var startPageNum = this.selector.getStartPageNum();
var startWordID = this.selector.getStartWordID();
var endPageNum = this.selector.getEndPageNum();
var endWordID = this.selector.getEndWordID();
if( startPageNum != endPageNum ) {
_a=0;
var boxesOne = this.pageManager.getPageObj(startPageNum).boxes;
var boxesTwo = this.pageManager.getPageObj(endPageNum).boxes;
var firstPageNum, firstStartWordID, firstEndWordID;
var secondPageNum, secondStartWordID, secondEndWordID;
if( startPageNum > endPageNum ) {
firstPageNum      = endPageNum;
firstStartWordID  = endWordID;
firstEndWordID    = boxesTwo.length - 1;
secondPageNum     = startPageNum;
secondStartWordID = 0;
secondEndWordID   = startWordID;
} else {
firstPageNum      = startPageNum;
firstStartWordID  = startWordID;
firstEndWordID    = boxesOne.length - 1;
secondPageNum     = endPageNum;
secondStartWordID = 0;
secondEndWordID   = endWordID;
}
this.copyRequest1 = firstPageNum + "_" + firstStartWordID + "_" + firstEndWordID;
this.copyRequest2 = secondPageNum + "_" + secondStartWordID + "_" + secondEndWordID;
this.copyRequestCount = 2;
this.checkCopyPermissions( firstPageNum, firstStartWordID, firstEndWordID );
this.checkCopyPermissions( secondPageNum, secondStartWordID, secondEndWordID );
} else {
_a=0;
var boxes = this.pageManager.getPageObj(startPageNum).boxes;
if( startWordID > endWordID ) {
var temp = startWordID;
startWordID = endWordID;
endWordID = temp;
}
this.copyRequest1 = startPageNum + "_" + startWordID + "_" + endWordID;
this.copyRequestCount = 1;
this.checkCopyPermissions( startPageNum, startWordID, endWordID );
}
}
}
Reader.prototype.checkCopyPermissions = function( pageNum, startWordID, endWordID ) {
var params = { action: "getCopyAccess", p1: reader.asin, p2: pageNum, p3: startWordID, p4: endWordID };
var jsonTokens = new JSONCom( browser );
jsonTokens.setKey( pageNum + "_" + startWordID + "_" + endWordID );
jsonTokens.setCallback( this.gotCopyPermissions.bind( this ) );
jsonTokens.setURL( Config.getServiceURL() );
jsonTokens.setParams( params );
jsonTokens.sendRequest();
}
Reader.prototype.gotCopyPermissions = function( jsoncom ) {
var response = 0;
var key = jsoncom.getKey();
var args = key.split("_");
if( this.copyRequest1 == key ) {
this.copyRequest1 = args[0];
response = 1;
} else if( this.copyRequest2 == key ) {
this.copyRequest2 = args[0];
resposne = 2;
} else {
return;
}
_a=0;
if( jsoncom.isError() ) {
_a=0;
extras.hideLoader();
if( jsoncom.getErrorCode().match( 'SERVICE' ) )
{
_a=0;
displayErrorDialog( 'The Copy feature is temporarily unavailable, try again later.' );
}
else if( jsoncom.getErrorCode() == 'COPY_LIMIT_EXCEEDED' )
{
_a=0;
displayErrorDialog( jsoncom.getError() );
}
this.copyRequest1 = "";
this.copyRequest2 = "";
this.copyResponse1 = "";
this.copyResponse2 = "";
this.copyResponseCount = 0;
this.copyRequestCount = 0;
} else {
var boxes = eval(jsoncom.getData());
var string = "";
var j = 0;
for( ; j < boxes.length - 1; j++ ) {
string += boxes[j].string + ' ';
}
string += boxes[j].string;
if( response == 1 ) {
this.copyResponse1 = string;
} else {
this.copyResponse2 = string;
}
this.copyResponseCount++;
if( this.copyResponseCount == this.copyRequestCount ) {
extras.hideLoader();
showCopyDialog();
var pages = (this.copyRequest2 != "") ?
[this.copyRequest1, this.copyRequest2] : this.copyRequest1;
var string = this.copyResponse1 + " " + this.copyResponse2 +
"\r\nCOPYRIGHTED MATERIAL\r\n" + this.getCitation(pages);
clipboard.set( string );
this.copyRequest1 = "";
this.copyRequest2 = "";
this.copyResponse1 = "";
this.copyResponse2 = "";
this.copyResponseCount = 0;
this.copyRequestCount = 0;
}
}
}
Reader.prototype.checkBrowserCompatibility = function () {
if ( browser.isCompatible() )
return;
var txt = 'The Amazon Online Reader works best with Internet Explorer 6.0+, Firefox 1.5+, or Safari 2.0.<br/><br/>' +
'<input type="checkbox" id="showIncompatibleBrowserDialogCheck"/>&nbsp;' +
'Do not show this message again';
var dialogOptions = {
message: txt,
width: 350,
okAction: (function(page) {
if( $('showIncompatibleBrowserDialogCheck').checked ) {
userSettings.set('showIncompatibleBrowserDialog', false);
}
}).bind(this)
};
displayMessageDialog( dialogOptions );
}
Reader.prototype.onToolbarAction = function(eventName) {
if( eventName == 'zoomInRequest' ) {
this.SetZoom(133);
} else if( eventName == 'zoomOutRequest' ) {
this.SetZoom(100);
} else if( eventName == 'singlePageRequest' ) {
this.SetViewer('single');
} else if( eventName == 'continuousRequest' ) {
this.SetViewer('continuous');
} else if( eventName == 'printRequest' ) {
this.printPage();
} else if( eventName == 'copyRequest' ) {
this.copyText();
} else if( eventName == 'leftColumnRequest' ) {
showHidePalettes();
this.adjustViewerSize();
} else if( eventName == 'miniBookshelfRequest' ) {
bookshelf.toggle();
} else if( eventName == 'contentsRequest' ) {
this.displayHelpContents();
} else if( eventName == 'reportAProblemRequest' ) {
this.displayReportAProblem();
}
}
Reader.prototype.setScroll = function(scrollX, scrollY) {
var pageNum;
var topPage = this.viewer.getFirstPage();
var bottomPage = this.viewer.getLastPage();
var pageTop = topPage.getAbsoluteTop();
var pageBottom = bottomPage.getAbsoluteTop() + bottomPage.getHeight();
if( pageBottom + scrollY < this.getHeight() ) {
this.viewer.onReachBottomEdge(scrollX, scrollY);
}
else if( pageTop + scrollY > 0 ) {
this.viewer.onReachTopEdge(scrollX, scrollY);
}
else {
this.viewer.onNormalScroll(scrollX, scrollY);
}
}
Reader.prototype.setCurrentPage = function( pageNum, checksum ) {
if( this.pageChanged ) {
this.fireEvent( 'pageChange', this.pageManager.getPage(pageNum),
this.pageManager.getPage(this.currentPage) );
}
if( this.currentPage != pageNum ) {
this.pageChanged = true;
}
this.currentPage = pageNum;
this.currentChecksum = checksum;
}
Reader.prototype.setCitation = function( citation ) {
this.citation = citation;
}
Reader.prototype.getViewer = function() {
return this.viewer;
}
Reader.prototype.getRelativeLeft = function() {
return browser.getRelativeLeft(this.div);
}
Reader.prototype.getAbsoluteLeft = function() {
return this.getViewerLeft() - this.div.scrollLeft;
}
Reader.prototype.getRelativeTop = function() {
return browser.getRelativeTop(this.div);
}
Reader.prototype.getAbsoluteTop = function() {
var top = this.getViewerTop() - this.div.scrollTop;
return top;
}
Reader.prototype.getViewerLeft = function() {
return browser.getAbsoluteLeft(this.viewerDiv) + browser.getAbsoluteLeft(this.div);
}
Reader.prototype.getViewerTop = function() {
return browser.getAbsoluteTop(this.viewerDiv) + browser.getAbsoluteTop(this.div);
}
Reader.prototype.getRelativeRight = function() {
return this.getRelativeLeft() + this.getWidth();
}
Reader.prototype.getAbsoluteRight = function() {
return this.getAbsoluteLeft() + this.getWidth();
}
Reader.prototype.getWidth = function() {
return browser.getWidth(this.div);
}
Reader.prototype.getHeight = function() {
return browser.getHeight(this.div);
}
Reader.prototype.isSelectionEnabled = function() {
return this.selectionEnabled;
}
Reader.prototype.getDisplayedPage = function(pageNum) {
var page = this.pages.get(pageNum);
if( !page ) {
throw new Exception('Page: '+pageNum+' is not displayed', 'PageNotDisplayed');
}
return page;
}
Reader.prototype.getClientWidth = function() {
return this.div.clientWidth;
}
Reader.prototype.getClientHeight = function() {
return this.div.clientHeight;
}
Reader.prototype.getScrollWidth = function() {
return this.div.scrollWidth;
}
Reader.prototype.getScrollHeight = function() {
return this.div.scrollHeight;
}
Reader.prototype.getScrollTop = function() {
return this.div.scrollTop;
}
Reader.prototype.getScrollLeft = function() {
return this.div.scrollLeft;
}
Reader.prototype.setScrollTop = function(scrollTop) {
this.div.scrollTop = scrollTop;
}
Reader.prototype.setScrollLeft = function(scrollLeft) {
this.div.scrollLeft = scrollLeft;
}
Reader.prototype.setWidth = function( width ) {
browser.setWidth(this.div, width);
}
Reader.prototype.setPermissions = function (perm) {
this.permissions = perm;
}
Reader.prototype.getPermissions = function () {
return this.permissions;
}
Reader.prototype.getCitation = function (pages) {
var value = this.citation;
if(typeof pages == 'string') pages = [pages];
if(typeof pages != 'undefined' &&
typeof pages.length != 'undefined' &&
pages.length > 0) {
value += (pages.length > 1) ? ' Pages ' : ' Page ';
value += pages.map(( function(p) {
return this.pageManager.getLogicalPageNumber(p);
}).bind(this)).join(',');
value += '.';
}
return value;
}
Reader.prototype.getClickedPageNum = function(x, y) {
var returnPage;
this.viewer.pages.each((function(page, pageNum) {
if (page != undefined) {
var divLeft = browser.getAbsoluteLeft(this.div);
var pageLeft = browser.getAbsoluteLeft(page.getPageDiv());
var pageWidth = browser.getWidth(page.getPageDiv());
var divTop = browser.getAbsoluteTop(this.div);
var pageTop = browser.getAbsoluteTop(page.getPageDiv());
var pageHeight = browser.getHeight(page.getPageDiv());
if ( (divLeft + pageLeft) < x && (divLeft + pageLeft + pageWidth) > x
&& (divTop + pageTop) < y && (divTop + pageTop + pageHeight) > y )
{
returnPage = page.getPageNum();
throw $break;
}
}
}).bind(this));
return returnPage;
}
Reader.prototype.getClickedPageX = function(x, y) {
var returnVal;
this.viewer.pages.each((function(page, pageNum) {
if (page != undefined) {
var divLeft = browser.getAbsoluteLeft(this.div);
var pageLeft = browser.getAbsoluteLeft(page.getPageDiv());
var pageWidth = browser.getWidth(page.getPageDiv());
var divTop = browser.getAbsoluteTop(this.div);
var pageTop = browser.getAbsoluteTop(page.getPageDiv());
var pageHeight = browser.getHeight(page.getPageDiv());
if ( (divLeft + pageLeft) < x && (divLeft + pageLeft + pageWidth) > x
&& (divTop + pageTop) < y && (divTop + pageTop + pageHeight) > y )
{
returnVal = x - divLeft - pageLeft;
throw $break;
}
}
}).bind(this));
return returnVal;
}
Reader.prototype.getClickedPageY = function(x, y) {
var returnVal;
this.viewer.pages.each((function(page, pageNum) {
if (page != undefined) {
var divLeft = browser.getAbsoluteLeft(this.div);
var pageLeft = browser.getAbsoluteLeft(page.getPageDiv());
var pageWidth = browser.getWidth(page.getPageDiv());
var divTop = browser.getAbsoluteTop(this.div);
var pageTop = browser.getAbsoluteTop(page.getPageDiv());
var pageHeight = browser.getHeight(page.getPageDiv());
var scroll = document.body.scrollTop;
if ( (divLeft + pageLeft) < x && (divLeft + pageLeft + pageWidth) > x
&& (divTop + pageTop) < y && (divTop + pageTop + pageHeight) > y )
{
returnVal = y - divTop - pageTop + scroll;
throw $break;
}
}
}).bind(this));
return returnVal;
}
Reader.prototype.adjustViewerSize = function() {
try {
var pageObj = this.pageManager.getPageObj(this.GetCurrentPage());
browser.setWidth(this.viewerDiv, pageObj.getWidth());
if( this.viewerType == 'single' ) {
_a=0;
this.viewerDiv.style.height = pageObj.getHeight();
browser.setHeight( $('viewerContainer'), pageObj.getHeight() );
}
else if( this.viewerType == 'continuous' ) {
var targetHeight = browser.getHeight(this.div);
if( this.hScrollVisible() ) {
targetHeight -= 15;
}
this.viewerDiv.style.height = targetHeight;
browser.setHeight( $('viewerContainer'), targetHeight );
}
} catch(e) {
if( !e.isType('PageNotReady') ) {
throw e;
}
}
this.onScroll();
this.sidebar.onWindowResize();
if( this.annotationEnabled ) {
this.pages.each((function(page,pageNum) {
this.annotationManager.refreshAnnotationControls(pageNum);
}).bind(this));
}
}
Reader.prototype.updateWingVisibility = function() {
var wingVisible = (browser.getVisibility(this.viewerDiv) == 'visible'
&& this.viewerType == 'single');
var page = this.pages.get(this.currentPage);
var wingVisibleL = (wingVisible && (!page || page.getPrevPage() != '')) ? 'show' : 'hide';
var wingVisibleR = (wingVisible && (!page || page.getNextPage() != '')) ? 'show' : 'hide';
browser.setVisibility($('pageTurnerLeft'), wingVisibleL);
browser.setVisibility($('pageTurnerRight'), wingVisibleR);
}
Reader.prototype.setViewerVisibility = function(visible) {
var viewerVisibility = visible ? 'show' : 'hide';
var scrollerVisibility = (visible && this.viewerType == 'continuous') ? 'show' : 'hide';
var layoutOverflow = (scrollerVisibility == 'show') ? 'hidden' : 'scroll';
this.viewerDiv.style.overflow = 'hidden';
browser.setVisibility(this.viewerDiv, viewerVisibility);
browser.setVisibility(this.annotationHolder, viewerVisibility);
browser.setVisibility($('vScrollerRail'), scrollerVisibility);
this.updateWingVisibility();
if( visible ) {
this.adjustViewerSize();
}
else {
browser.setHeight(this.viewerDiv, 0);
browser.setHeight($('viewerContainer'), 0);
}
this.viewer.isVisible = visible;
}
Reader.prototype.getRelativePageLocation = function(clientX, clientY) {
var readerX = clientX - this.getAbsoluteLeft();
var readerY = clientY - this.getAbsoluteTop();
var pageX = null;
var pageY = null;
var clickedPage = null;
this.pages.each((function(page,pageNum) {
var pageLeft = page.getAbsoluteLeft();
var pageTop = page.getAbsoluteTop();
var pageWidth = page.getWidth();
var pageHeight = page.getHeight();
if( pageLeft <= readerX && pageTop <= readerY &&
pageLeft + pageWidth >= readerX && pageTop + pageHeight >= readerY )
{
pageX = readerX - pageLeft;
pageY = readerY - pageTop;
clickedPage = page;
throw $break;
}
}).bind(this));
var returnVal = new AssociativeArray();
if( clickedPage != null ) {
returnVal.put('page', clickedPage);
returnVal.put('pageX', pageX);
returnVal.put('pageY', pageY);
}
return returnVal;
}
Reader.prototype.onWindowResize = function(e) {
if( browser.saf ) {
var availHeight = window.outerHeight;
var heightDiff = availHeight - this.lastAvailHeight;
if( heightDiff != 0 ) {
$('body').style.height = $('body').clientHeight + heightDiff;
var targetHeight = document.body.clientHeight;
if( this.viewerType == 'continuous' && this.hScrollVisible() ) {
targetHeight -= 15;
}
browser.setHeight( this.viewerDiv, targetHeight );
browser.setHeight( $('viewerContainer'), targetHeight );
this.lastAvailHeight = availHeight;
}
this.adjustViewerSize();
}
var bodyHeight = document.body.clientHeight;
var bodyWidth = document.body.clientWidth;
this.sidebar.onWindowResize(e);
$('layoutBody').style.marginLeft = this.sidebar.getWidth() + 10;
browser.setWidth(this.div, bodyWidth - this.sidebar.getWidth() - 10);
browser.setHeight(this.div, bodyHeight - browser.getAbsoluteTop(this.div));
extras.setStripeWidth(bodyWidth - this.sidebar.getWidth() - 40);
this.scroller.onResize();
if( this.annotationEnabled ) {
this.pages.each((function(page,pageNum) {
this.annotationManager.refreshAnnotationControls(pageNum);
}).bind(this));
}
}
Reader.prototype.onScroll = function(e) {
browser.setTop(this.annotationHolder, -1 * this.div.scrollTop);
browser.setLeft(this.annotationHolder, -1 * this.div.scrollLeft);
_a=0;
this.fireEvent('scroll');
}
Reader.prototype.onPageChange = function(eventName, page) {
var pageNum = page.getPageNum();
if (this.annotationManager.getBookmark(pageNum) == null) {
toolbar.setButtonEnabled("addBookmark", true);
toolbar.setButtonEnabled("bookmark",true);
toolbar.setButtonEnabled("removeBookmark", false);
}
else {
toolbar.setButtonEnabled("addBookmark", false);
toolbar.setButtonEnabled("bookmark",false);
toolbar.setButtonEnabled("removeBookmark", true);
}
}
Reader.prototype.displayHelpContents = function() {
Extras.helpPopUp(Config.getHelpURL());
}
Reader.prototype.displayReportAProblem = function() {
Extras.helpPopUp(Config.getReportAProblemURL());
}
Reader.prototype.bbFrameInit = function() {
if(history.length > 1 && !browser.saf) {
this.bbFrameContent();
window.setTimeout(this.bbFrameContent.bind(this), 20);
}
}
Reader.prototype.bbFrameContent = function() {
this.backButtonArmed = false;
var frm = $('backButtonFrame');
var frm_doc;
if(browser.ie) {
frm.onreadystatechange = this.bbHandler.bind(this);
frm_doc = frm.contentWindow.document;
} else if (!browser.saf) {
frm.onload = this.bbHandler.bind(this);
frm_doc = frm.contentDocument;
}
if(frm_doc) {
frm_doc.open();
frm_doc.write(' ');
frm_doc.close();
}
}
Reader.prototype.bbHandler = function(e) {
if(browser.ie && $('backButtonFrame').readyState != 'complete') return;
if(!this.backButtonArmed) {
this.backButtonArmed = true;
return;
} else if (!userSettings.get('showBackDialog')) {
history.go(-1);
return;
}
var text = 'Using the browser\'s "Back" button will take you out of the ' +
'Amazon Online Reader. Do you wish to leave this book?<br/><br/>' +
'<input type="checkbox" id="showBackDialogCheck"/>&nbsp;' +
'Do not show this message again';
var dialogOptions = {
message: text,
width: 300,
title: " Please note",
type: 'confirm',
okImg: 'digital/sitbv3/general/yes_button',
cancelImg: 'digital/sitbv3/general/no_button',
okAction: ( function() {
if( !$('showBackDialogCheck').checked ) {
history.go(-1);
} else {
userSettings.set('showBackDialog', false);
userSettings.save();
window.setTimeout("history.go(-1);", 300);
}
}),
cancelAction: ( (function() { this.bbFrameContent() }).bind(this) )
};
displayMessageDialog( dialogOptions );
}
AnnotationManager = function(reader, asin) {
Object.extend(this, new EventDispatcher());
this.reader = reader;
this.asin = asin;
this.annotationViewer = new AnnotationViewer( reader, this );
this.HIGHLIGHT = "highlight";
this.BOOKMARK = "bookmark";
this.PRIVATE = false;
this.PUBLIC = true;
this.isHighlightMode = false;
this.count = 0;
this.annotationsList = new AssociativeArray();
this.count = 0;
this.loadStatus = 'LOADING';
this.loadAnnotations();
this.annotationsReady = false;
this.privateAnnotationDisplayFilter = true;
this.defaultAnnotationScope = Annotation.PRIVATE;
this.popedUpAnnotation = new Object();
this.popedUpAnnotation.pageNum = undefined;
this.popedUpAnnotation.ID = undefined;
this.annotationDasIDs = new Object();
this.hasRealName = false;
this.verifyRealName( '', '', false );
}
Object.extend(AnnotationManager.prototype, SmartObject.prototype);
AnnotationManager.prototype.parent = SmartObject.prototype;
AnnotationManager.NEW_OFFSET_X = 20;
AnnotationManager.NEW_OFFSET_Y = 20;
AnnotationManager.OVERLAPPING_OFFSET = 5;
AnnotationManager.prototype.initEventListeners = function() {
toolbar.addListener('addBookmarkRequest', this, 'onAddBookmark');
toolbar.addListener('bookmarkRequest', this, 'onAddBookmark');
toolbar.addListener('addHighlightRequest', this, 'onAddHighlight');
toolbar.addListener('highlightRequest', this, 'onAddHighlight');
toolbar.addListener('annotationsOnPageRequest', this, 'onShowHideAnnotations');
toolbar.addListener('removeHighlightRequest', this, 'onRemoveHighlight');
toolbar.addListener('removeBookmarkRequest', this, 'onRemoveBookmark');
toolbar.addListener('extendHighlightRequest', this, 'onExtendHighlight');
toolbar.addListener('makeHighlightPublicPrivateRequest', this, 'onConvertAnnotation');
toolbar.addListener('makeBookmarkPublicPrivateRequest', this, 'onConvertAnnotation');
if (this.reader.isSelectionEnabled()) {
var selector = this.reader.selector;
selector.addListener('annotationSelection', this, 'onAnnotationSelection');
selector.addListener('annotationDeselection', this, 'onAnnotationDeselection');
selector.addListener('textSelection', this, 'onSelection')
}
this.reader.addListener('pageOnScreen', this, 'onPageDisplayed');
this.reader.pageManager.addListener('pageUnload', this, 'onPageUnload');
this.reader.addListener('pageOffScreen', this, 'onPageOffScreen');
this.reader.addListener('popUpAnnotation', this, 'onPopUpAnnotation');
}
AnnotationManager.prototype.destroy = function() {
this.annotationsList.each( (function(annotations,key) {
annotations.each( (function(annotation) {
annotation.destroy();
}).bind(this) );
}).bind(this) );
this.annotationViewer.destroy();
this.parent.destroy.call(this);
}
AnnotationManager.prototype.getDefaultAnnotationScope = function() {
return this.defaultAnnotationScope;
}
AnnotationManager.prototype.setDefaultAnnotationScope = function(scope) {
this.defaultAnnotationScope = scope;
}
AnnotationManager.prototype.updateAnnotationColor = function(color) {
this.reader.pages.each( (function(page, pageNum) {
var pageAnnotations = this.annotationsList.get(pageNum);
if( !pageAnnotations ) throw $continue;
pageAnnotations.each( (function(annotation) {
annotation.refresh();
}).bind(this) );
}).bind(this) );
}
AnnotationManager.prototype.onRemoveHighlight = function() {
try {
if(this.reader.selector.isSelected()) {
this.deleteBySelection();
} else {
var selected = this.reader.selector.getSelectedAnnotation();
if(selected && selected.type == Annotation.HIGHLIGHT && selected.isOwner) {
this.removeAnnotation(selected);
}
}
}
catch (e) { e.logError(); }
}
AnnotationManager.prototype.onRemoveBookmark = function() {
var annotations = this.annotationsList.get(this.reader.GetCurrentPage());
if( !annotations ) return;
annotations.each((function(annotation) {
if( annotation.type == Annotation.BOOKMARK && annotation.isOwner ) {
this.removeAnnotation(annotation);
}
}).bind(this) );
this.enableAddBookmark(true);
}
AnnotationManager.prototype.onExtendHighlight = function() {
this.extendBySelection();
}
AnnotationManager.prototype.onConvertAnnotation = function() {
if( !this.hasRealName ) {
this.verifyRealNameStart('convert');
return;
}
var selectedAnnotation = this.reader.selector.selectedAnnotation;
_a=0;
if( selectedAnnotation != null ) {
if (selectedAnnotation.scope == Annotation.PUBLIC) {
selectedAnnotation.setScope(Annotation.PRIVATE);
} else if (selectedAnnotation.scope == Annotation.PRIVATE) {
selectedAnnotation.setScope(Annotation.PUBLIC);
}
selectedAnnotation.save();
this.togglePublicPrivateButton(selectedAnnotation, true);
}
}
AnnotationManager.prototype.startHighlight = function() {
}
AnnotationManager.prototype.endHighlight = function() {
}
AnnotationManager.prototype.findOverlapedHighlights = function(highlight, overlapIDs) {
var highlightList = new Array();
var pagesToScan = [ highlight.getStartPage() ];
if (highlight.getEndPage() != highlight.getStartPage()) {
pagesToScan.push(highlight.getEndPage());
}
for (var page = 0; page < pagesToScan.length; page++) {
var pageAnnotations = this.annotationsList.get(pagesToScan[page]);
if( pageAnnotations != undefined ) {
pageAnnotations.each( (function(annotation) {
if( annotation != undefined &&
annotation.type == Annotation.HIGHLIGHT &&
annotation.isOwner &&
(highlight.overlap(annotation) & overlapIDs) != 0 &&
!highlightList.contains(annotation))
{
highlightList.push(annotation);
}
}).bind(this) );
}
}
return highlightList;
}
AnnotationManager.prototype.removeAnnotationRef = function(annotation) {
var pageAnnotations = this.annotationsList.get(annotation.getStartPage());
if( pageAnnotations ) {
pageAnnotations.remove( annotation.getID() );
}
if( annotation.getStartPage() != annotation.getEndPage()) {
pageAnnotations = this.annotationsList.get(annotation.getEndPage());
if( pageAnnotations ) {
pageAnnotations.remove( annotation.getID() );
}
}
}
AnnotationManager.prototype.addAnnotationRef = function(annotation) {
var startPage = annotation.getStartPage();
var endPage = annotation.getEndPage();
if( this.annotationsList.get(startPage) == undefined ) {
this.annotationsList.put(startPage, new AssociativeArray());
}
this.annotationsList.get(startPage).put( annotation.getID(), annotation );
if( startPage != endPage ) {
if( this.annotationsList.get(endPage) == undefined ) {
this.annotationsList.put(endPage, new AssociativeArray());
}
this.annotationsList.get(endPage).put( annotation.getID(), annotation );
}
}
AnnotationManager.prototype.addHighlight = function() {
if( !this.getPrivateAnnotationDisplayFilter() ) {
this.onShowHideAnnotations("onShowHideAnnotations", true, true);
}
try {
if( !this.hasRealName && this.defaultAnnotationScope == Annotation.PUBLIC )
{
this.verifyRealNameStart( 'highlight' );
return;
}
var selector = this.reader.selector;
var highlight = this.createHighlight(
selector.getStartPageNum(),
selector.getEndPageNum(),
selector.getStartWordID(),
selector.getEndWordID()
);
selector.clearTextSelection();
var overlapedHighlight = this.findOverlapedHighlights(
highlight,
Highlight.OVERLAPS | Highlight.CONTAINS | Highlight.STICKS
);
if( overlapedHighlight.length > 1 ) {
_a=0;
return;
}
if (overlapedHighlight.length == 0) {
var withinHighlight = this.findOverlapedHighlights(
highlight,
Highlight.WITHIN | Highlight.WITHIN_EDGE | Highlight.EQUALS
);
if (withinHighlight.length > 0)
return;
_a=0;
this.addAnnotation(highlight);
}
else {
_a=0;
var highlighToExtend = overlapedHighlight[0];
var reconstructRefs =
highlight.getStartPage() != highlighToExtend.getStartPage() ||
highlight.getEndPage() != highlighToExtend.getEndPage();
if (reconstructRefs)
this.removeAnnotationRef(highlighToExtend);
highlighToExtend.add(highlight);
if (reconstructRefs)
this.addAnnotationRef(highlighToExtend);
highlight.destroy();
highlight = highlighToExtend;
}
highlight.show();
selector.selectAnnotation(highlight);
highlight.save();
} catch (e) { e.logError(); }
}
AnnotationManager.prototype.getBookmark = function (pageNum) {
var bookmark = null;
var annotations = this.annotationsList.get(pageNum);
if( annotations != undefined) {
annotations.each( (function(annotation) {
if( annotation.getType() == Annotation.BOOKMARK &&
annotation.isOwner ) {
bookmark = annotation;
throw $break;
}
}).bind(this) );
}
return bookmark;
}
AnnotationManager.prototype.addBookmark = function( pageNum ) {
try {
if( !this.getPrivateAnnotationDisplayFilter() ) {
this.onShowHideAnnotations("onShowHideAnnotations", true, true);
}
if( !pageNum )
pageNum = this.reader.GetCurrentPage();
if( !this.hasRealName && this.defaultAnnotationScope == Annotation.PUBLIC )
{
this.pageNumToBookmark = pageNum;
this.verifyRealNameStart( 'bookmark' );
return;
}
if (this.getBookmark(pageNum) != null)
return;
var data = {
annotationId:   null,
startPage:      pageNum,
endPage:        pageNum,
startWord:      0,
endWord:        0,
scope:          this.getDefaultAnnotationScope(),
lastModified:   null,
notes:          "",
tags:           "",
isOwner:        1,
relatedContent: "",
deltaX:         0,
deltaY:         0,
open:           1
}
var bm = new Bookmark(this, data, true);
this.addAnnotation(bm);
bm.show();
bm.save();
var page = this.reader.getDisplayedPage(pageNum);
var bookmarkBottom = bm.getBottom() + page.getAbsoluteTop();
if( bookmarkBottom < this.reader.getViewerTop() ) {
this.reader.viewer.makeCurrentPageVisible();
}
this.enableAddBookmark(false);
this.pageNumToBookmark = null;
} catch (e) { e.logError(); }
}
AnnotationManager.prototype.getPageDiv = function(pageNum) {
_a=0;
_a=0;
_a=0;
_a=0;
return this.reader.pageManager.getPageObj(pageNum).getPageDiv();
}
AnnotationManager.prototype.onPopUpAnnotation = function(event, pageNum, ID) {
if( this.popedUpAnnotation.pageNum != undefined ) {
var annotation = this.getAnnotationByID( this.popedUpAnnotation.pageNum, this.popedUpAnnotation.ID );
if( !annotation.isOwner ) {
annotation.hide();
}
}
var annotation = this.getAnnotationByID( pageNum, ID );
if( !annotation ) {
_a=0;
return;
}
if( !this.getPrivateAnnotationDisplayFilter() ) {
this.onShowHideAnnotations("", true, true);
}
this.popedUpAnnotation.pageNum = pageNum;
this.popedUpAnnotation.ID = ID;
if( this.reader.pages.get(pageNum) ) {
this.displayAnnotation(annotation);
this.reader.selector.selectAnnotation(annotation);
}
}
AnnotationManager.prototype.onAddHighlight = function() {
if( this.reader.selector.isSelected() ) {
this.addHighlight();
}
else {
if( !this.isHighlightMode ) {
this.isHighlightMode = true;
cursor.setCursor('highlight');
} else {
this.isHighlightMode = false;
cursor.unsetCursor('highlight');
}
}
}
AnnotationManager.prototype.enableAddBookmark = function(enabled) {
if (enabled) {
toolbar.setButtonEnabled("addBookmark", true);
toolbar.setButtonEnabled("bookmark",true);
toolbar.setButtonEnabled("removeBookmark", false);
}
else {
toolbar.setButtonEnabled("addBookmark", false);
toolbar.setButtonEnabled("bookmark",false);
toolbar.setButtonEnabled("removeBookmark", true);
}
}
AnnotationManager.prototype.onAddBookmark = function() {
this.addBookmark(this.pageNumToBookmark);
}
AnnotationManager.prototype.onPageDisplayed = function(event, pageObj) {
if( this.annotationsReady == true ) {
this.displayAnnotations(pageObj.getPageNum());
}
}
AnnotationManager.prototype.moveNotToOverlap = function(annotation) {
var overlapNote;
var pageNotes = this.annotationsList.get(annotation.getStartPage());
if( !pageNotes ) {
return;
}
do {
overlapNote = false;
pageNotes.each( (function(tempAnnotation) {
if( tempAnnotation.type == this.HIGHLIGHT && tempAnnotation.isOpen() &&
tempAnnotation.getDeltaX() - annotation.getDeltaX() &&
Math.abs(tempAnnotation.getDeltaX() - annotation.getDeltaX()) < AnnotationManager.OVERLAPPING_OFFSET &&
Math.abs(tempAnnotation.getDeltaY() - annotation.getDeltaY()) < AnnotationManager.OVERLAPPING_OFFSET) {
overlapNote = true;
throw $break;
}
}).bind(this) );
if( overlapNote ) {
annotation.setDeltaX( annotation.getDeltaX() + AnnotationManager.NEW_OFFSET_X );
annotation.setDeltaY( annotation.getDeltaY() + AnnotationManager.NEW_OFFSET_Y );
}
}
while( overlapNote );
}
AnnotationManager.prototype.onPageUnload = function(event, pageObj) {
var annotations = this.annotationsList.get(pageObj.getPageNum());
if( annotations == undefined )
return;
annotations.each( (function(annotation) {
annotation.clean();
}).bind(this) );
}
AnnotationManager.prototype.onPageOffScreen = function(event, pageObj) {
var pageNum = pageObj.getPageNum();
var pageAnnotations = this.annotationsList.get( pageNum );
if( pageAnnotations == undefined ) return;
pageAnnotations.each( (function(annotation) {
if( annotation.getStartPage() == annotation.getEndPage() ||
(annotation.getStartPage() == pageNum && !this.reader.pages.get(annotation.getEndPage())) ||
(annotation.getEndPage() == pageNum && !this.reader.pages.get(annotation.getStartPage())) )
annotation.hide();
}).bind(this) );
}
AnnotationManager.prototype.onAnnotationSelection = function(eventName, annotation) {
annotation.setFocus(true);
this.togglePublicPrivateButton(annotation, true);
}
AnnotationManager.prototype.onAnnotationDeselection = function(eventName, annotation) {
annotation.setFocus(false);
this.togglePublicPrivateButton(annotation, false);
}
AnnotationManager.prototype.togglePublicPrivateButton = function(annotation, selected) {
var enabled = selected && annotation && annotation.isOwner;
var text = "Make ";
var element;
if( annotation.type == Annotation.HIGHLIGHT ) {
toolbar.setButtonEnabled("makeHighlightPublicPrivate", enabled);
text += "Highlight ";
element = $('makeHighlightPublicPrivate_text');
} else if( annotation.type == Annotation.BOOKMARK ) {
toolbar.setButtonEnabled("makeBookmarkPublicPrivate", enabled);
text += "Bookmark ";
element = $('makeBookmarkPublicPrivate_text');
}
text += (annotation.getScope() == Annotation.PUBLIC) ? "Private" : "Public";
if( element ) {
element.innerHTML = text;
}
}
AnnotationManager.prototype.onShowHideAnnotations = function(eventName, isOverride, override) {
var status = !this.getPrivateAnnotationDisplayFilter();
if( isOverride  ) status = override;
this.setPrivateAnnotationDisplayFilter(status);
this.annotationsList.each((function(list,pageNum) {
if( this.reader.pages.get(pageNum) ) {
this.displayAnnotations(pageNum);
}
}).bind(this) );
}
AnnotationManager.prototype.setPrivateAnnotationDisplayFilter = function(f) {
_a=0;
this.privateAnnotationDisplayFilter = f;
$("annotationsOnPage_check").src = f?Toolbar.IMG_CHECK:Toolbar.IMG_SPACER;
}
AnnotationManager.prototype.getPrivateAnnotationDisplayFilter = function() {
return this.privateAnnotationDisplayFilter;
}
AnnotationManager.prototype.onSelection = function(selectionInfo) {
if( this.isHighlightMode ) {
this.addHighlight();
this.isHighlightMode = false;
cursor.unsetCursor('highlight');
}
}
AnnotationManager.prototype.addAnnotation = function(annotObj) {
try {
annotObj.setID(this.count++);
this.moveNotToOverlap(annotObj);
this.addAnnotationRef(annotObj);
this.fireEvent('annotationCreated', annotObj);
}
catch (e) { e.logError(); }
}
AnnotationManager.prototype.getAllAnnotations = function() {
var res = new Array();
var pages = this.annotationsList.indexes;
var dedup = new Object();
for( var i = 0; i < pages.length; i++ ) {
var pageAnnotations = this.annotationsList.get(pages[i]);
pageAnnotations.each( (function(annotation, ID) {
if( dedup[ID] ) throw $continue;
dedup[ID] = 1;
res.push( annotation );
}) );
}
return res;
}
AnnotationManager.prototype.getAnnotationByID = function(pageNum, ID) {
try {
if( this.annotationsList.get(pageNum) != undefined ) {
var annotation = this.annotationsList.get(pageNum).get(ID);
return annotation;
}
return undefined;
} catch (e) { e.logError(); }
}
AnnotationManager.prototype.removeAnnotation = function(annotation) {
if( !annotation.isOwner ) return false;
this.removeAnnotationRef(annotation);
annotation.remove();
annotation.clean();
annotation.destroy();
}
AnnotationManager.prototype.createHighlight = function(startPage, endPage, startWord, endWord) {
var data = {
annotationId:   null,
startPage:      startPage,
endPage:        endPage,
startWord:      startWord,
endWord:        endWord,
scope:          this.getDefaultAnnotationScope(),
lastModified:   null,
notes:          "",
tags:           "",
isOwner:        1,
relatedContent: "",
deltaX:         0,
deltaY:         0,
open:           1,
customerName:   ''
}
return new Highlight(this, data, true);
}
AnnotationManager.prototype.deleteBySelection = function() {
var startPage = this.reader.selector.getStartPageNum();
var startWord = this.reader.selector.getStartWordID();
var endPage   = this.reader.selector.getEndPageNum();
var endWord   = this.reader.selector.getEndWordID();
this.reader.selector.clearTextSelection();
var selection = this.createHighlight(startPage, endPage, startWord, endWord);
var annotationsToRemove = this.findOverlapedHighlights(selection, Highlight.CONTAINS | Highlight.EQUALS);
for (var i = 0; i < annotationsToRemove.length; i++)
this.removeAnnotation(annotationsToRemove[i]);
var highlightsToShrink = this.findOverlapedHighlights(selection, Highlight.OVERLAPS | Highlight.WITHIN_EDGE);
for (var i = 0; i < highlightsToShrink.length; i++) {
var highlight = highlightsToShrink[i];
var reconstructRefs = highlight.getStartPage() != highlight.getEndPage();
if (reconstructRefs)
this.removeAnnotationRef(highlight);
highlight.subtract(selection);
if (reconstructRefs)
this.addAnnotationRef(highlight);
highlightsToShrink[i].show();
}
}
AnnotationManager.prototype.displayAnnotations = function(pageNum) {
var i;
var annotations = this.annotationsList.get(pageNum)
if( annotations == undefined )
return;
annotations.each( (function(annotation) {
try {
if( this.getPrivateAnnotationDisplayFilter() ) {
if( this.popedUpAnnotation.pageNum != undefined &&
annotation.getID() == this.popedUpAnnotation.ID) {
annotation.show();
this.reader.selector.selectAnnotation(annotation);
}
else if( annotation.isOwner ) {
annotation.show();
}
} else if( annotation.isOwner ) {
annotation.hide();
}
} catch (e) { e.logError(); }
}).bind(this) );
}
AnnotationManager.prototype.displayAnnotation = function(annotation) {
annotation.show();
}
AnnotationManager.prototype.loadAnnotationsCallback = function(jsoncom) {
try {
_a=0;
if (jsoncom.isError()) {
_a=0;
this.loadStatus = 'ERROR';
}
else {
if( this.loadStatus == 'LOADING' )
this.loadStatus = 'LOADING_MORE';
else if( this.loadStatus == 'LOADING_MORE' )
this.loadStatus = 'LOADED';
var data = jsoncom.getData();
for (var i = 0; i < data.length; i++) {
if( this.annotationDasIDs[data[i].annotationId] ) {
continue;
}
this.annotationDasIDs[data[i].annotationId] = true;
var newAnnotation;
if( data[i].type == Annotation.HIGHLIGHT) {
newAnnotation = new Highlight( this, data[i], false );
}
else if( data[i].type == Annotation.BOOKMARK ) {
newAnnotation = new Bookmark( this, data[i], false );
}
else {
_a=0;
continue;
}
this.addAnnotation(newAnnotation);
}
this.annotationsReady = true;
this.reader.pages.each((function(page,pageNum) {
this.displayAnnotations(pageNum);
}).bind(this));
}
} catch (e) { e.logError(); }
}
AnnotationManager.prototype.loadAnnotations = function() {
this.loadStatus = 'LOADING';
_a=0;
var json = new JSONCom( browser );
json.setCallback( this.loadAnnotationsCallback.bind(this) );
json.setURL( Config.getServiceURL() );
json.setParams( { action: "getAnnotations", asin: this.asin, scope: Annotation.PUBLIC } );
json.sendRequest();
_a=0;
json = new JSONCom( browser );
json.setCallback( this.loadAnnotationsCallback.bind(this) );
json.setURL( Config.getServiceURL() );
json.setParams( { action: "getAnnotations", asin: this.asin, ownerOnly: 1 } );
json.sendRequest();
}
AnnotationManager.prototype.refreshTriangles = function() {
this.annotationsList.each((function(list,pageNum) {
if( !this.reader.pages.get(pageNum) ) throw $continue;
list.each( (function(annotation) {
if( annotation.bubble != undefined ) {
annotation.bubble.refreshTriangle();
}
}) );
}) );
}
AnnotationManager.prototype.getAnnotationByLocation = function(pageNum, x, y) {
var boxID = this.reader.pageManager.getBoxFromCoordinates( pageNum, x, y );
var annotations = this.annotationsList.get(pageNum);
if( !annotations ) return null;
var selected = null;
annotations.each((function(annotation,ID) {
if( annotation.type == Annotation.BOOKMARK &&
annotation.isClicked(x, y) ) {
selected = annotation;
throw $break;
} else if( annotation.type == Annotation.HIGHLIGHT &&
annotation.getIndicatorObj() != null &&
boxID ) {
var indicator = annotation.getIndicatorObj();
if( indicator.getVisibility() && indicator.includesBox(boxID, pageNum) ) {
selected = annotation;
throw $break;
}
}
}).bind(this) );
return selected;
}
AnnotationManager.prototype.verifyRealNameStart = function( type ) {
var dialogOptions = {
title:      'Public Annotations Require a Real Name <span style="vertical-align:super; font-size:9px">TM</span>',
titleHR:    true,
showClose:  true,
type:       'confirm',
okImg:      'digital/sitbv3/general/create_realname-md-pri',
message:    'Before you can create public annotations in this book you' +
' need to create a Real Name<span style="vertical-align:super; font-size:8px">TM</span>' +
' . A Real Name is a signiture that will accompany your' +
' annotations and other content you submit to Amazon.com.<br/><br/>' +
'If you do not wish to create your Real Name now, click "Cancel"' +
' below. You will be asked again to create your Real Name when ' +
' you create your first public annotation.',
okAction: this.verifyRealName.bind(this, type)
};
displayGenericDialog( dialogOptions );
}
AnnotationManager.prototype.verifyRealName = function( type, button, showPipeline ) {
_a=0;
extras.showLoader();
var params = { action: "camsPipeline", annoType: type };
var form = $('rcanNameSelectForm');
if( form != undefined )
{
for( var i = 0; i < form.length; i++ )
{
var element = form.elements[i];
params[element.name] = element.value;
}
if( button != undefined )
{
params[button + '.x'] = '1';
params[button + '.y'] = '1';
}
}
if( showPipeline != undefined )
{
params['showPipeline'] = showPipeline;
}
var json = new JSONCom( browser );
json.setCallback( this.verifyRealNameCallback.bind(this) );
json.setURL( Config.getServiceURL() );
json.setParams( params );
json.sendRequest();
}
AnnotationManager.prototype.verifyRealNameCallback = function( jsoncom ) {
_a=0;
extras.hideLoader();
try
{
if( jsoncom.isError() )
{
_a=0;
}
else
{
var data = jsoncom.getData();
var showPipeline = true;
if( data.showPipeline != undefined )
{
showPipeline = (data.showPipeline == 'true');
}
if( data.error != undefined && data.error.length > 0 )
{
_a=0;
}
else if( data.display != undefined && data.display.length > 0 )
{
if( showPipeline )
{
this.processRealNameHTML( data.display );
}
}
else if( data.annoType != undefined )
{
this.hasRealName = true;
hideDialog( 'realNamePipeline' );
$('realNamePipelineContent').innerHTML = '';
if( data.annoType == 'highlight' )
{
this.addHighlight( );
}
else if( data.annoType == 'bookmark' )
{
this.addBookmark( this.pageNumToBookmark );
}
else if( data.annoType == 'convert' )
{
this.onConvertAnnotation();
}
}
else {
this.hasRealName = true;
}
}
}
catch( e ) { e.logError(); }
}
AnnotationManager.prototype.processRealNameHTML = function( html ) {
_a=0;
$('realNamePipelineContent').innerHTML = html;
while( html.length > 0 )
{
var index = html.indexOf( '<script' );
if( index == 0 )
{
var endIndex = html.indexOf( '</script>' );
var script = html.substring( html.indexOf( '>' ) + 1, endIndex );
var s = document.createElement( 'script' );
s.type = 'text/javascript';
s.text = script;
$('realNamePipelineContent').appendChild( s );
index = endIndex + 9;
}
else if( index < 0 )
{
index = html.length;
}
html = html.substr( index );
}
displayDialog( 'realNamePipeline' );
reader.sidebar.resizeRealNamePipeline();
}
AnnotationManager.prototype.refreshAnnotationControls = function(pageNum) {
var annotations = this.annotationsList.get(pageNum);
if (annotations == undefined) return;
annotations.each((function(annotation, ID) {
try {
if( !annotation.hidden )
annotation.refresh();
} catch(e) {
if( !e.isType('PageNotDisplayed') ) throw $e;
}
}).bind(this));
}
function Toggle(id)
{
var image_open = Config.getGeneralMediaURL('nav/arrow_small2');
var image_close = Config.getGeneralMediaURL('nav/1arrow_small2');
if (id == 'expandall')
{
elements = document.getElementsByTagName('ul');
for (i = 0; i < elements.length; i++)
{
id = elements[i].id.substr(3);
if (id != '' && id != 'root')
{
elements[i].style.display = 'block';
image = document.getElementById("img_" + id);
if (image != null)
{
image.src = image_open;
}
}
}
}
else if (id == 'collapseall')
{
elements = document.getElementsByTagName('ul');
for (i = 0; i < elements.length; i++)
{
id = elements[i].id.substr(3);
if (id != '' && id != 'root')
{
elements[i].style.display = 'none';
image = document.getElementById("img_" + id);
if (image != null)
{
image.src = image_close;
}
}
}
}
else
{
element = document.getElementById("ul_" + id);
style   = element.style;
image   = document.getElementById("img_" + id);
if (style.display == 'none')
{
style.display = 'block';
image.src = image_open;
}
else
{
style.display = 'none';
image.src = image_close;
}
}
}
Toolbar = function() {
Object.extend( this, new EventDispatcher() );
this.toolEnabled = new Object();
this.toolEnabled["singlePage"] = false;
this.toolEnabled["continuous"] = false;
this.toolEnabled["zoomIn"] = false;
this.toolEnabled["zoomOut"] = false;
this.toolEnabled["annotationsOnPage"] = false;
this.toolEnabled["leftColumn"] = false;
this.toolEnabled["viewSettings"] = false;
this.toolEnabled["addHighlight"] = false;
this.toolEnabled["highlight"] = false;
this.toolEnabled["removeHighlight"] = false;
this.toolEnabled["highlightSettings"] = false;
this.toolEnabled["bookmark"] = false;
this.toolEnabled["addBookmark"] = false;
this.toolEnabled["removeBookmark"] = false;
this.toolEnabled["makeHighlightPublicPrivate"] = false;
this.toolEnabled["makeBookmarkPublicPrivate"] = false;
this.toolEnabled["bookmarkSettings"] = false;
this.toolEnabled["copy"] = false;
this.toolEnabled["print"] = false;
this.toolEnabled["contents"] = false;
this.toolEnabled["reportAProblem"] = false;
this.showTooltipOn = new Object();
this.showTooltipOn["highlight"] = Config.getCurrentMode() != 'SITBpaid';
this.showTooltipOn["bookmark"] = Config.getCurrentMode() != 'SITBpaid';
this.showTooltipOn["copy"] = Config.getCurrentMode() != 'SITBpaid';
this.showTooltipOn["print"] = Config.getCurrentMode() != 'SITBpaid';
this.onMouseOverCallback = this.onMouseOver.bind(this);
this.onMouseMoveCallback = this.onMouseMove.bind(this);
this.onMouseOutCallback = this.onMouseOut.bind(this);
this.toolMap = new Object();
Event.observe(window, 'load', this.initialize.bind(this));
}
Object.extend(Toolbar.prototype, SmartObject.prototype);
Toolbar.IMG_SPACER = Config.getGeneralMediaURL('misc/transparent-pixel');
Toolbar.IMG_CHECK = Config.getGeneralMediaURL('digital/sitbv3/general/check_icon');
Toolbar.IMG_ENABLED =
{
view:           Config.getGeneralMediaURL('digital/sitbv3/toolbar/view_button'),
singlePage:      Config.getGeneralMediaURL('digital/sitbv3/general/1up_icon'),
continuous:      Config.getGeneralMediaURL('digital/sitbv3/general/continuous_icon'),
zoomIn:          Config.getGeneralMediaURL('digital/sitbv3/general/zoom_in_icon'),
zoomOut:         Config.getGeneralMediaURL('digital/sitbv3/general/zoom_out_icon'),
highlight:       Config.getGeneralMediaURL('digital/sitbv3/toolbar/highlight_enabled_button'),
addHighlight:    Config.getGeneralMediaURL('digital/sitbv3/general/highlight_enabled_icon'),
removeHighlight: Config.getGeneralMediaURL('digital/sitbv3/general/highlight_remove_icon'),
bookmark:        Config.getGeneralMediaURL('digital/sitbv3/toolbar/bookmark_enabled_button'),
addBookmark:     Config.getGeneralMediaURL('digital/sitbv3/general/bookmark_enabled_icon'),
removeBookmark:  Config.getGeneralMediaURL('digital/sitbv3/general/bookmark_remove_icon'),
copy:            Config.getGeneralMediaURL('digital/sitbv3/toolbar/copy_enabled_button'),
print:           Config.getGeneralMediaURL('digital/sitbv3/toolbar/print_enabled_button'),
help:            Config.getGeneralMediaURL('digital/sitbv3/toolbar/help_button'),
contents:        Config.getGeneralMediaURL('digital/sitbv3/general/question_mark_icon')
};
Toolbar.IMG_DISABLED =
{
singlePage:      Config.getGeneralMediaURL('digital/sitbv3/general/1up_icon'),
continuous:      Config.getGeneralMediaURL('digital/sitbv3/general/continuous_icon'),
zoomIn:          Config.getGeneralMediaURL('digital/sitbv3/general/zoom_in_icon'),
zoomOut:         Config.getGeneralMediaURL('digital/sitbv3/general/zoom_out_icon'),
highlight:       Config.getGeneralMediaURL('digital/sitbv3/toolbar/highlight_disabled_button'),
addHighlight:    Config.getGeneralMediaURL('digital/sitbv3/general/highlight_disabled_icon'),
removeHighlight: Config.getGeneralMediaURL('digital/sitbv3/general/highlight_remove_icon'),
bookmark:        Config.getGeneralMediaURL('digital/sitbv3/toolbar/bookmark_disabled_button'),
addBookmark:     Config.getGeneralMediaURL('digital/sitbv3/general/bookmark_disabled_icon'),
removeBookmark:  Config.getGeneralMediaURL('digital/sitbv3/general/bookmark_remove_icon'),
copy:            Config.getGeneralMediaURL('digital/sitbv3/toolbar/copy_disabled_button'),
print:           Config.getGeneralMediaURL('digital/sitbv3/toolbar/print_disabled_button'),
contents:        Config.getGeneralMediaURL('digital/sitbv3/general/question_mark_icon')
};
Toolbar.SHOW_TOOLTIP_DELAY=500;
Toolbar.HIDE_TOOLTIP_DELAY=3000;
Toolbar.TOOLTIP_OFFSET=20;
Toolbar.prototype.initialize = function() {
_a=0;
Event.observe($('toolbarMenu'), 'click', this.onToolbarClick.bind(this));
Event.observe($('toolbarMenu'), 'mousedown', this.onMouseDown.bind(this));
Event.observe(document, 'click', this.onOutsideToolbarClick.bind(this));
Event.observe($('layoutBody'), 'scroll', this.onOutsideToolbarClick.bind(this));
Event.observe($('tabbedContentTOC'), 'scroll', this.onOutsideToolbarClick.bind(this));
Event.observe($('tabbedContentAnnotations'), 'scroll', this.onOutsideToolbarClick.bind(this));
var readerPerms = Config.getReaderPermissions();
if( readerPerms.jump_page ) {
Event.observe($('page_form'), 'submit', this.onPageSubmit.bind(this) );
$('page').disabled = false;
}
this.setButtonEnabled("singlePage", readerPerms["toolbar_view_singlePage"] == 1);
this.setButtonEnabled("continuous", readerPerms["toolbar_view_continuous"] == 1);
this.setButtonEnabled("zoomIn",readerPerms["toolbar_view_zoomIn"] == 1);
this.setButtonEnabled("zoomOut",readerPerms["toolbar_view_zoomOut"] == 1);
this.setButtonEnabled("annotationsOnPage",readerPerms["toolbar_view_annotationsOnPage"] == 1);
this.setButtonEnabled("leftColumn",readerPerms["toolbar_view_leftColumn"] == 1);
this.setButtonEnabled("viewSettings",readerPerms["toolbar_settings"] == 1);
this.setButtonEnabled("addHighlight",readerPerms["toolbar_highlight_add"] == 1);
this.setButtonEnabled("highlight",readerPerms["toolbar_highlight_add"] == 1);
this.setButtonEnabled("removeHighlight",readerPerms["toolbar_highlight_remove"] == 1);
this.setButtonEnabled("highlightSettings",readerPerms["toolbar_settings"] == 1);
this.setButtonEnabled("addBookmark",readerPerms["toolbar_bookmark_add"] == 1);
this.setButtonEnabled("bookmark",readerPerms["toolbar_bookmark_add"] == 1);
this.setButtonEnabled("removeBookmark",readerPerms["toolbar_bookmark_remove"] == 1);
this.setButtonEnabled("bookmarkSettings",readerPerms["toolbar_settings"] == 1);
this.setButtonEnabled("copy",readerPerms["toolbar_copy"] == 1);
this.setButtonEnabled("print",readerPerms["toolbar_print"] == 1);
this.setButtonEnabled("contents",readerPerms["toolbar_help_contents"] == 1);
this.setButtonEnabled("reportAProblem",readerPerms["toolbar_help_reportAProblem"] == 1);
this.setButtonEnabled("makeHighlightPublicPrivate", false);
this.setButtonEnabled("makeBookmarkPublicPrivate", false);
this.initButtonHover();
}
Toolbar.prototype.initButtonHover = function()
{
this.viewButtonLeft      = $('toolbar_view_buttonLeft');
this.viewButton          = $('toolbar_view_button');
this.viewButtonRight     = $('toolbar_view_buttonRight');
this.highlightButtonLeft = $('toolbar_highlight_buttonLeft');
this.highlightButton     = $('toolbar_highlight_button');
this.highlightDropDown   = $('toolbar_highlight_dropdown');
this.bookmarkButtonLeft  = $('toolbar_bookmark_buttonLeft');
this.bookmarkButton      = $('toolbar_bookmark_button');
this.bookmarkDropDown    = $('toolbar_bookmark_dropdown');
this.copyButtonLeft      = $('toolbar_copy_buttonLeft');
this.copyButton          = $('toolbar_copy_button');
this.copyButtonRight     = $('toolbar_copy_buttonRight');
this.printButtonLeft     = $('toolbar_print_buttonLeft');
this.printButton         = $('toolbar_print_button');
this.printButtonRight    = $('toolbar_print_buttonRight');
this.helpButtonLeft      = $('toolbar_help_buttonLeft');
this.helpButton          = $('toolbar_help_button');
this.helpButtonRight     = $('toolbar_help_buttonRight');
Event.observe( this.viewButtonLeft, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.viewButtonLeft, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.viewButton, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.viewButton, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.viewButtonRight, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.viewButtonRight, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.highlightButtonLeft, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.highlightButtonLeft, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.highlightButton, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.highlightButton, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.highlightDropDown, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.highlightDropDown, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.bookmarkButtonLeft, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.bookmarkButtonLeft, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.bookmarkButton, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.bookmarkButton, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.bookmarkDropDown, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.bookmarkDropDown, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.copyButtonLeft, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.copyButtonLeft, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.copyButton, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.copyButton, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.copyButtonRight, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.copyButtonRight, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.printButtonLeft, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.printButtonLeft, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.printButton, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.printButton, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.printButtonRight, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.printButtonRight, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.helpButtonLeft, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.helpButtonLeft, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.helpButton, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.helpButton, "mouseout", this.menuMouseOut.bind(this) );
Event.observe( this.helpButtonRight, "mouseover", this.menuMouseOver.bind(this) );
Event.observe( this.helpButtonRight, "mouseout", this.menuMouseOut.bind(this) );
}
Toolbar.prototype.refreshButton = function(name, enabled) {
if( this.toolMap[name] ) {
this.toolMap[name].each(function(item) {
$(item + "_button").className = enabled?"enabledButton":"disabledButton";
});
} else {
var icon = $(name + "_button_icon");
if( enabled )
{
$(name + "_button").className = "enabledButton";
if( icon ) $(name + "_button_icon").src = Toolbar.IMG_ENABLED[name];
}
else
{
$(name + "_button").className = "disabledButton";
if( icon ) $(name + "_button_icon").src = Toolbar.IMG_DISABLED[name];
}
}
if ( this.showTooltipOn[ name ] ) {
if ( !enabled ) {
Event.observe($(name + "_button"), "mouseover", this.onMouseOverCallback);
Event.observe($(name + "_button"), "mousemove", this.onMouseMoveCallback);
Event.observe($(name + "_button"), "mouseout", this.onMouseOutCallback);
}
else {
Event.stopObserving($(name + "_button"), "mouseover", this.onMouseOverCallback);
Event.stopObserving($(name + "_button"), "mousemove", this.onMouseMoveCallback);
Event.stopObserving($(name + "_button"), "mouseout", this.onMouseOutCallback);
}
}
}
Toolbar.prototype.menuMouseOver = function( event ) {
var obj = Event.element(event);
if( obj.id.match( 'view' ) )
{
this.viewButtonLeft.className = 'buttonEndCapLeftHover';
this.viewButton.className = 'buttonHover';
this.viewButtonRight.className = 'buttonEndCapRightHover';
}
else if( obj.id.match( 'highlight' ) )
{
this.highlightButtonLeft.className = 'buttonEndCapLeftHover';
this.highlightButton.className = 'buttonHover';
this.highlightDropDown.className = 'buttonDropDownRightHover';
}
else if( obj.id.match( 'bookmark' ) )
{
this.bookmarkButtonLeft.className = 'buttonEndCapLeftHover';
this.bookmarkButton.className = 'buttonHover';
this.bookmarkDropDown.className = 'buttonDropDownRightHover';
}
else if( obj.id.match( 'copy' ) )
{
this.copyButtonLeft.className = 'buttonEndCapLeftHover';
this.copyButton.className = 'buttonHover';
this.copyButtonRight.className = 'buttonEndCapRightHover';
}
else if( obj.id.match( 'print' ) )
{
this.printButtonLeft.className = 'buttonEndCapLeftHover';
this.printButton.className = 'buttonHover';
this.printButtonRight.className = 'buttonEndCapRightHover';
}
else if( obj.id.match( 'help' ) )
{
this.helpButtonLeft.className = 'buttonEndCapLeftHover';
this.helpButton.className = 'buttonHover';
this.helpButtonRight.className = 'buttonEndCapRightHover';
}
}
Toolbar.prototype.menuMouseOut = function( event ) {
var obj = Event.element(event);
if( !obj.id ) return;
if( obj.id.match( 'view' ) )
{
this.viewButtonLeft.className = 'buttonEndCapLeft';
this.viewButton.className = 'button';
this.viewButtonRight.className = 'buttonEndCapRight';
}
else if( obj.id.match( 'highlight' ) )
{
this.highlightButtonLeft.className = 'buttonEndCapLeft';
this.highlightButton.className = 'button';
this.highlightDropDown.className = 'buttonDropDownRight';
}
else if( obj.id.match( 'bookmark' ) )
{
this.bookmarkButtonLeft.className = 'buttonEndCapLeft';
this.bookmarkButton.className = 'button';
this.bookmarkDropDown.className = 'buttonDropDownRight';
}
else if( obj.id.match( 'copy' ) )
{
this.copyButtonLeft.className = 'buttonEndCapLeft';
this.copyButton.className = 'button';
this.copyButtonRight.className = 'buttonEndCapRight';
}
else if( obj.id.match( 'print' ) )
{
this.printButtonLeft.className = 'buttonEndCapLeft';
this.printButton.className = 'button';
this.printButtonRight.className = 'buttonEndCapRight';
}
else if( obj.id.match( 'help' ) )
{
this.helpButtonLeft.className = 'buttonEndCapLeft';
this.helpButton.className = 'button';
this.helpButtonRight.className = 'buttonEndCapRight';
}
}
Toolbar.prototype.setButtonEnabled = function(name, enabled) {
this.toolEnabled[name] = enabled;
this.refreshButton(name, enabled);
}
Toolbar.prototype.onOutsideToolbarClick = function(event) {
var obj = Event.element(event);
if( (obj.nodeName == 'SPAN' || obj.nodeName == 'IMG')
&& obj.parentNode && (obj.parentNode.nodeName == 'A') )
{
obj = obj.parentNode;
}
if( obj.id.match("_button") || obj.id.match("_menu") || obj.id.match("_dropdown") ){
return;
}
this.displayDropdown();
}
Toolbar.prototype.onMouseDown = function(event) {
Event.stopBubble(event);
}
Toolbar.prototype.onToolbarClick = function(event) {
Event.stopBubble(event);
var obj = Event.element(event);
if (obj.nodeType == 3) {
obj = obj.parentNode;
}
if( (obj.nodeName == 'SPAN' || obj.nodeName == 'IMG')
&& obj.parentNode && (obj.parentNode.nodeName == 'A') )
{
obj = obj.parentNode;
}
if( obj.name == "" || (obj.id.match("_button") == null && obj.id.match("_menu") == null)) {
return;
}
if ( obj.id.match("_button") && this.toolEnabled[obj.name] != true) {
return;
}
if (obj.id.match("_menu")) {
if (this.isDropdownDisplayed(obj.name)) {
this.displayDropdown();
}
else {
this.displayDropdown(obj.name);
}
}
else {
var action = obj.name + "Request";
_a=0;
this.fireEvent(action, status);
this.displayDropdown();
}
}
Toolbar.prototype.onPageChange = function(eventName, page) {
var pageNum = page.getLogicalPage() ? page.getLogicalPage() : page.getPageNum();
$('page').value = pageNum;
}
Toolbar.prototype.onPageSubmit = function() {
var logicalPage = $('page').value;
var pageNum = reader.pageManager.getPhysicalPageNumber(logicalPage);
if( pageNum != -1 ) {
reader.DisplayPage(pageNum,undefined,true);
}
}
Toolbar.prototype.isDropdownDisplayed = function(name) {
return document.getElementById(name + "_dropdown").style.display == "block";
}
Toolbar.prototype.displayDropdown = function(name) {
var dropdowns = new Array();
dropdowns.push("view_dropdown");
dropdowns.push("highlight_dropdown");
dropdowns.push("bookmark_dropdown");
dropdowns.push("help_dropdown");
for (var i = 0; i < dropdowns.length; i++) {
if (name != undefined && (name + "_dropdown") == dropdowns[i] ) {
document.getElementById(dropdowns[i]).style.display = "block";
}
else {
document.getElementById(dropdowns[i]).style.display = "none";
}
}
}
Toolbar.prototype.createTooltip = function() {
this.tooltip = $('tooltip');
var tooltipContent = $('tooltipContent');
tooltipContent.innerHTML =
'This feature is only available with Amazon Upgrade. '
+ '<a href="' + Config.getHelpTooltipLink() + '">Learn more</a>';
if( !Config.isInSITBPaid() ) {
tooltipContent.innerHTML += '<br>This book is not in the Amazon Upgrade program.';
}
Event.observe(this.tooltip, "mouseover", this.clearHideTimer.bind(this));
Event.observe(this.tooltip, "mouseout", this.delayedHideTooltip.bind(this));
}
Toolbar.prototype.onMouseMove = function(event) {
try {
this.mouseX = event.clientX;
this.mouseY = event.clientY;
}
catch (e) { e.logError(); }
}
Toolbar.prototype.onMouseOver = function(event) {
try {
this.delayedShowTooltip();
}
catch (e) { e.logError(); }
}
Toolbar.prototype.onMouseOut = function(event) {
try {
this.delayedHideTooltip();
}
catch (e) { e.logError(); }
}
Toolbar.prototype.delayedShowTooltip = function() {
if (this.hideTimer) {
clearTimeout(this.hideTimer);
this.hideTimer = undefined;
}
if (this.showTimer == undefined) {
this.showTimer = setTimeout(this.showTooltip.bind(this), Toolbar.SHOW_TOOLTIP_DELAY);
}
}
Toolbar.prototype.delayedHideTooltip = function() {
if (this.showTimer) {
clearTimeout(this.showTimer);
this.showTimer = undefined;
}
if (this.hideTimer == undefined) {
this.hideTimer = setTimeout(this.hideTooltip.bind(this), Toolbar.HIDE_TOOLTIP_DELAY);
}
}
Toolbar.prototype.hideTooltip = function() {
if( this.tooltip )
this.tooltip.style.display = 'none';
this.hideTimer = undefined;
}
Toolbar.prototype.showTooltip = function() {
if (this.tooltip == undefined)
this.createTooltip();
this.showTimer = undefined;
this.tooltip.style.display = 'block';
browser.setLeft(this.tooltip, this.mouseX + Toolbar.TOOLTIP_OFFSET);
browser.setTop(this.tooltip, this.mouseY + Toolbar.TOOLTIP_OFFSET);
}
Toolbar.prototype.clearHideTimer = function() {
if (this.hideTimer) {
clearTimeout(this.hideTimer);
this.hideTimer = undefined;
}
}
var toolbar = new Toolbar();
Selector = function(reader_div, reader) {
this.baseDiv = $(reader_div);
this.reader = reader;
this.textSelected = false;
this.selectingText = false;
this.startPageNum = null;
this.startWordID = null;
this.endPageNum = null;
this.endWordID = null;
this.anchorPageNum = null;
this.anchorWordID = null;
this.selectedAnnotation = null;
this.currentX = 0;
this.currentY = 0;
this.currentPage = null;
this.lastClientX = 0;
this.lastClientY = 0;
this.selectionVisible = false;
this.mouseMoveCallback = this.dragSelection.bind(this);
Object.extend(this, new EventDispatcher());
Event.observe(this.baseDiv, 'mousedown', this.startSelection.bind(this), false);
Event.observe(this.baseDiv, 'mouseup', this.endSelection.bind(this), false);
Event.observe(this.baseDiv, 'mouseup', this.onClick.bind(this), false);
this.reader.pageManager.addListener('pageLoad', this, 'onPageLoad');
this.reader.pageManager.addListener('pageUnload', this, 'onPageUnload');
}
Object.extend(Selector.prototype, SmartObject.prototype);
Selector.prototype.getSelectedAnnotation = function() {
return this.selectedAnnotation;
}
Selector.prototype.isSelected = function() {
return this.textSelected;
}
Selector.prototype.getStartPageNum = function() {
return this.startPageNum;
}
Selector.prototype.getStartWordID = function() {
return this.startWordID;
}
Selector.prototype.getEndPageNum = function() {
return this.endPageNum;
}
Selector.prototype.getEndWordID = function() {
return this.endWordID;
}
Selector.prototype.clearTextSelection = function() {
if( this.indicator != null ) {
try {
this.indicator.destroy();
} catch( e ) { e.logError(); }
}
this.startWordID = null;
this.endWordID = null;
this.startPageNum = null;
this.endPageNum = null;
this.anchorPageNum = null;
this.anchorWordID = null;
this.indicator = null;
this.selectingText = false;
this.textSelected = false;
this.selectionVisible = false;
}
Selector.prototype.clearAnnotationSelection = function() {
if( !this.selectedAnnotation ) return;
this.fireEvent( 'annotationDeselection', this.selectedAnnotation );
this.selectedAnnotation = null;
}
Selector.prototype.selectAnnotation = function(annotation) {
if( annotation == this.selectedAnnotation )
return;
if( this.selectedAnnotation )
this.fireEvent( 'annotationDeselection', this.selectedAnnotation );
this.selectedAnnotation = annotation;
this.fireEvent( 'annotationSelection', annotation );
}
Selector.prototype.deselectAnnotation = function(annotation) {
if( annotation != this.selectedAnnotation )
return;
this.fireEvent( 'annotationDeselection', annotation );
this.selectedAnnotation = null;
}
Selector.prototype.startSelection = function(event) {
if( this.selectingText ) return false;
this.lastClientX = event.clientX;
this.lastClientY = event.clientY;
var locationInfo = this.reader.getRelativePageLocation(event.clientX, event.clientY);
this.currentX = locationInfo.get('pageX');
this.currentY = locationInfo.get('pageY');
if (this.currentX == undefined || this.currentX > (browser.getWidth(this.baseDiv) - 15)) return true;
var page = locationInfo.get('page');
if (page) {
this.clearTextSelection();
this.selectingText = true;
}
Event.observe(this.baseDiv, 'mousemove', this.mouseMoveCallback, false);
return false;
}
Selector.prototype.dragSelection = function(event) {
if( !this.selectingText ) return;
if( Math.abs(event.clientX - this.lastClientX) < 5 &&
Math.abs(event.clientY - this.lastClientY) < 5 )
return;
var locationInfo = this.reader.getRelativePageLocation(event.clientX, event.clientY);
var pageX = locationInfo.get('pageX');
var pageY = locationInfo.get('pageY');
var page = locationInfo.get('page');
if( page == null ) return;
var readerX = this.lastClientX - this.reader.getAbsoluteLeft();
var readerY = this.lastClientY - this.reader.getAbsoluteTop();
var lastPageX = readerX - page.getAbsoluteLeft();
var lastPageY = readerY - page.getAbsoluteTop();
this.extendSelection(page, lastPageX, lastPageY, pageX, pageY);
this.lastClientX = event.clientX;
this.lastClientY = event.clientY;
this.currentX = pageX;
this.currentY = pageY;
return false;
}
Selector.prototype.endSelection = function(event) {
if( !this.selectingText ) return false;
this.selectingText = false;
if( this.startWordID != null && this.endWordID != null )
{
_a=0;
this.selectionVisible = true;
this.textSelected = true;
var eventData = {
startPageNum: this.startPageNum,
startWordID: this.startWordID,
endPageNum: this.endPageNum,
endWordID: this.endWordID
};
this.fireEvent('textSelection', eventData);
}
else {
this.textSelected = false;
this.selectionVisible = false;
}
Event.stopObserving(this.baseDiv, 'mousemove', this.mouseMoveCallback, false);
}
Selector.prototype.onClick = function(event) {
try {
var pageInfo = this.reader.getRelativePageLocation(event.clientX, event.clientY);
var pageNum = null;
var page = pageInfo.get('page');
var pageX = pageInfo.get('pageX');
var pageY = pageInfo.get('pageY');
if( page )
pageNum = pageInfo.get('page').getPageNum();
else
return;
annotation = this.reader.annotationManager.getAnnotationByLocation(
pageNum, pageX, pageY );
if( annotation ) {
this.selectAnnotation(annotation);
} else {
if( pageX > page.getWidth() - Bookmark.CORNER_SIZE && pageY < Bookmark.CORNER_SIZE ) {
this.reader.annotationManager.addBookmark( pageNum );
}
}
} catch(e) {
e.logError();
}
}
Selector.prototype.onPageLoad = function(event, page) {
if( this.textSelected && !this.selectionVisible &&
this.startPageNum <= page.getPageNum() &&
this.endPageNum >= page.getPageNum() )
{
this.selectionVisible = true;
this.indicator = new Indicator( this.reader, Indicator.SELECTION,
this.startPageNum, this.startWordID );
this.indicator.setEnd( this.endPageNum, this.endWordID );
_a=0;
}
}
Selector.prototype.onPageUnload = function(event, page) {
if( this.textSelected  && this.selectionVisible &&
this.startPageNum <= page.getPageNum() &&
this.endPageNum >= page.getPageNum() )
{
this.selectionVisible = false;
this.indicator.destroy();
this.indicator = null;
_a=0;
}
if( this.selectedAnnotation &&
this.selectedAnnotation.getStartPage() == page.getPageNum() ) {
this.selectedAnnotation = null;
}
}
Selector.prototype.extendSelection = function( page, startX, startY, endX, endY ) {
var pageRows = page.rows;
if( pageRows == null ) {
this.endSelection();
_a=0;
return;
}
var boxesSelected = this.reader.pageManager.getBoxesForRange(page.getPageNum(),
startX, startY, endX, endY );
if( boxesSelected.length == 0 ) {
return;
}
var pageNum = page.getPageNum();
var newStartWordID = boxesSelected[0];
var newEndWordID = boxesSelected[boxesSelected.length-1];
if( this.startPageNum != this.endPageNum &&
this.endPageNum != pageNum && this.startPageNum != pageNum )
{
return;
}
if( this.anchorPageNum == null ) {
this.anchorPageNum = pageNum;
try {
this.anchorWordID = newStartWordID;
this.indicator = new Indicator( this.reader, Indicator.SELECTION,
this.anchorPageNum, this.anchorWordID );
} catch( e ) {
e.logError();
}
}
if( newStartWordID > newEndWordID ) {
var temp = newEndWordID;
newEndWordID = newStartWordID;
newStartWordID = temp;
}
var forward = pageNum > this.anchorPageNum ||
(pageNum == this.anchorPageNum && newStartWordID >= this.anchorWordID);
if( forward ) {
this.startPageNum = this.anchorPageNum;
this.startWordID = this.anchorWordID;
this.endPageNum = pageNum;
this.endWordID = newEndWordID;
}
else {
this.startPageNum = pageNum;
this.startWordID = newStartWordID;
this.endPageNum = this.anchorPageNum;
this.endWordID = this.anchorWordID;
}
this.indicator.setStart( this.startPageNum, this.startWordID );
this.indicator.setEnd( this.endPageNum, this.endWordID );
}
Annotation = function (annotationManager, type, data, isNew) {
try {
if (annotationManager == undefined)
return;
Object.extend(this, new SmartObject());
this.numsave = 0;
this.HIGHLIGHT = Annotation.HIGHLIGHT;
this.BOOKMARK  = Annotation.BOOKMARK;
this.PRIVATE = Annotation.PRIVATE;
this.PUBLIC = Annotation.PUBLIC;
this.annotationManager = annotationManager;
this.type = type;
this.dasID = data.annotationId;
this.scope = (data.scope) ? Annotation.PUBLIC : Annotation.PRIVATE;
this.lastModified = data.timestamp;
this.notes = data.notes;
this.tags = data.tags;
this.deltaY = data.deltaY;
this.deltaX = data.deltaX;
this.width = data.width;
this.open = data.open;
this.isOwner = data.isOwner;
this.relatedContent = data.relatedContent;
this.customerName = data.customerName;
if (data.customerName) {
var badgeIndex = data.customerName.search( /<br/ );
if( badgeIndex > -1 ) {
this.customerNameNoBadge = data.customerName.substring( 0, badgeIndex );
} else {
this.customerNameNoBadge = data.customerName;
}
}
else {
this.customerNameNoBadge = "";
}
if (data.startPage == data.endPage) {
this.startPage = this.endPage = data.startPage;
this.startWord = Math.min(data.startWord, data.endWord);
this.endWord = Math.max(data.startWord, data.endWord);
} else if (data.startPage > data.endPage) {
this.startPage = data.endPage;
this.endPage = data.startPage;
this.startWord = data.endWord;
this.endWord = data.startWord;
}
else {
this.startPage = data.startPage;
this.endPage = data.endPage;
this.startWord = data.startWord;
this.endWord = data.endWord;
}
this.hidden = true;
this.bubble = undefined;
this.dirty = isNew;
this.isNew = isNew;
this.uniqueID = Annotation.NEXT_ID;
this.attachedPage = null;
Annotation.NEXT_ID++;
} catch (e) { e.logError(); }
}
Annotation.HIGHLIGHT = "highlight";
Annotation.BOOKMARK = "bookmark";
Annotation.PRIVATE = 0;
Annotation.PUBLIC = 1;
Annotation.NEXT_ID = 1;
Annotation.prototype.autoSave = function() {
this.save();
tagManager.save();
this.saveTimer = setTimeout( this.autoSave.bind(this), 10000 );
}
Annotation.prototype.clean = function() {
if( this.bubble ) {
this.bubble.destroy();
this.bubble = undefined;
}
}
Annotation.prototype.getType = function() {
return this.type;
}
Annotation.prototype.getID = function() {
return this.uniqueID;
}
Annotation.prototype.getDasID = function() {
return this.dasID;
}
Annotation.prototype.getStartPage = function() {
return this.startPage;
}
Annotation.prototype.getEndPage = function() {
return this.endPage;
}
Annotation.prototype.getStartWord = function() {
return this.startWord;
}
Annotation.prototype.getEndWord = function() {
return this.endWord;
}
Annotation.prototype.getAttachedPage = function() {
return this.attachedPage;
}
Annotation.prototype.pickAttachedPage = function() {
var pages = [ this.getStartPage() ];
if( this.getStartPage() != this.getEndPage() ) {
pages.push( this.getEndPage() );
}
pages.each( (function(page) {
if( reader.pages.get(page) ) {
_a=0;
this.attachedPage = page;
throw $break;
}
}).bind(this) );
}
Annotation.prototype.getScope = function() {
return this.scope;
}
Annotation.prototype.getRelatedContent = function() {
return this.relatedContent;
}
Annotation.prototype.getDeltaY = function() {
return this.deltaY;
}
Annotation.prototype.getDeltaX = function() {
return this.deltaX;
}
Annotation.prototype.getWidth = function() {
return this.width;
}
Annotation.prototype.getNotes = function() {
return this.notes;
}
Annotation.prototype.getTags = function() {
return this.tags;
}
Annotation.prototype.getColor = function() {
if( this.isOwner ) {
return userSettings.get("annotationColor");
} else {
return "gray";
}
}
Annotation.prototype.setType = function(type) {
this.type = type;
}
Annotation.prototype.setID = function(ID) {
this.ID = ID;
}
Annotation.prototype.setDasID = function(dasID) {
this.dasID = dasID;
}
Annotation.prototype.setStartPage = function(startPage) {
if( this.startPage == startPage ) return;
this.startPage = startPage;
this.setChanged();
}
Annotation.prototype.setEndPage = function(endPage) {
if( this.endPage == endPage ) return;
this.endPage = endPage;
this.setChanged();
}
Annotation.prototype.setStartWord = function(startWord) {
if( this.startWord == startWord ) return;
this.startWord = startWord;
this.setChanged();
}
Annotation.prototype.setEndWord = function(endWord) {
if( this.endWord == endWord ) return;
this.endWord = endWord;
this.setChanged();
}
Annotation.prototype.setScope = function(scope) {
if( this.scope == scope ) return;
this.scope = scope;
this.setChanged();
}
Annotation.prototype.setNote = function(notes) {
if( this.notes == notes ) return;
this.notes = notes;
this.setChanged();
}
Annotation.prototype.setTags = function(tags) {
if( this.tags == tags ) return;
this.tags = tags;
this.setChanged();
}
Annotation.prototype.setOpen = function(open) {
if( this.open == open ) return;
this.open = open ? 1 : 0;
if( !this.bubble ) return;
if( open ) {
this.bubble.show();
} else {
this.bubble.hide();
}
this.setChanged();
}
Annotation.prototype.isOpen = function() {
return this.open;
}
Annotation.prototype.setFocus = function(focus) {
if( this.hidden ) return false;
if( focus ) {
this.setOpen(true);
}
if( this.bubble ) {
this.bubble.setForeground(focus);
}
}
Annotation.prototype.setDeltaY = function(y) {
this.deltaY = y;
this.setChanged();
}
Annotation.prototype.setDeltaX = function(x) {
this.deltaX = x;
this.setChanged();
}
Annotation.prototype.hide = function() {
if( this.bubble ) this.bubble.hide();
this.hidden = true;
this.attachedPage = null;
}
Annotation.prototype.show = function() {
this.hidden = false;
var reader = this.annotationManager.reader;
var attachedPageObj = reader.pages.get(this.attachedPage);
if( !this.attachedPage || !attachedPageObj ) {
this.pickAttachedPage();
if( !this.attachedPage ) {
throw new Exception("Cannot display annotation w/o a page displayed", 'PageNotDisplayed');
}
}
_a=0;
try {
if( !this.bubble ) {
this.bubble = new AnnotationControl(this, this.open);
}
if( this.open ) {
this.bubble.show();
}
if( !this.saveTimer ) {
this.autoSave();
}
} catch(e) {
if( !e.isType('PageNotReady') ) throw e;
}
}
Annotation.prototype.saveCallback = function(jsoncom) {
if (jsoncom.isError()) {
_a=0;
this.bubble.setSaveStatus( 'error' );
}
else {
var data = jsoncom.getData();
this.isNew = false;
_a=0;
this.dasID = data.annotationId;
this.relatedContent = data.relatedContent;
if( this.bubble ) {
this.bubble.setSaveStatus( 'saved' );
}
}
this.annotationManager.fireEvent( 'annotationSaved', this );
}
Annotation.prototype.destroyCallback = function(jsoncom) {
if( jsoncom.isError() ) {
_a=0;
}
else {
_a=0;
}
}
Annotation.prototype.save = function() {
if( !this.bubble || !this.isOwner ||
(!this.isChanged() && !this.bubble.isChanged()) ) {
return;
}
if( !this.isNew && !this.dasID )
return;
var tttt = new Array();
tttt[Annotation.HIGHLIGHT] = "HIGHLIGHT";
tttt[Annotation.BOOKMARK] = "BOOKMARK";
var date = new Date();
this.timestamp = date.getTime();
this.notes = this.bubble.getNotes();
this.tags = this.bubble.getTags().join(", ");
_a=0;
this.width = this.bubble.getWidth();
_a=0;
var params = { action:    "putAnnotation",
asin:      this.annotationManager.asin,
startPage: this.startPage,
endPage:   this.endPage,
startWord: this.startWord,
endWord:   this.endWord,
type:      this.type,
scope:     this.scope,
notes:     this.notes,
tags:      this.tags,
deltaY:    this.deltaY,
deltaX:    this.deltaX,
width:     this.width,
open:      this.open,
timestamp: this.timestamp };
if( this.dasID ) {
params.annotationId = this.dasID;
}
var json = new JSONCom( browser );
json.setKey(this.dasID);
json.setCallback( this.saveCallback.bind(this) );
json.setURL( Config.getServiceURL() );
json.setParams( params );
json.sendRequest();
this.isNew = false;
this.dirty = false;
this.bubble.setChanged(false);
}
Annotation.prototype.remove = function() {
this.annotationManager.fireEvent( 'annotationRemoved', this );
var params;
params = { action: "deleteAnnotation", asin: this.annotationManager.asin, annotationId: this.dasID};
var json = new JSONCom( browser );
json.setKey(this.dasID);
json.setCallback( this.destroyCallback.bind(this) );
json.setURL( Config.getServiceURL() );
json.setParams( params );
json.sendRequest();
}
Annotation.prototype.isChanged = function() {
return this.dirty;
}
Annotation.prototype.setChanged = function() {
this.dirty = true;
}
Annotation.prototype.getClosestPoint = function(x, y) {
return [0,0];
}
Annotation.prototype.getCornerUR = function() {
}
Annotation.prototype.refresh = function() {
if( this.open && !this.hidden && this.bubble != undefined ) {
this.bubble.refreshUI();
}
}
AnnotationControl = function(annotation, initStatus) {
this.annotation = annotation;
this.reader = annotation.annotationManager.reader;
this.attachedPage = annotation.getAttachedPage();
this.basediv = this.getBaseDiv();
this.div = null;
this.focus = false;
this.onMoveCallback = this.onMove.bind(this);
this.onEndMoveCallback = this.onEndMove.bind(this);
this.onResizeRightCallback = this.onResizeRight.bind(this);
this.onEndResizeRightCallback = this.onEndResizeRight.bind(this);
this.isMoving = false;
this.isResizingRight = false;
this.lastX = null;
this.lastY = null;
this.lastWidth = null;
this.notes = null;
this.tags = null;
this.moveBar = null;
this.resizeBar = null;
this.main = null;
this.dirty = false;
this.closeAfterFiveSeconds = this.annotation.isNew;
this.displayInitialized = false;
this.control_id = AnnotationControl.NEXT_ID;
AnnotationControl.NEXT_ID++;
_a=0;
if( initStatus ) {
this.show();
}
this.dirty = false;
}
Object.extend(AnnotationControl.prototype, SmartObject.prototype);
AnnotationControl.prototype.parent = SmartObject.prototype;
AnnotationControl.NEXT_ID = 1;
AnnotationControl.COLORS = {
'green_inner': 'E9FFDE',
'green_outer': 'CAFCB0',
'green_outer_inactive': 'D8F9C6',
'blue_inner': 'ECF9FF',
'blue_outer': 'CDEEFE',
'blue_outer_inactive': 'E1F3FB',
'pink_inner': 'FFE8F3',
'pink_outer': 'FED0E7',
'pink_outer_inactive': 'FFE8F3',
'gray_inner': 'F5F4F2',
'gray_outer': 'E8E6DC',
'gray_outer_inactive': 'EAE9E4',
'gold_inner': 'FFFCDF',
'gold_outer': 'FCF6B1',
'gold_outer_inactive': 'FFFBCE'
};
AnnotationControl.IMAGE_PARTS = [
'top_left_corner', 'top_filler', 'top_right_corner', 'left_filler',
'inner_top_left_corner', 'inner_top_right_corner', "right_filler",
'inner_bottom_left_corner', 'inner_bottom_right_corner', 'right_resizer',
'bottom_left_corner', 'bottom_filler', 'bottom_right_corner' ];
AnnotationControl.OUTER_COLORS = [
'inner_top', 'inner_bottom'
];
AnnotationControl.INNER_COLORS = [
'inner_top_middle', 'inner_left', 'main', 'inner_right',
'inner_bottom_middle'
];
AnnotationControl.LINE_HEIGHT = 20;
AnnotationControl.DEFAULT_WIDTH = 180;
AnnotationControl.DEFAULT_HEIGHT = 65;
AnnotationControl.MIN_WIDTH = 100;
AnnotationControl.prototype.destroy = function() {
_a=0;
if( this.div )
this.basediv.removeChild(this.div);
if( this.triangle ) {
_a=0;
this.triangle.remove();
}
this.parent.destroy.call(this);
}
AnnotationControl.prototype.getNotes = function() {
return this.notes.getValue();
}
AnnotationControl.prototype.setNotes = function(notes) {
this.notes.setValue(notes);
this.setChanged();
}
AnnotationControl.prototype.getTags = function() {
return this.tags.getTags();
}
AnnotationControl.prototype.setTags = function(list) {
this.tags.setTags(list);
this.setChanged();
}
AnnotationControl.prototype.setTagsByString = function(string) {
this.setTags( string.split(',') );
}
AnnotationControl.prototype.isChanged = function() {
return this.dirty;
}
AnnotationControl.prototype.setChanged = function(value) {
if( value == undefined ) value = true;
if( this.annotation.isOwner )
{
this.dirty = value ? true : false;
this.setSaveStatus( 'modified' );
}
}
AnnotationControl.prototype.initDisplay = function() {
_a=0;
this.createUI();
var left = 0;
var top = 0;
var width = AnnotationControl.DEFAULT_WIDTH;
var mode = this.reader.viewerType;
var lineTop = this.annotation.getLineTop();
var lineBottom = this.annotation.getLineBottom();
if (mode == "single" && lineTop < 0) {
this.annotation.setDeltaY(lineBottom - lineTop)
}
else {
var offsetFromToolbar = this.annotation.getLineTop()
+ browser.getAbsoluteTop(this.annotation.annotationManager.reader.getDisplayedPage(this.attachedPage).getPageDiv());
if (offsetFromToolbar < 0) {
this.annotation.setDeltaY(lineBottom - lineTop);
}
}
if ( this.annotation.getWidth() )
width = this.annotation.getWidth();
this.setNotes(this.annotation.getNotes());
this.setTagsByString(this.annotation.getTags());
this.displayInitialized = true;
this.setWidth(width);
this.setForeground(false);
this.refreshTextAreas();
if( this.annotation.isOwner && this.closeAfterFiveSeconds ) {
}
}
AnnotationControl.prototype.createUI = function() {
_a=0;
this.div = document.createElement("div");
this.div.style.position = "absolute";
browser.setZIndex(this.div, 50);
this.basediv.appendChild(this.div);
var innerColor = this.getColor("inner");
var outerColor = this.getColor("outer");
var extraOptions = "";
if( browser.ie ) {
extraOptions = ' onselectstart="return false;" onselect="return false;"';
}
var html =
'<table cellspacing="0" cellpadding="0" class="ac_frame" id="frame_'+this.control_id+'">' +
'<tr id="topbar_'+this.control_id+'"'+extraOptions+'>'+
'<td class="ac_movebar">' + this.getImage("top_left_corner") + '</td>' +
'<td style="background-image:url('+ this.getImageURL("top_filler") +');" class="ac_movebar" width="100%">' +
this.getImage("top_filler") + '</td>' +
'<td>' + this.getImage("top_right_corner") + '</td>' +
'</tr>' +
'<tr>' +
'<td id="leftbar_'+this.control_id+'" class="ac_movebar" width="9" height="100%" style="background-image:url('+ this.getImageURL("left_filler") +');"'+extraOptions+'>' +
this.getImage("left_filler") + '</td>' +
'<td width="100%" height="100%" align="center" valign="middle">' +
'<table cellspacing="0" cellpadding="0" style="width: 100%; height: 100%">' +
'<tr id="inner_top_'+this.control_id+'" style="background-color: '+ outerColor +';"'+extraOptions+'>' +
'<td width="5">' + this.getImage("inner_top_left_corner") + '</td>' +
'<td width="100%" id="inner_top_middle_'+this.control_id+'" style="background-color: '+ innerColor +'"></td>' +
'<td width="5">' + this.getImage("inner_top_right_corner") + '</td>' +
'</tr>' +
'<tr>' +
'<td height="100%" id="inner_left_'+this.control_id+'" style="background-color: '+ innerColor +'"'+extraOptions+'></td>' +
'<td id="main_'+this.control_id+'" style="background-color:'+ innerColor +'; height:100%" valign="top"></td>' +
'<td id="inner_right_'+this.control_id+'" style="background-color:'+ innerColor +'" height="100%"'+extraOptions+'></td>' +
'</tr>' +
'<tr id="inner_bottom_'+this.control_id+'" style="background-color: '+ outerColor +';"'+extraOptions+'>' +
'<td width="5">' + this.getImage("inner_bottom_left_corner") + '</td>' +
'<td width="100%" id="inner_bottom_middle_'+this.control_id+'" style="background-color: '+ innerColor +'"></td>' +
'<td width="5">' + this.getImage("inner_bottom_right_corner") + '</td>' +
'</tr>' +
'</table>' +
'</td>' +
'<td width="17" id="resizebar_'+this.control_id+'" class="ac_resizebar" style="background-image:url('+ this.getImageURL("right_filler") +')" valign="middle"'+extraOptions+'>' +
this.getImage("right_filler") + "<br/>" + this.getImage("right_resizer") + '</td>' +
'</tr>' +
'<tr id="bottombar_'+this.control_id+'" class="ac_movebar"'+extraOptions+'>' +
'<td>' + this.getImage("bottom_left_corner") + '</td>' +
'<td width="100%" style="background-image:url('+this.getImageURL("bottom_filler")+');">' +
this.getImage("bottom_filler") + '</td>' +
'<td>' + this.getImage("bottom_right_corner") + '</td>' +
'</tr>' +
'</table>';
if(browser.ie) {
html += '<iframe></iframe>';
}
this.div.innerHTML = html;
this.topBar = $('topbar_' + this.control_id);
this.leftBar = $('leftbar_' + this.control_id);
this.bottomBar = $('bottombar_' + this.control_id);
this.resizeBar = $('resizebar_' + this.control_id);
this.main = $('main_' + this.control_id);
this.mainFrame = $('frame_'+this.control_id);
this.closeButton = $(this.getImageID("top_right_corner"));
var options = {
disabled: !this.annotation.isOwner,
backgroundColor: innerColor
}
this.notes = new SmartTextArea(options);
this.tags = new TagListControl(options);
this.main.innerHTML =
'<div class="ac_bold">Note:</div>' + this.notes.getHTML() +
'<div class="ac_bold">Tags:</div>' + this.tags.getHTML() ;
if( !this.annotation.isOwner && this.annotation.customerName ) {
this.main.innerHTML += '<div class="ac_realname">' + this.annotation.customerName +
'</div>';
}
if( this.annotation.isOwner )
{
}
this.tags.init();
this.notes.init();
this.tags.getSmartTextArea().addListener('heightChange', this, 'onHeightChange');
this.notes.addListener('heightChange', this, 'onHeightChange');
Event.observe(this.topBar, 'mousedown', this.onStartMove.bind(this), false);
Event.observe(this.leftBar, 'mousedown', this.onStartMove.bind(this), false);
Event.observe(this.bottomBar, 'mousedown', this.onStartMove.bind(this), false);
Event.observe(this.resizeBar, 'mousedown', this.onStartResizeRight.bind(this), false);
Event.observe(this.div, 'mousedown', this.onClick.bind(this), false);
Event.observe(this.closeButton, 'click', this.onClose.bind(this), false);
Event.observe(this.div, 'mouseup', this.stopEvent.bind(this), false);
Event.observe(this.div, 'click', this.stopEvent.bind(this), false);
Event.observe(this.div, 'mouseover', (function() {
if( this.closeAfterFiveSeconds ) this.closeAfterFiveSeconds = false;
}).bind(this), false);
this.setHeight(AnnotationControl.DEFAULT_HEIGHT);
this.setWidth(AnnotationControl.DEFAULT_WIDTH);
this.notes.addListener('change', this, 'setChanged');
this.tags.getSmartTextArea().addListener('change', this, 'setChanged');
this.triangle = new Triangle( this.getColor("outer") );
this.triangle.basediv = this.basediv;
this.triangle.init();
}
AnnotationControl.prototype.hide = function() {
if( this.hidden || !this.displayInitialized ) return;
Element.hide(this.div);
this.hidden = true;
this.triangle.hide();
}
AnnotationControl.prototype.show = function() {
if( !this.displayInitialized ) {
this.initDisplay();
this.setSaveStatus();
}
if( this.attachedPage != this.annotation.getAttachedPage() ) {
_a=0;
this.basediv.removeChild(this.div);
this.attachedPage = this.annotation.getAttachedPage();
this.basediv = this.getBaseDiv();
this.basediv.appendChild(this.div);
this.triangle.basediv = this.basediv;
this.triangle.reattach();
}
Element.show(this.div);
this.hidden = false;
this.setLeft( this.getAdjustedLeft() );
this.setTop( this.getAdjustedTop() );
_a=0;
this.triangle.show();
this.refreshTriangle();
}
AnnotationControl.prototype.getAdjustedLeft = function() {
var naturalLeft = this.mapX(this.annotation.getLineEnd() + this.annotation.getDeltaX());
if (naturalLeft < this.getMinimumLeft())
naturalLeft = this.getMinimumLeft();
var maxLeft = this.getMaximumLeft();
if( maxLeft < this.getMinimumLeft() )
maxLeft = this.getMinimumLeft();
return (maxLeft < naturalLeft)?maxLeft:naturalLeft;
}
AnnotationControl.prototype.getAdjustedTop = function() {
var top = this.annotation.getLineTop() + this.annotation.getDeltaY();
var pageObj = this.annotation.annotationManager.reader.getDisplayedPage(this.attachedPage);
if( top < 0 ) {
top = 0;
} else if( top > pageObj.getHeight() ) {
top = pageObj.getHeight() - this.getHeight();
}
_a=0;
return this.mapY( top );
}
AnnotationControl.prototype.isLowerThanDocumentBody = function() {
return (this.getPageTop()
+ browser.getAbsoluteTop(this.annotation.annotationManager.reader.getDisplayedPage(this.attachedPage).getPageDiv())
+ this.getHeight()
+ browser.getHeight($('toolbarMenu'))
- browser.getHeight($('layoutBody')))
> 0;
}
AnnotationControl.prototype.getMaximumLeft = function () {
var browserWidth = document.body.clientWidth;
return browserWidth - this.getWidth() - 20;
}
AnnotationControl.prototype.getMinimumLeft = function() {
return (browser.ie)? 0 : this.reader.sidebar.getWidth();
}
AnnotationControl.prototype.refreshUI = function () {
this.setLeft( this.getAdjustedLeft() );
this.setTop( this.getAdjustedTop() );
var innerColor = this.getColor("inner");
var outerColor = this.getColor("outer");
this.notes.setColor( innerColor );
this.tags.setColor( innerColor )
AnnotationControl.IMAGE_PARTS.each( (function(imgName) {
var element = $(this.getImageID(imgName));
if( !element ) {
_a=0;
throw $continue;
}
element.src = this.getImageURL(imgName);
if( imgName.match(/filler/) )
{
if( !element.parentNode ) {
_a=0;
}
element.parentNode.style.backgroundImage = "url("+this.getImageURL(imgName)+")";
}
}).bind(this) );
AnnotationControl.OUTER_COLORS.each( (function(part) {
var element = $(part+'_'+this.control_id);
element.style.backgroundColor = outerColor;
}).bind(this) );
AnnotationControl.INNER_COLORS.each( (function(part) {
var element = $(part+'_'+this.control_id);
element.style.backgroundColor = innerColor;
}).bind(this) );
this.refreshTriangle();
}
AnnotationControl.prototype.setForeground = function(foreground) {
this.focus = foreground;
if( foreground ) {
this.show();
if( this.annotation.isOwner && !this.isLowerThanDocumentBody() ) {
this.notes.focus();
}
}
var zindex = foreground ? 12 : 11;
browser.setZIndex(this.div, zindex);
this.refreshUI();
}
AnnotationControl.prototype.moveBy = function(x, y) {
this.setLeft( browser.getRelativeLeft(this.div)+x );
this.setTop( browser.getRelativeTop(this.div)+y );
this.refreshTriangle();
}
AnnotationControl.prototype.refreshTriangle = function() {
if( this.triangle == undefined ) return;
var centerX = this.getPageLeft() + this.getWidth() / 2;
var centerY = this.getPageTop() + this.getHeight() / 2 + 20;
var points = this.annotation.getClosestPoint(centerX, centerY);
if( !points ) return;
this.triangle.setColor( this.getColor("outer") );
this.triangle.draw( this.mapX(points[0]), this.mapY(points[1]),
this.mapX(centerX), this.mapY(centerY) );
}
AnnotationControl.prototype.mapX = function(x) {
return x + this.reader.getAbsoluteLeft() - browser.getAbsoluteLeft(this.basediv.parentNode);
}
AnnotationControl.prototype.mapY = function(y) {
return y + this.reader.getAbsoluteTop() - browser.getAbsoluteTop(this.basediv.parentNode);
}
AnnotationControl.prototype.setLeft = function(left) {
browser.setLeft(this.div, left);
}
AnnotationControl.prototype.setTop = function(top) {
browser.setTop(this.div, top);
}
AnnotationControl.prototype.getLeft = function() {
return browser.getRelativeLeft(this.div);
}
AnnotationControl.prototype.getTop = function() {
return browser.getRelativeTop(this.div);
}
AnnotationControl.prototype.setWidth = function(width) {
browser.setWidth(this.mainFrame, width);
}
AnnotationControl.prototype.setHeight = function(height) {
browser.setHeight(this.mainFrame, height);
}
AnnotationControl.prototype.getWidth = function() {
return browser.getWidth(this.mainFrame);
}
AnnotationControl.prototype.getPageTop = function() {
return this.getTop() + browser.getAbsoluteTop(this.basediv.parentNode) - this.reader.getAbsoluteTop();
}
AnnotationControl.prototype.getPageLeft = function() {
return this.getLeft() + browser.getAbsoluteLeft(this.basediv.parentNode) - this.reader.getAbsoluteLeft();
}
AnnotationControl.prototype.getHeight = function() {
return browser.getHeight(this.mainFrame);
}
AnnotationControl.prototype.isShown = function() {
return !this.hidden;
}
AnnotationControl.prototype.onHeightChange = function(eventName, newHeight, oldHeight) {
_a=0;
this.setHeight( this.getHeight() + newHeight - oldHeight );
try {
this.refreshTriangle();
} catch(e) {  }
}
AnnotationControl.prototype.onFiveSecondsExpired = function() {
if( this.closeAfterFiveSeconds ) {
this.onClose();
}
}
AnnotationControl.prototype.onStartMove = function(event) {
if( Event.element(event) == this.closeButton ) return;
if( !this.isMoving ) {
this.isMoving = true;
this.lastX = event.clientX;
this.lastY = event.clientY;
Event.observe(document, 'mousemove', this.onMoveCallback, false);
Event.observe(document, 'mouseup', this.onEndMoveCallback, false);
Event.preventDefaults(event);
}
}
AnnotationControl.prototype.onMove = function(event) {
var diffX = event.clientX - this.lastX;
var diffY = event.clientY - this.lastY;
if( this.getLeft() + diffX < this.getMinimumLeft() ) {
diffX = this.getMinimumLeft() - this.getLeft();
}
if ( this.getLeft() + diffX > this.getMaximumLeft() ) {
diffX = this.getMaximumLeft() - this.getLeft();
}
if( Math.abs(diffX) < 2 && Math.abs(diffY) < 2 )
return;
this.moveBy(diffX, diffY);
this.lastX = event.clientX;
this.lastY = event.clientY;
Event.stopBubble(event);
}
AnnotationControl.prototype.onEndMove = function(event) {
this.isMoving = false;
Event.stopObserving(document, 'mousemove', this.onMoveCallback, false);
Event.stopObserving(document, 'mouseup', this.onEndMoveCallback, false);
this.setChanged();
this.annotation.setDeltaX( this.getPageLeft() - this.annotation.getLineEnd() );
this.annotation.setDeltaY( this.getPageTop() - this.annotation.getLineTop() );
Event.stopBubble(event);
}
AnnotationControl.prototype.onStartResizeRight = function(event) {
if( !this.isResizingRight ) {
this.isResizingRight = true;
this.lastX = event.clientX;
this.lastWidth = this.getWidth();
this.lastMainWidth = browser.getWidth(this.main);
Event.observe(document, 'mousemove', this.onResizeRightCallback, false);
Event.observe(document, 'mouseup', this.onEndResizeRightCallback, false);
Event.preventDefaults(event);
}
}
AnnotationControl.prototype.refreshTextAreas = function() {
this.notes.updateTextArea();
this.notes.refreshUI();
this.tags.refreshTextArea();
}
AnnotationControl.prototype.onResizeRight = function(event) {
var diffX = event.clientX - this.lastX;
if (this.getLeft() > this.getMaximumLeft() && diffX > 0) {
_a=0;
return;
}
if( Math.abs(diffX) < 2)
return;
if (this.lastMainWidth + diffX >= AnnotationControl.MIN_WIDTH) {
this.tags.setWidth(this.lastMainWidth + diffX);
this.notes.setWidth(this.lastMainWidth + diffX);
this.setWidth(this.lastWidth + diffX);
}
this.refreshTriangle();
this.refreshTextAreas();
}
AnnotationControl.prototype.onEndResizeRight = function(event) {
this.isResizingRight = false;
Event.stopObserving(document, 'mousemove', this.onResizeRightCallback, false);
Event.stopObserving(document, 'mouseup', this.onEndResizeRightCallback, false);
Event.stopBubble(event);
}
AnnotationControl.prototype.onClick = function(event) {
Event.stopBubble(event);
if( Event.element(event) == this.closeButton )
return;
this.reader.selector.selectAnnotation(this.annotation);
}
AnnotationControl.prototype.onClose = function(event) {
this.reader.selector.deselectAnnotation(this.annotation);
this.annotation.setOpen(0);
if( event )
Event.stopBubble(event);
}
AnnotationControl.prototype.stopEvent = function(event) {
if ( !this.isMoving && !this.isResizingRight )
Event.stopBubble(event);
}
AnnotationControl.prototype.getImageURL = function(part) {
var imageName = "digital/sitb/reader/ac/" + this.annotation.getColor() + "_" + part;
if( !this.focus && Config.getGeneralMediaURL(imageName+"_inactive") ) {
imageName += "_inactive";
}
return Config.getGeneralMediaURL(imageName);
}
AnnotationControl.prototype.getImageID = function(part) {
return part + '_img_' + this.control_id;
}
AnnotationControl.prototype.getImage = function(part, customOptions) {
var options = { id: this.getImageID(part) };
if( browser.ie ) {
options.ondragstart = "return false;";
}
if( customOptions ) {
Object.extend( options, customOptions );
}
var option_string = "";
$H(options).keys().each((function(key) {
option_string += key + '="' + options[key] + '" ';
}).bind(this) );
return '<img src="'+ this.getImageURL(part) +'" '+option_string+'/>';
}
AnnotationControl.prototype.getColor = function(part) {
var colorName = this.annotation.getColor() + "_" + part;
if( !this.focus && AnnotationControl.COLORS[colorName+"_inactive"] ) {
colorName += '_inactive';
}
return '#' + AnnotationControl.COLORS[colorName];
}
AnnotationControl.prototype.setSaveStatus = function( saved ) {
return;
if( !this.annotation.isOwner ) return;
var status = $('save_status_' + this.control_id);
if( saved == undefined ) saved = '';
if( saved == 'saved' )
status.innerHTML = 'Changes saved';
else if( saved == 'modified' )
status.innerHTML = 'Saving changes...';
else if( saved == 'error' )
status.innerHTML = 'Changes not saved';
else
status.innerHTML = '&nbsp;';
}
AnnotationControl.prototype.getBaseDiv = function() {
return this.reader.pageManager.getPageFromCache(this.attachedPage).annotDiv;
}
SampleAnnotation = function(id) {
this.note = '';
this.tags = new Array();
this.highlight = '';
this.id = id;
}
AnnotationSearch = function(annotations) {
this.aList = (typeof annotations == 'undefined') ? new Array() : annotations;
}
AnnotationSearch.prototype.add = function(obj) {
this.aList.push(obj);
}
AnnotationSearch.prototype.remove = function(obj) {
this.aList = this.aList.without(obj);
}
AnnotationSearch.prototype.search = function(query, matchFunction) {
var matches = new Array();
var tokens  = query.toLowerCase().split(' ');
for (var i = 0; i < this.aList.length; i++)
if (matchFunction(this.aList[i], tokens))
matches.push(this.aList[i]);
return matches;
}
AnnotationSearch.prototype.searchMyBookmarks = function(query) {
return this.search(query, this.matchMyBookmarks.bind(this));
}
AnnotationSearch.prototype.searchMyHighlights = function(query) {
return this.search(query, this.matchMyHighlights.bind(this));
}
AnnotationSearch.prototype.searchMyNotes = function(query) {
return this.search(query, this.matchMyNotes.bind(this));
}
AnnotationSearch.prototype.searchMyTags = function(query) {
return this.search(query, this.matchMyTags.bind(this));
}
AnnotationSearch.prototype.searchAllTags = function(query) {
return this.search( query, this.matchAllTags.bind(this) );
}
AnnotationSearch.prototype.matchTokens = function(str, tokens) {
for(var i = 0; i < tokens.length; i++)
if (!str.match(tokens[i]))
return false;
return true;
}
AnnotationSearch.prototype.matchMyBookmarks = function(obj, tokens) {
if (!obj.isOwner || obj.type != obj.BOOKMARK)
return false;
return this.matchTokens(obj.getNotes().toLowerCase(), tokens);
}
AnnotationSearch.prototype.matchMyHighlights = function(obj, tokens) {
if (!obj.isOwner || obj.type != obj.HIGHLIGHT)
return false;
return this.matchTokens(obj.getRelatedContent().toLowerCase(), tokens);
}
AnnotationSearch.prototype.matchMyNotes = function(obj, tokens) {
if( !obj.isOwner )
return false;
return this.matchTokens(obj.getNotes().toLowerCase(), tokens);
}
AnnotationSearch.prototype.matchMyTags = function(obj, tokens) {
if( !obj.isOwner )
return false;
return this.matchTokens(obj.getTags().toLowerCase(), tokens);
}
AnnotationSearch.prototype.matchAllTags = function(obj, tokens) {
return this.matchTokens(obj.getTags().toLowerCase(), tokens);
}
AnnotationSearch.prototype.matchHL = function(obj, tokens) {
str = obj.highlight.toLowerCase();
for(var i = 0; i < tokens.length; ++i) {
if(!str.match(tokens[i])) return false;
}
return true;
}
AnnotationViewer = function( reader, annotationManager )
{
this.reader = reader;
this.annotationManager = annotationManager;
this.annotations = $('annotations');
this.html = '';
this.insertBefore = null;
this.renderFunctions = new AssociativeArray();
this.renderFunctions['allannotations']  = this.renderAllAnnotations.bind(this);
this.renderFunctions['allnotes']        = this.renderAllNotes.bind(this);
this.renderFunctions['yourannotations'] = this.renderYourAnnotations.bind(this);
this.renderFunctions['yourhighlights']  = this.renderYourHighlights.bind(this);
this.renderFunctions['yourbookmarks']   = this.renderYourBookmarks.bind(this);
this.renderFunctions['yournotes']       = this.renderYourNotes.bind(this);
this.annotationEntries = new AssociativeArray();
Event.observe($('annotationFilterCombo'), 'change', this.filterAnnotations.bind(this));
annotationManager.addListener( 'annotationRemoved', this, 'onAnnotationRemove' );
annotationManager.addListener( 'annotationSaved', this, 'onAnnotationSave' );
}
Object.extend(AnnotationViewer.prototype, SmartObject.prototype);
AnnotationViewer.prototype.getView = function() {
return $('annotationFilterCombo').value;
}
AnnotationViewer.prototype.filterAnnotations = function()
{
var annoOption = this.getView();
if( annoOption == '' ) {
return;
}
extras.showLoader();
while( this.annotations.hasChildNodes() )
this.annotations.removeChild( this.annotations.firstChild );
if( this.annotationManager.loadStatus == 'LOADED' )
{
this.renderAnnotationLinks( annoOption );
extras.hideLoader();
}
else if( this.annotationManager.loadStatus == 'ERROR' )
{
this.annotations.innerHTML = 'Service temporarily unavailable, try again later.';
extras.hideLoader();
}
else if( this.annotationManager.loadStatus.match( 'LOADING' ) )
{
this.annotations.innerHTML = 'Loading...';
setTimeout( 'reader.annotationManager.annotationViewer.filterAnnotations()', 1000);
}
}
AnnotationViewer.prototype.renderAnnotationLinks = function( view )
{
var before = new Date().getTime();
this.html = '';
this.annotations.innerHTML = '';
this.annotationEntries = new AssociativeArray();
if( view.match( 'tags' ) )
{
this.renderTags( view );
}
else
{
this.annotationManager.annotationsList.eachSorted(
(function(list,pageNum) {
list.each( this.renderFunctions[view] );
}).bind(this)
);
}
var interm = new Date().getTime();
var interm2 = new Date().getTime();
this.reader.sidebar.onWindowResize();
var after = new Date().getTime();
var diff = after - before;
_a=0;
_a=0;
}
AnnotationViewer.prototype.renderAllAnnotations = function( annotation )
{
if( annotation.getType() == this.annotationManager.HIGHLIGHT && annotation.getScope() == Annotation.PUBLIC )
{
this.renderHighlight( annotation, false );
}
else if( annotation.getType() == this.annotationManager.BOOKMARK && annotation.getScope() == Annotation.PUBLIC )
{
this.renderBookmark( annotation, false );
}
}
AnnotationViewer.prototype.renderAllNotes = function( annotation )
{
if ( annotation.getScope() == Annotation.PUBLIC ) {
this.renderNotes( annotation );
}
}
AnnotationViewer.prototype.renderYourAnnotations = function( annotation )
{
if( annotation.isOwner == 1 )
{
if( annotation.getType() == this.annotationManager.HIGHLIGHT )
{
this.renderHighlight( annotation, false );
}
if( annotation.getType() == this.annotationManager.BOOKMARK )
{
this.renderBookmark( annotation, false );
}
}
}
AnnotationViewer.prototype.renderYourHighlights = function( annotation )
{
if( annotation.isOwner == 1 && annotation.getType() == this.annotationManager.HIGHLIGHT )
{
this.renderHighlight( annotation, true );
}
}
AnnotationViewer.prototype.renderYourBookmarks = function( annotation )
{
if( annotation.isOwner == 1 && annotation.getType() == this.annotationManager.BOOKMARK )
{
this.renderBookmark( annotation, true );
}
}
AnnotationViewer.prototype.renderYourNotes = function( annotation )
{
if( annotation.isOwner == 1 )
{
this.renderNotes( annotation );
}
}
AnnotationViewer.prototype.renderNotes = function( annotation )
{
var notes  = annotation.getNotes();
var page   = annotation.getStartPage();
var author = annotation.customerNameNoBadge;
var ID  = annotation.getID();
if( notes != undefined && notes.length > 0 )
{
this.renderAnnotationEntry(
notes, [page], '', '', author, false, false, true, true, [ID] );
}
}
AnnotationViewer.prototype.renderTags = function( view )
{
var tagCollection = {};
var sortedTags = new Array();
var annotIDs = new Array();
this.annotationManager.annotationsList.eachSorted(
(function( annotations )
{
annotations.each(
(function( annotation )
{
if( (view == "alltags" && annotation.getScope() == Annotation.PUBLIC)
||  (view == "yourtags" && annotation.isOwner == 1) )
{
var page = annotation.getStartPage();
var tags = annotation.getTags();
if( tags != undefined && tags.length > 0 )
{
var tagsList = tags.split( ',' );
for( var i = 0; i < tagsList.length; i++ )
{
var tag = tagsList[i].trim().toLowerCase();
if (tagCollection[tag]==undefined) tagCollection[tag] = new Object();
var pages = tagCollection[tag].pages;
if( typeof( pages ) == "undefined" )
{
sortedTags.push( tag );
tagCollection[tag].pages = new Array();
tagCollection[tag].pages.push( page );
annotIDs[tag] = new Array();
annotIDs[tag][page] = new Array();
}
else if( pages[pages.length-1] != page )
{
pages.push( page );
annotIDs[tag][page] = new Array();
}
if (annotIDs[tag][page][ annotIDs[tag][page].length-1 ] != annotation.getID())
annotIDs[tag][page].push( annotation.getID() );
if (annotation.isOwner == 1) tagCollection[tag].isOwner = true;
}
}
}
}).bind(this)
);
}).bind(this)
);
sortedTags.sort();
for( var i = 0; i < sortedTags.length; i++ )
{
var tag = sortedTags[i];
this.renderAnnotationEntry(
tag, tagCollection[tag].pages, '', '', '', true, false, true, false, annotIDs[tag], true );
}
}
AnnotationViewer.prototype.renderHighlight = function( highlight, isCompact )
{
var tags   = highlight.getTags();
var note   = highlight.getNotes();
var page   = highlight.getStartPage();
var text   = highlight.getRelatedContent();
var author = highlight.customerNameNoBadge;
var annotID  = highlight.getID();
if( isCompact )
author = '';
this.renderAnnotationEntry(
text, [page], tags, note, author, false, true, isCompact, true, [annotID] );
}
AnnotationViewer.prototype.renderBookmark = function( bookmark, isCompact )
{
var tags   = bookmark.getTags();
var note   = bookmark.getNotes();
var page   = bookmark.getStartPage();
var text   = 'Bookmark';
var author = bookmark.customerNameNoBadge;
var annotID  = bookmark.getID();
if( isCompact )
{
text = (note != undefined && note.length > 0) ?
note : ('Page ' + this.reader.pageManager.getLogicalPageNumber( page ));
author = '';
}
this.renderAnnotationEntry(
text, [page], tags, note, author, false, false, isCompact, true, [annotID] );
}
AnnotationViewer.prototype.renderAnnotationEntry = function(
text, pages, tags, note, author, isTextTag, isTextQuote, isCompact, addBreak, annotID, tagsView )
{
var tdStyle = (addBreak)?"margin-top: 10px;":"margin-top: 0px;";
var tempHTML = '<div class="SEBase dots" style="'+ tdStyle +'">&nbsp;';
var textSpanStyle = (isTextQuote)?"font-style: italic;":"";
var textHTMLEscaped = text.escapeHTML();
var textQuotesEscaped = textHTMLEscaped.escapeQuotes();
tempHTML += '<span class="SELeft" style="'+ textSpanStyle + '" title="'+ textQuotesEscaped +'" >';
if( isTextTag )
{
tempHTML += TagListControl.getViewHTML( text.split( ', ' ) );
}
else
{
tempHTML += textHTMLEscaped;
}
tempHTML += '</span>';
tempHTML += '<span class="SERight">';
var eventHTML = "";
var pageNumber;
if( tagsView )
{
if( pages.length <= 5 )
{
for( var i = 0, len = pages.length; i < len; i++ )
{
var delim = (i > 0)?", ":"";
pageNumber = this.reader.pageManager.getLogicalPageNumber( pages[i] );
if (annotID[pages[i]].length == 1) {
eventHTML = "reader.fireEvent('popUpAnnotation','" + pages[i] + "','" + annotID[pages[i]][0] + "');";
tempHTML += delim +
"<a href=\"#\" onClick=\"if(reader) {reader.DisplayPage('" +
pages[i] + "',undefined,true);" + eventHTML + " return false;}\">" + pageNumber + "</a>";
}
else {
tempHTML += delim +
"<a href=\"#\" onClick=\"if(reader) {reader.search.searchTagsOnPage('" + textHTMLEscaped.escapeQuotes(true) + "','" + pages[i] + "'); return false;}\">" + pageNumber + "</a>";
}
}
}
else
{
tempHTML += '<a href="#" onClick="reader.search.tagSearch(\''+ textQuotesEscaped +'\')">' + pages.length + ' pages</a>';
}
}
else {
eventHTML = "reader.fireEvent('popUpAnnotation','" + pages[0] + "','" + annotID[0] + "');";
pageNumber = this.reader.pageManager.getLogicalPageNumber( pages[0] );
tempHTML +=
"<a href=\"#\" onClick=\"if(reader) {reader.DisplayPage('" +
pages[0] + "',undefined,true);" + eventHTML + " return false;}\">" + pageNumber + "</a>";
}
tempHTML += '</span></div>';
if( !isCompact )
{
if( tags != undefined && tags.length > 0 )
{
tempHTML += '<div class="SEBase">&nbsp;<span class="SELeft fieldName" style="padding-left:5px" title="' + tags.escapeHTML().escapeQuotes() + '">Tags: ' + TagListControl.getViewHTML( tags.split( ', ' )) + '</span></div>';
}
if( note != undefined && note.length > 0 )
{
note = note.replace( /\s+/g, ' ' );
tempHTML += '<div class="SEBase">&nbsp;<span class="SELeft fieldName" style="padding-left:5px" title="' + note.escapeHTML().escapeQuotes() + '">Note: ' + note.escapeHTML() + '</span></div>';
}
}
if( author != undefined && author.length > 0 )
{
tempHTML += '<div class="SEBase">&nbsp;<span class="SELeft fieldName">By: ' + author + '</span></div>';
}
var annotContainer = this.annotationEntries.get(annotID[0]);
if( !annotContainer || tagsView ) {
var annotContainer = document.createElement('div');
if( this.insertBefore ) {
this.annotations.insertBefore(annotContainer, this.insertBefore);
} else {
this.annotations.appendChild(annotContainer);
}
if( !tagsView ) {
this.annotationEntries.put(annotID[0], annotContainer);
}
}
annotContainer.innerHTML = tempHTML;
}
AnnotationViewer.prototype.onAnnotationSave = function( event, annotation ) {
if( this.getView().match('tags') ) {
this.renderAnnotationLinks( this.getView() );
} else {
this.annotationManager.annotationsList.eachSorted(
(function(annotations,pageNum) {
if( pageNum < annotation.getStartPage() ) {
throw $continue;
}
var firstAnnotation = null;
annotations.each( (function(annot) {
firstAnnotation = annot;
this.insertBefore = this.annotationEntries.get(firstAnnotation.getID())
if( this.insertBefore )
throw $break;
}).bind(this) );
if( this.insertBefore )
throw $break;
}).bind(this)
);
this.renderFunctions[this.getView()]( annotation );
this.insertBefore = null;
}
}
AnnotationViewer.prototype.onAnnotationRemove = function( event, annotation ) {
if( this.getView().match('tags') ) {
this.renderAnnotationLinks( this.getView() );
} else {
var annotationElement = this.annotationEntries.get( annotation.getID() );
if( annotationElement ) {
this.annotations.removeChild( annotationElement );
this.annotationEntries.remove( annotation.getID() );
}
}
}
Bookmark = function (annotationManager, data, isNew) {
if( isNew )
data.deltaX = -250;
Annotation.call(this, annotationManager, annotationManager.BOOKMARK, data, isNew);
this.bookmarkDiv = null;
}
Object.extend(Bookmark.prototype, Annotation.prototype);
Bookmark.prototype.parent = Annotation.prototype;
Bookmark.CORNER_SIZE = 80;
Bookmark.prototype.clean = function () {
if( !this.pageDiv ) {
_a=0;
} else {
this.pageDiv.removeChild( this.bookmarkDiv );
this.bookmarkDiv = null;
}
this.parent.clean.call(this);
}
Bookmark.prototype.hide = function () {
_a=0;
if( this.bookmarkDiv )
browser.setVisibility(this.bookmarkDiv, "hide");
this.parent.hide.call(this);
}
Bookmark.prototype.show = function() {
if( this.bookmarkDiv == null ) {
this.bookmarkDiv = document.createElement("div");
browser.setNodeAttribute(this.bookmarkDiv, "id", "bookmark_" + this.startPage);
browser.setPositioning(this.bookmarkDiv, "absolute");
this.bookmarkDiv.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + Config.getGeneralMediaURL("digital/sitbv3/general/bookmark_clean.png") + "')";
this.pageDiv = this.annotationManager.getPageDiv(this.startPage);
_a=0;
this.pageDiv.appendChild(this.bookmarkDiv);
this.bookmarkImg = document.createElement("img");
browser.setNodeAttribute(this.bookmarkImg, "src", Config.getGeneralMediaURL("digital/sitbv3/general/bookmark_clean.png"));
this.bookmarkImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)';
this.bookmarkDiv.appendChild(this.bookmarkImg);
}
_a=0;
this.update();
_a=0;
browser.setVisibility(this.bookmarkDiv, "visible");
this.parent.show.call(this);
}
Bookmark.prototype.reset = function () {
if ($("bookmark" + this.id) != undefined)
this.pageDiv.removeChild(this.bookmarkDiv);
}
Bookmark.prototype.remove = function () {
if ($("bookmark" + this.id) != undefined)
this.pageDiv.removeChild(this.bookmarkDiv);
this.parent.remove.call(this);
}
Bookmark.prototype.getCornerUR = function() {
return [browser.getAbsoluteLeft(this.bookmarkDiv), browser.getAbsoluteTop(this.bookmarkDiv)];
}
Bookmark.prototype.getClosestPoint = function(x, y) {
return this.getCornerUR();
}
Bookmark.prototype.isClicked = function(x, y) {
if( this.hidden ) return false;
var leftX = browser.getAbsoluteLeft(this.bookmarkDiv);
var rightX = leftX + browser.getWidth(this.bookmarkDiv);
var topY = browser.getAbsoluteTop(this.bookmarkDiv);
var bottomY = topY + browser.getHeight(this.bookmarkDiv);
return ( x > leftX && x < rightX && y > topY && y < bottomY );
}
Bookmark.prototype.getBottom = function() {
return browser.getAbsoluteTop(this.bookmarkDiv) + browser.getHeight(this.bookmarkDiv);
}
Bookmark.prototype.getLineEnd = function() {
return browser.getAbsoluteLeft(this.bookmarkDiv);
}
Bookmark.prototype.getLineTop = function() {
return browser.getAbsoluteTop(this.bookmarkDiv);
}
Bookmark.prototype.getLineBottom = function() {
return browser.getAbsoluteTop(this.bookmarkDiv);
}
Bookmark.prototype.update = function() {
browser.setLeft(this.bookmarkDiv, browser.getWidth(this.pageDiv) - 55);
browser.setTop(this.bookmarkDiv, "0px");
}
Bookshelf = function(asin) {
this.asin = asin;
this.startOffset = 0;
this.sortOrder = 'poo';
this.bookCount = 0;
this.initialized = 0;
this.imgCount = 10;
this.images = new Array(this.imgCount);
for(i = 0; i < this.imgCount; i++) {
this.images[i] = document.createElement('img');
Element.addClassName(this.images[i], 'mbsCover');
}
this.imageInfo = new Array();
this.onOutsideBookshelfClickCallback = this.onOutsideBookshelfClick.bind(this);
}
Object.extend(Bookshelf.prototype, SmartObject.prototype);
Bookshelf.prototype.initialize = function() {
var shelf = $('mbsShelf');
shelf.innerHTML = '';
this.startOffset = 0;
this.imgCount = Math.min(20, this.bookCount);
for(i = 0; i < this.imgCount; i++) {
if( !this.images[i] ) {
_a=0;
continue;
}
this.setCover(this.images[i], i);
if(this.images[i].parent != shelf) {
shelf.appendChild(this.images[i])
}
}
this.shadeButtons();
}
Bookshelf.prototype.setCover = function(imgObj, position) {
imgObj.id = 'mbsCover' + position;
var book;
if(book = this.imageInfo[position]) {
imgObj.src = book.src;
imgObj.height = book.height;
imgObj.width = book.width;
imgObj.onclick = new Function("bookshelf.open('" + book.asin + "');");
} else {
imgObj.src = Config.getGeneralMediaURL('x-site/icons/no-img-sm');
}
if( browser.ie )
{
imgObj.onmouseover = new Function("this.style.borderColor = '#039';");
imgObj.onmouseout = new Function("this.style.borderColor = '#FFF';");
}
}
Bookshelf.prototype.scrollRight = function() {
if (this.startOffset + this.imgCount >= this.bookCount) return;
var shelf = $('mbsShelf');
var first = $('mbsCover' + this.startOffset);
shelf.removeChild(first);
this.setCover(first, this.startOffset + this.imgCount)
shelf.appendChild(first);
++this.startOffset;
this.shadeButtons();
}
Bookshelf.prototype.scrollLeft = function() {
if(this.startOffset <= 0) return;
var shelf = $('mbsShelf');
var last = $('mbsCover' + (this.startOffset + this.imgCount - 1));
shelf.removeChild(last);
this.setCover(last, --this.startOffset);
shelf.insertBefore(last, shelf.firstChild);
this.shadeButtons();
}
Bookshelf.prototype.shadeButtons = function() {
browser.setOpacity($('mbsSrlLeft'), (this.startOffset<=0) ? 0.25 : 1);
browser.setOpacity($('mbsSrlRight'), (this.startOffset + this.imgCount>=this.bookCount) ? 0.25 : 1);
}
Bookshelf.prototype.populate = function(initialize) {
if(initialize) {
sort = $('mbsSort');
this.sortOrder = sort.options[sort.selectedIndex].value;
$('mbsShelf').innerHTML = '<span class="small"><center>Loading...</center></span>';
}
var json = new JSONCom( browser );
json.setCallback( this.populateCallback.bind(this) );
json.setURL( Config.getServiceURL() );
if(initialize) {
json.setParams({ action: "getBookshelf", p1: 0, p2: 20, p3: this.sortOrder, p4: Config.getRequestedASIN() });
} else {
json.setParams({ action: "getBookshelf", p1: 20, p2: 0, p3: this.sortOrder, p4: Config.getRequestedASIN() });
}
json.sendRequest();
}
Bookshelf.prototype.populateCallback = function(jsoncom) {
var shelf = $('mbsShelf');
if(jsoncom.isError()) {
if (jsoncom.getErrorCode() == "MBS_AUTHENTICATION" ||
jsoncom.getErrorCode() == "MBS_EMPTY" ) {
shelf.innerHTML = '<span class="small">' + jsoncom.getError() + '</span>';
}
else {
_a=0;
shelf.innerHTML = '<span class="small">Your list of books you can read online is currently unavailable. Please <a href="#" onclick="bookshelf.populate(1);">try again</a> later.</span>';
}
this.shadeButtons();
} else {
out = jsoncom.getData();
var settings = out[0];
for(i=0; i < settings.count; ++i) {
this.imageInfo[settings.start + i] = out[i + 1];
}
if(settings.start == 0) {
this.bookCount = settings.total;
this.initialize();
if(this.bookCount > settings.count) this.populate(0);
}
}
}
Bookshelf.prototype.toggle = function() {
var m = $("mbsMiddle");
var i = $("showHideMbsImg");
if (m.style.display != "block") {
m.style.display = "block";
i.src = Config.getGeneralMediaURL("digital/sitbv3/toolbar/show-hide_hide");
Event.observe(document, 'click', this.onOutsideBookshelfClickCallback);
Event.observe($('toolbarMenu'), 'click', this.onOutsideBookshelfClickCallback);
} else {
m.style.display = "none";
i.src = Config.getGeneralMediaURL("digital/sitbv3/toolbar/show-hide_show");
Event.stopObserving(document, 'click', this.onOutsideBookshelfClickCallback);
Event.stopObserving($('toolbarMenu'), 'click', this.onOutsideBookshelfClickCallback);
}
if(!this.initialized) {
this.populate(1);
this.initialized = 1;
}
}
Bookshelf.prototype.open = function(asin) {
window.location = Config.getReaderURL() + "?asin=" + asin;
}
Bookshelf.prototype.onOutsideBookshelfClick = function (event) {
var parentDiv = Event.findElement(event, "div");
var id = parentDiv.id;
if( id == "mbsHolder" || id == "mbsMiddle" || id == "mbsSorter" ||
id == "mbsBottom" || id == "mbsShelf" || id == "mbsShowHide" ) {
return;
}
var m = $("mbsMiddle").style.display;
if ( m == "block" || m == "" ) {
this.toggle();
}
}
function Clipboard() {
this.content = '';
}
Object.extend(Clipboard.prototype, SmartObject.prototype);
Clipboard.prototype.set = function(string) {
this.content = string;
this.refresh();
}
Clipboard.prototype.refresh = function() {
try
{
if( window.clipboardData ) {
window.clipboardData.setData( 'Text', this.content );
} else {
var copyDiv = $('copyDiv');
if(!copyDiv) {
copyDiv = document.createElement('div');
copyDiv.id = 'copyDiv';
document.body.appendChild(copyDiv);
}
var divinfo = '<embed src="' + Config.getGeneralMediaURL('digital/sitbv3/ffcopy') +
'" FlashVars="clipboard='+escape(this.content)+
'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
copyDiv.innerHTML = divinfo;
}
}
catch ( e )
{
}
}
Cursor = function() {
this.previousType = "move";
this.isTrailing = false;
this.trailingImage = "";
this.specialCursors = new AssociativeArray();
this.specialComplements = new AssociativeArray();
this.specialCursors.put('highlight', Config.getGeneralMediaURL('digital/sitbv3/general/highlight_enabled_icon'));
this.specialComplements.put('highlight', 'text');
this.cursors = new Array();
this.onMoveCallback = this.onMouseMove.bind(this);
this.onLoad();
}
Object.extend(Cursor.prototype, SmartObject.prototype);
Cursor.prototype.onLoad = function(event) {
this.imgElement = document.createElement('img');
this.imgElement.style.position = "absolute";
document.body.appendChild(this.imgElement);
Element.hide(this.imgElement);
Event.observe(document, 'mouseout', this.onMouseOut.bind(this), true);
}
Cursor.prototype.setCursor = function(type) {
this.cursors.push(type);
this.refreshCursor();
}
Cursor.prototype.unsetCursor = function(type) {
for(var i=this.cursors.length-1; i>=0; i--) {
if( this.cursors[i] == type )
this.cursors.splice(i, 1);
}
this.refreshCursor();
}
Cursor.prototype.getCurrentCursor = function() {
return this.cursors[this.cursors.length-1];
}
Cursor.prototype.refreshCursor = function() {
var type = this.getCurrentCursor();
if( !type ) type = '';
var specialCursor = this.specialCursors.get(type);
var complementType = this.specialComplements.get(type);
if( specialCursor ) {
$("viewer").style.cursor = complementType;
this.isTrailing = true;
this.imgElement.setAttribute('src', specialCursor);
Element.show(this.imgElement);
Event.observe(document, 'mousemove', this.onMoveCallback, true);
}
else {
this.isTrailing = false;
Element.hide(this.imgElement);
if (!this.isWaiting()) {
$("viewer").style.cursor = type;
}
Event.stopObserving(document, 'mousemove', this.onMoveCallback, true);
}
}
Cursor.prototype.beginWait = function() {
this.setCursor('wait');
}
Cursor.prototype.endWait = function() {
this.unsetCursor('wait');
}
Cursor.prototype.isWaiting = function() {
return this.getCurrentCursor() == "wait";
}
Cursor.prototype.onMouseMove = function(event) {
if( !this.isTrailing )
return;
browser.setLeft(this.imgElement, event.clientX+10);
browser.setTop(this.imgElement, event.clientY);
}
Cursor.prototype.onMouseOut = function(event) {
if( !this.isTrailing )
return;
browser.setLeft(this.imgElement, -100);
}
function displayDialog( dialogID ) {
$( 'entireOverlay' ).style.display = 'block';
$( dialogID ).style.display = 'block';
if(browser.ie) {
$A([$('searchCombo'), $('annotationFilterCombo'), $('mbsSort')]).each(function(e) {
e.disabled = true;
browser.setBackgroundColor(e,'#A19C98');
});
}
reader.sidebar.centerDialog( dialogID );
}
function hideDialog( dialogID ) {
$( 'entireOverlay' ).style.display = 'none';
$( dialogID ).style.display = 'none';
$('errorText').innerHTML = '';
if(browser.ie) {
$A([$('searchCombo'), $('annotationFilterCombo'), $('mbsSort')]).each(function(e) {
e.disabled = false;
browser.setBackgroundColor(e,'white');
});
}
}
var errorDialogCallback = null;
function displayErrorDialog( message, width, errorCallback ) {
extras.hideLoader();
errorDialogCallback = errorCallback;
if( width ) {
browser.setWidth( $('generalErrorDialog'), width );
}
$('errorText').innerHTML = message;
displayDialog( 'generalErrorDialog' );
}
function hideErrorDialog() {
browser.setWidth( $('generalErrorDialog'), 400 );
hideDialog( 'generalErrorDialog' );
if (errorDialogCallback) {
eval(errorDialogCallback);
}
}
var messageDialogCallback = null;
function displayMessageDialog( optionsOverride ) {
var options = {
width:      350,
title:      " Important",
titleImg:   'x-locale/common/icons/exclamation-error-red',
type:       "message",
okImg:      'digital/sitbv3/general/close_button'
};
if( optionsOverride )
Object.extend(options, optionsOverride);
displayGenericDialog( options );
}
function displayGenericDialog( optionsOverride ) {
var options = {
width:      350,
title:      "",
titleImg:   null,
titleStyle: "color: #CC6600; font: bold 12px Verdana, Arial;",
titleHR:    false,
showClose:  false,
message:    "",
messageStyle: 'font: 12px Verdana, Arial;',
type:       "message",
okImg:      'digital/sitbv3/general/close_button',
cancelImg:  'digital/sitbv3/general/cancel_button'
};
if( optionsOverride ) {
Object.extend( options, optionsOverride );
}
if( options.width )
browser.setWidth( $('genericDialog'), options.width );
var content = options.message;
var titleArea = '';
if( options.titleImg ) {
titleArea += '<img src="' + Config.getGeneralMediaURL(options.titleImg) + '"/>'
}
if( options.title ) {
titleArea += '<span style="'+ options.titleStyle +'">' + options.title + '</span>';
}
if( options.showClose ) {
titleArea += '<img style="position:absolute; right:5px; top: 2px; cursor: pointer;" onClick="cancelGenericDialog();" src="'+ Config.getGeneralMediaURL('digital/sitbv3/general/close_x') +'"/>';
}
if( options.titleHR ) {
titleArea += '<hr noshade size="1"/>';
}
$('genericDialogTitle').innerHTML = titleArea;
$('genericDialogText').innerHTML = '<span style="'+options.messageStyle+'">' + content + '</span>';
var buttonHTML = '<img src="'+ Config.getGeneralMediaURL(options.okImg) +'" onClick="okGenericDialog();" style="cursor: pointer;" alt="OK"/>';
if( options.type == 'confirm' ) {
buttonHTML += '&nbsp;&nbsp;<img src="'+  Config.getGeneralMediaURL(options.cancelImg) +'" style="cursor: pointer;" onClick="cancelGenericDialog();" alt="Cancel"/>';
}
$('genericDialogButton').innerHTML = buttonHTML;
dialogOnOK = options.okAction;
dialogOnCancel = options.cancelAction;
displayDialog( 'genericDialog' );
}
var dialogOnOK = null;
var dialogOnCancel = null;
var dialogOptions = null;
function okGenericDialog() {
hideDialog( 'genericDialog' );
if( dialogOnOK ) {
dialogOnOK();
dialogOnOK = null;
}
}
function cancelGenericDialog() {
hideDialog( 'genericDialog' );
if( dialogOnCancel ) {
dialogOnCancel();
dialogOnCancel = null;
}
}
function showCopyDialog() {
var showDialog = userSettings.get('showCopyDialog');
if( showDialog == 'true' || showDialog == true ) {
displayDialog( 'copyDialog' );
}
}
function closeCopyDialog() {
var copyDialogCheckbox = document.getElementById('copyDialogCheckbox');
if( copyDialogCheckbox.checked )
{
userSettings.set('showCopyDialog', false);
userSettings.save();
}
hideDialog( 'copyDialog' );
}
function Extras() {
this.div = null;
this.stripeDiv = null;
}
Object.extend(Extras.prototype, SmartObject.prototype);
Extras.prototype.init = function() {
this.stripeDiv = $('infoStripe');
Event.observe($('closeInfoStripe'), 'click', this.hideStripe.bind(this), false );
}
Extras.prototype.showLoader = function() {
$('loader').style.display = 'block';
cursor.beginWait();
}
Extras.prototype.hideLoader = function() {
$('loader').style.display = 'none';
cursor.endWait();
}
Extras.prototype.createTable = function(parentOfDiv, name, numRows, numColumns, borderWidth) {
var daDiv = document.createElement("div");
parentOfDiv.appendChild(daDiv);
browser.setNodeAttribute(daDiv, "id", name);
var daTable = document.createElement("table");
daDiv.appendChild(daTable);
browser.setNodeAttribute(daTable, "id", name + "_table");
browser.setNodeAttribute(daTable, "border", borderWidth);
browser.setNodeAttribute(daTable, "cellspacing", "0");
browser.setNodeAttribute(daTable, "cellpadding", "0");
var daTHead = document.createElement("thead");
browser.setNodeAttribute(daTHead, "id", name + "_thead");
daTable.appendChild(daTHead);
var daTBody = document.createElement("tbody");
browser.setNodeAttribute(daTBody, "id", name + "_tbody");
daTable.appendChild(daTBody);
var daArray = Array();
for (var row = 0; row < numRows; row++) {
var daTr = document.createElement("tr");
browser.setNodeAttribute(daTr, "id", name + "_tr");
daTBody.appendChild(daTr);
daArray[row] = Array();
for (var col = 0; col < numColumns; col++) {
var daTd = document.createElement("td");
browser.setNodeAttribute(daTd, "id", name + "_td");
daTr.appendChild(daTd);
daArray[row][col] = daTd;
}
}
return daArray;
}
Extras.prototype.hideStripe = function() {
browser.setVisibility(this.stripeDiv, 'hide');
}
Extras.prototype.setStripeWidth = function(w) {
browser.setWidth(this.stripeDiv, w);
}
Extras.helpPopUp = function(url) {
window.open(url,'AmazonHelp','width=820,height=520,resizable=1,scrollbars=1');
return false;
}
Highlight = function (annotationManager, data, isNew) {
if( isNew )
data.deltaX = 20;
Annotation.call(this, annotationManager, annotationManager.HIGHLIGHT, data, isNew);
this.indicatorObj = undefined;
}
Highlight.NOOVERLAP     = 0;
Highlight.OVERLAPS      = 1;
Highlight.WITHIN        = 2;
Highlight.WITHIN_EDGE   = 4;
Highlight.CONTAINS      = 8;
Highlight.EQUALS        = 16;
Highlight.STICKS        = 32;
Highlight.prototype = new Annotation();
Highlight.prototype.parent = Annotation.prototype;
function pad(x, place) {
var a = "" + x;
var s = "";
for (var ii=a.length; ii<=place; ii++)
s += "0";
return s + x;
}
Highlight.prototype.setIndicatorObj = function (obj) {
this.indicatorObj = obj;
}
Highlight.prototype.getStartSequenceID = function() {
return this.getStartPage() + pad(this.getStartWord(), 6);
}
Highlight.prototype.getEndSequenceID = function() {
return this.getEndPage() + pad(this.getEndWord(), 6);
}
Highlight.prototype.getIndicatorObj = function () {
return this.indicatorObj;
}
Highlight.prototype.hide = function() {
if( this.indicatorObj ) this.indicatorObj.hide();
this.parent.hide.call(this);
}
Highlight.prototype.show = function() {
if( this.getIndicatorObj() == undefined ) {
var type = this.isOwner ? Indicator.HIGHLIGHT_USER : Indicator.HIGHLIGHT_OTHER;
this.setIndicatorObj( new Indicator(this.annotationManager.reader, type,
this.startPage, this.startWord) );
this.indicatorObj.setEnd( this.endPage, this.endWord );
}
_a=0;
this.indicatorObj.show();
this.parent.show.call(this);
}
Highlight.prototype.refresh = function() {
if( this.indicatorObj != undefined )
this.indicatorObj.refresh();
this.parent.refresh.call(this);
}
Highlight.prototype.clean = function () {
if( this.indicatorObj ) {
this.indicatorObj.destroy();
this.indicatorObj = null;
}
this.parent.clean.call(this);
}
Highlight.prototype.setStart = function (startPage, startWord) {
if( startPage != this.endPage ) {
var pageObj = this.annotationManager.reader.pageManager.getPageObj(this.startPage);
var boxes = pageObj.getBoxes();
if( startWord >= boxes.length ) {
startPage = this.endPage;
startWord = 0;
}
}
this.indicatorObj.setStart(startPage, startWord);
this.startPage = startPage;
this.startWord = startWord;
}
Highlight.prototype.setEnd = function (endPage, endWord) {
if( endWord < 0 && endPage != this.startPage ) {
var pageObj = this.annotationManager.reader.pageManager.getPageObj(this.startPage);
var boxes = pageObj.getBoxes();
endWord = boxes.length-1;
if( endPage == this.attachedPage )
this.bubble.hide();
endPage = this.startPage;
}
this.indicatorObj.setEnd(endPage, endWord);
this.endPage   = endPage;
this.endWord   = endWord;
}
Highlight.prototype.overlap = function (annotation) {
var start0 = this.getStartSequenceID();
var end0 = this.getEndSequenceID();
var start1 = annotation.getStartSequenceID();
var end1 = annotation.getEndSequenceID();
if (end0 < start1 || end1 < start0) {
var beforeStart0 = this.getStartPage() + pad(this.getStartWord() - 1, 6);
var afterEnd0 = this.getEndPage() + pad(this.getEndWord() + 1, 6);
if (start1 == afterEnd0 || end1 == beforeStart0)
return Highlight.STICKS;
else
return Highlight.NOOVERLAP;
}
if (start0 == start1 && end0 == end1) {
return Highlight.EQUALS;
}
if (start0 < start1 && start1 <= end0 && end0 < end1 ||
start1 < start0 && start0 <= end1 && end1 < end0) {
return Highlight.OVERLAPS;
}
if (start0 <= start1 && end0 >= end1) {
return Highlight.CONTAINS;
}
if (start0 == start1 || end0 == end1) {
return Highlight.WITHIN_EDGE;
}
return Highlight.WITHIN;
}
Highlight.prototype.subtract = function(highlight) {
this.show();
var start0 = this.getStartSequenceID();
var end0 = this.getEndSequenceID();
var start1 = highlight.getStartSequenceID();
var end1 = highlight.getEndSequenceID();
if (end0 < start1 || end1 < start0)
return;
if (start0 >= start1) {
this.setStart(highlight.getEndPage(), highlight.getEndWord() + 1);
}
else {
this.setEnd(highlight.getStartPage(), highlight.getStartWord() - 1);
}
this.setChanged();
this.pickAttachedPage();
this.bubble.show();
}
Highlight.prototype.add = function(highlight) {
this.show();
if (highlight.getStartSequenceID() < this.getStartSequenceID())
this.setStart(highlight.getStartPage(), highlight.getStartWord());
if (highlight.getEndSequenceID() > this.getEndSequenceID())
this.setEnd(highlight.getEndPage(), highlight.getEndWord());
this.setChanged();
}
Highlight.prototype.getCornerUR = function() {
return this.indicatorObj.getCornerUR( this.getAttachedPage() );
}
Highlight.prototype.getLineEnd = function() {
return this.indicatorObj.getLineEnd( this.getAttachedPage() );
}
Highlight.prototype.getLineTop = function() {
var bubbleHeight = AnnotationControl.DEFAULT_HEIGHT + 30;
return this.indicatorObj.getLineTop( this.getAttachedPage() ) - bubbleHeight;
}
Highlight.prototype.getLineBottom = function() {
return this.indicatorObj.getLineBottom( this.getAttachedPage() );
}
Highlight.prototype.getClosestPoint = function(x, y) {
return this.indicatorObj.getClosestPoint(x, y, this.getAttachedPage());
}
function Indicator(reader, type, pageStart, wordStart) {
this.id = Indicator.NEXT_ID;
Indicator.NEXT_ID++;
this.page = pageStart;
this.type = type;
this.reader = reader;
this.pageStart      = pageStart;
this.pageEnd        = this.pageStart;
this.wordStart      = wordStart;
this.wordEnd        = this.wordStart;
this.page0 = this.pageStart;
this.start0 = this.wordStart;
this.end0 = this.wordStart;
this.page1 = undefined;
this.hidden0 = false;
this.hidden1 = false;
try {
this.setRangeType(this.pageStart, this.wordStart, this.pageEnd, this.wordEnd, 1);
} catch(e) {
if( e.isType('PageNotReady') ) {
this.hidden0 = true;
_a=0;
} else { throw e; }
}
}
Indicator.NONE              = 0;
Indicator.SELECTION         = 1;
Indicator.HIGHLIGHT_OTHER   = 2;
Indicator.HIGHLIGHT_USER    = 3;
Indicator.SITB              = 4;
Indicator.MAX_TYPES         = 5;
Indicator.COLORS = new Object();
Indicator.COLORS[Indicator.NONE]              = "00ffff";
Indicator.COLORS[Indicator.SELECTION]         = "A09E9D";
Indicator.COLORS[Indicator.HIGHLIGHT_OTHER]   = "D7D7D5";
Indicator.COLORS[Indicator.SITB]              = "FD9002";
Indicator.ANNOTATION_COLORS = {
green: '8FFC56',
pink:  'F6A6CB',
gray:  'D7D7D5',
blue:  '95DAFC',
gold:  'F9ED63'
}
Object.extend(Indicator.prototype, SmartObject.prototype);
Indicator.prototype.parent = SmartObject.prototype;
Indicator.NEXT_ID = 1;
Indicator.isIndicatorDiv = function(element) {
return (element && element.id.indexOf("box_") == 0);
}
Indicator.getColor = function(type) {
if( type == Indicator.HIGHLIGHT_USER ) {
return Indicator.ANNOTATION_COLORS[userSettings.get("annotationColor")];
} else {
return Indicator.COLORS[type];
}
}
Indicator.prototype.getID = function() {
return this.id;
}
Indicator.prototype.destroy = function() {
this.hide();
this.parent.destroy.call(this);
}
Indicator.prototype.show = function() {
if( this.resetPage0 ) {
this.refreshBoundaries();
}
try {
if( this.hidden0 ) {
this.setRangeType( this.page0, this.start0, this.page0, this.end0, 1 );
this.hidden0 = false;
}
} catch(e) {
if( !e.isType('PageNotReady') ) { throw e; };
}
try {
if( this.hidden1 && this.page1 ) {
_a=0;
this.setRangeType( this.page1, this.start1, this.page1, this.end1, 1 );
this.hidden1 = false;
}
} catch(e) {
if( !e.isType('PageNotReady') ) { throw e; };
}
}
Indicator.prototype.hide = function() {
try {
if( !this.hidden0 ) {
this.setRangeType( this.page0, this.start0, this.page0, this.end0, -1 );
this.hidden0 = true;
}
} catch(e) {
if( !e.isType('PageNotReady') ) throw e;
}
try {
if( !this.hidden1 && this.page1 ) {
this.setRangeType( this.page1, this.start1, this.page1, this.end1, -1 );
this.hidden1 = true;
}
} catch(e) {
if( !e.isType('PageNotReady') ) throw e;
}
}
Indicator.prototype.refresh = function() {
try {
this.setRangeType(this.pageStart, this.wordStart, this.pageEnd, this.wordEnd, 0);
} catch(e) {
if( !e.isType('PageNotReady') ) throw e;
}
}
Indicator.prototype.setType = function(type) {
this.type = type;
}
Indicator.prototype.refreshBoundaries = function() {
this.resetPage0 = false;
if( this.pageStart == this.pageEnd ) {
this.page0 = this.pageStart;
this.start0 = this.wordStart;
this.end0 = this.wordEnd;
this.page1 = undefined;
}
else if( this.pageStart < this.pageEnd ) {
this.page0 = this.pageStart;
this.start0 = this.wordStart;
try {
var boxes = this.reader.pageManager.getPageObj(this.page0).getBoxes();
this.end0 = boxes.length - 1;
} catch(e) {
if( !e.isType('DataNotReady') ) throw e;
this.resetPage0 = true;
}
this.page1 = this.pageEnd;
this.start1 = 0;
this.end1 = this.wordEnd;
}
}
Indicator.prototype.setStart = function(pageStart, wordStart) {
if( pageStart == this.pageStart && wordStart == this.wordStart )
return;
try {
this.setRangeType( pageStart, wordStart, this.pageStart, this.wordStart-1, 1 );
this.setRangeType( this.pageStart, this.wordStart, pageStart, wordStart-1, -1 );
} catch(e) {
if( e.isType('PageNotReady') ) {
this.hidden0 = true;
_a=0;
} else { throw e; }
}
this.pageStart = pageStart;
this.wordStart = wordStart;
this.refreshBoundaries();
}
Indicator.prototype.setEnd = function(pageEnd, wordEnd) {
if( pageEnd == this.pageEnd && wordEnd == this.wordEnd )
return;
try {
this.setRangeType( this.pageEnd, this.wordEnd+1, pageEnd, wordEnd, 1 );
this.setRangeType( pageEnd, wordEnd+1, this.pageEnd, this.wordEnd, -1 );
} catch(e) {
if( e.isType('EndPageNotReady') ) {
this.hidden1 = true;
_a=0;
} else if( e.isType('PageNotReady') ) {
this.hidden0 = true;
} else { throw e; }
}
this.pageEnd = pageEnd;
this.wordEnd = wordEnd;
this.refreshBoundaries();
}
Indicator.prototype.setRangeType = function(rangeStartPage, rangeStartWord, rangeEndPage, rangeEndWord, delta) {
var samePage = (rangeStartPage == rangeEndPage);
if( !(samePage && rangeStartWord <= rangeEndWord) &&
rangeStartPage > rangeEndPage )
return;
var pageManager = this.reader.pageManager;
if( samePage ) {
pageManager.changeBoxTypeRef( rangeStartPage, rangeStartWord, rangeEndWord, this.type, delta );
} else {
var exceptionToThrow = null;
try {
var pageObj = this.reader.pageManager.getPageObj(rangeStartPage);
var lastWord = pageObj.getBoxes().length - 1;
pageManager.changeBoxTypeRef( rangeStartPage, rangeStartWord, lastWord, this.type, delta );
} catch(e) {
if( e.isType('PageNotReady') ) {
exceptionToThrow = e;
} else {
throw e;
}
}
try {
pageManager.changeBoxTypeRef( rangeEndPage, 0, rangeEndWord, this.type, delta );
} catch(e) {
if( e.isType('PageNotReady') ) {
throw new Exception("", 'EndPageNotReady');
} else {
throw e;
}
}
if( exceptionToThrow ) {
throw exceptionToThrow;
}
}
}
Indicator.prototype.includesBox = function(boxID, page) {
if( this.page0 != page && this.page1 != page )
return false;
try {
var pageObj0 = this.reader.getDisplayedPage(this.page0);
var pageBoxes = pageObj0.getBoxes();
for( var i=this.start0; i<=this.end0; i++ )
{
if( pageBoxes[i] && pageBoxes[i].itemID == boxID )
return true;
}
} catch(e) {
if( !e.isType('PageNotDisplayed') ) throw e;
}
try {
if( !this.page1 ) return false;
var pageObj1 = this.reader.getDisplayedPage(this.page1);
pageBoxes = pageObj1.getBoxes();
for( var i=this.start1; i<=this.end1; i++ )
{
if( pageBoxes[i] && pageBoxes[i].itemID == boxID )
return true;
}
} catch(e) {
if( !e.isType('PageNotDisplayed') ) throw e;
}
return false;
}
Indicator.prototype.getType = function() {
return this.type;
}
Indicator.prototype.getVisibility = function() {
return !this.hidden0;
}
Indicator.prototype.getPageStart = function() {
return this.page0;
}
Indicator.prototype.getPageEnd = function() {
if (this.page1 == undefined) {
return this.page0;
} else {
return this.page1;
}
}
Indicator.prototype.getWordStart = function() {
return this.start0;
}
Indicator.prototype.getWordEnd = function() {
if (this.page1 == undefined) {
return this.end0;
} else {
return this.end1;
}
}
Indicator.prototype.getCornerUR = function( basePage ) {
var pageObj = this.reader.getDisplayedPage( basePage );
var pageBoxes = pageObj.getBoxes();
var pageRows = pageObj.rows;
var startWord = (basePage == this.page0) ? this.start0 : this.start1;
_a=0;
}
Indicator.prototype.getClosestPoint = function( x, y, basePage ) {
var pageManager = this.reader.pageManager;
var rowPageNum = null;
var closestRow = null;
var minDist = 999999;
var pageResult = null;
var yMin = 999999;
var yMax = 0;
var heightOffset = 0;
var targetPage = null;
var pagesToLook = [ this.page0 ];
if( this.page1 && this.page1 != this.page0 ) {
pagesToLook.push( this.page1 );
}
pagesToLook.each( (function(pageNum) {
try {
if( basePage == pageNum ) {
heightOffset = 0;
} else if( basePage == this.page0 ) {
heightOffset = this.reader.getDisplayedPage(this.page0).getHeight();
} else if( basePage == this.page1 ) {
heightOffset = -this.reader.getDisplayedPage(this.page1).getHeight();
}
pageResult = this.getClosestRowOnPage( pageNum, x, y - heightOffset );
if( minDist < pageResult[1] ) {
throw $break;
}
closestRow = pageResult[0];
minDist = pageResult[1];
rowPageNum = pageNum;
yMax = closestRow.yMax + heightOffset;
yMin = closestRow.yMin + heightOffset;
if( minDist == 0 ) {
throw $break;
}
} catch(e) {
if( e == $break || e == $continue ) throw e;
else if( !e.isType('PageNotDisplayed') && !e.isType('BoxNotReady') ) throw e;
}
}).bind(this) );
if( !closestRow ) {
_a=0;
_a=0;
return null;
}
var yPoint = y;
if( y > yMax ) yPoint = yMax;
if( y < yMin ) yPoint = yMin;
var pageObj = this.reader.getDisplayedPage( rowPageNum );
var boxes = pageObj.getBoxes();
var startWord = (rowPageNum == this.page0) ? this.start0 : this.start1;
var endWord = (rowPageNum == this.page0) ? this.end0 : this.end1;
var xMin = closestRow.xMin;
var xMax = closestRow.xMax;
var xPoint = x;
if( pageObj.getBoxes()[startWord].itemID > closestRow.columns[0].itemID )
xMin = pageObj.getBoxes()[startWord].left;
if( pageObj.getBoxes()[endWord].itemID < closestRow.columns[closestRow.columns.length-1].itemID )
xMax = pageObj.getBoxes()[endWord].left + pageObj.getBoxes()[endWord].width;
if( xPoint < xMin ) xPoint = xMin;
if( xPoint > xMax ) xPoint = xMax;
return [xPoint, yPoint];
}
Indicator.prototype.getClosestRowOnPage = function(pageNum, x, y) {
var closest = null;
var pageObj = this.reader.getDisplayedPage(pageNum);
var rows = pageObj.rows;
var boxes = pageObj.getBoxes();
var startRow;
var endRow;
if( pageNum == this.page0 ) {
startRow = boxes[this.start0].row;
endRow = boxes[this.end0].row;
} else if( pageNum == this.page1 && this.page1 ) {
startRow = boxes[this.start1].row || 0;
endRow = boxes[this.end1].row;
} else {
_a=0;
return null;
}
var minDist = 999999;
for( var i = startRow; i <= endRow; i++ ) {
var row = rows[i];
if( closest == null && y <= row.yMin ) {
closest = row;
minDist = row.yMin - y;
break;
} else if( y > row.yMin && y < row.yMax ) {
closest = row;
minDist = 0;
break;
} else if( y >= row.yMax ) {
closest = row;
minDist = y - row.yMax;
}
}
return [closest, minDist];
}
Indicator.prototype.eachBox = function( iterator ) {
var pageObj = this.reader.getDisplayedPage(this.page0);
for( var i=this.start0; i<this.end0; i++ ) {
try {
iterator( pageObj.getBoxes()[i], i );
} catch( e ) {
if( e == $continue ) continue;
else if( e == $break ) break;
else throw e;
}
}
if( !this.page1 ) return;
pageObj = this.reader.getDisplayedPage(this.page1);
for( var i=this.start1; i<this.end1; i++ ) {
try {
iterator( pageObj.getBoxes()[i], i );
} catch( e ) {
if( e == $continue ) continue;
else if( e == $break ) break;
else throw e;
}
}
}
Indicator.prototype.getLineEnd = function( basePage ) {
var pageObj = this.reader.getDisplayedPage(basePage);
var startWord = (basePage==this.page0) ? this.start0 : this.start1;
xMax = pageObj.getRows()[pageObj.getBoxes()[startWord].row].xMax;
return xMax;
}
Indicator.prototype.getLineTop = function( basePage ) {
var pageObj = this.reader.getDisplayedPage(basePage);
var startWord = (basePage==this.page0) ? this.start0 : this.start1;
yMin = pageObj.getRows()[pageObj.getBoxes()[startWord].row].yMin;
return yMin;
}
Indicator.prototype.getLineBottom = function( basePage ) {
var pageObj = this.reader.getDisplayedPage(basePage);
var endWord = (basePage==this.page0) ? this.end0 : this.end1;
yMax = pageObj.getRows()[pageObj.getBoxes()[endWord].row].yMax;
return yMax;
}
function showHideBookmark()
{
var b = $("bookmark");
var v = b.style.visibility;
if (v != "visible") {
b.style.visibility = "visible";
}
else {
b.style.visibility = "hidden";
}
}
function showHidePalettes()
{
var layoutSidebar = $("layoutSidebar");
var display   = layoutSidebar.style.display;
var image     = $("showHidePalettesImg");
if (display != "block" && display != "") {
image.src               = Config.getGeneralMediaURL('digital/sitbv3/general/showHide_palettes_open');
layoutSidebar.style.display = "block";
$("leftColumn_check").src = Toolbar.IMG_CHECK;
}
else {
image.src               = Config.getGeneralMediaURL('digital/sitbv3/general/showHide_palettes_closed');
layoutSidebar.style.display = "none";
$("leftColumn_check").src = Toolbar.IMG_SPACER;
}
reader.onWindowResize();
}
function changeTab(tabName)
{
var currentTab = $('currentTab');
var previousTab = currentTab.value;
if( previousTab != tabName && !$(tabName + 'Tab').src.match('_inactive') ||
$(tabName + 'Tab').src.match('_off') )
{
currentTab.value = tabName;
var tocTab         = $( "tocTab" );
var annotationsTab = $( "annotationsTab" );
var toc            = $( "tabbedContentTOC" );
var annotations    = $( "tabbedContentAnnotations" );
var filter         = $( "annotationFilter" );
if( tabName == "toc" )
{
tocTab.src         = Config.getGeneralMediaURL('digital/sitbv3/tabs/sections_on');
annotationsTab.src = Config.getGeneralMediaURL('digital/sitbv3/tabs/annotations_off');
annotations.style.display = "none";
filter.style.display = "none";
toc.style.display = "block";
}
else if( tabName == "annotations" )
{
tocTab.src         = Config.getGeneralMediaURL('digital/sitbv3/tabs/sections_off');
annotationsTab.src = Config.getGeneralMediaURL('digital/sitbv3/tabs/annotations_on');
toc.style.display = "none";
annotations.style.display = "block";
filter.style.display = "block";
reader.annotationManager.annotationViewer.filterAnnotations();
}
reader.sidebar.resizeComponents();
}
}
function goToNextPage(src)
{
var p = $("pageImg");
var r = p.src = (src)
}
function changePageNumber(num)
{
var n = $("pageNumber");
var o = n.value = (num)
}
function getLivePageHeight()
{
if (window.innerHeight)
return window.innerHeight;
if (document.body.clientHeight)
return document.body.clientHeight;
}
function useLivePageHeight()
{
livePageHeight = getLivePageHeight();
$("pageLeft").style.height = livePageHeight + 'px';
$("pageRight").style.height = livePageHeight + 'px';
$("tabbedContentHolder").style.height = livePageHeight - 251 + 'px';
}
function changeTabs()
{
var c = $('contentsTab').src;
var b = $('bookmarksTab').src;
var h = $('highlightsTab').src;
var n = $('notesTab').src;
var t = $('tagsTab').src;
}
function MM_preloadImages() {
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) {
var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() {
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_showHideLayers() {
var i,p,v,obj,args=MM_showHideLayers.arguments;
for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
obj.visibility=v; }
}
function MM_changeProp(objName,x,theProp,theValue) {
var obj = MM_findObj(objName);
if (obj && (theProp.indexOf("style.")==-1 || obj.style)) {
if (theValue == true || theValue == false) {
if (theValue != '')
eval("obj." + theProp + "=" + theValue);
else _a=0;
} else {
eval("obj."+theProp+"='"+theValue+"'");
}
}
}
ListControl = function(parent, div) {
this.controlId = ListControl.NEXT_ID;
ListControl.NEXT_ID++;
this.div = div;
this.selectedIndex = -1;
this.selectedLi = null;
this.parent = parent;
this.justClicked = false;
var id = 'listcontrol_' + this.controlId;
this.div.innerHTML =
'<ul id="' + id + '" class="listcontrol_ul">' +
'</ul>';
this.ul = $(id);
this.hide();
Event.observe(this.ul, 'mouseup', this.onMouseSelect.bind(this), false);
Event.observe(this.ul, 'mouseover', this.onMouseOver.bind(this), false);
Event.observe(this.ul, 'mousedown', this.stopEvent.bind(this), false);
Event.observe(this.ul, 'click', this.stopEvent.bind(this), false);
Object.extend(this, new EventDispatcher());
}
Object.extend(ListControl.prototype, SmartObject.prototype);
ListControl.NEXT_ID = 1;
ListControl.prototype.refresh = function() {
if (this.data) {
var html = '';
for (var i = 0; i < this.data.length; i++) {
var id = 'listcontrol_' + this.controlId + '_' + i;
var line = this.data[i].escapeHTML().replace(/\s/g, "&nbsp;")
html += '<li id="' + id + '" value="' + i + '">' + line + '</li>';
}
this.ul.innerHTML = html;
}
else
this.ul.innerHTML = '';
}
ListControl.prototype.setData = function(data) {
this.selectedIndex = -1;
this.data = data;
this.refresh();
this.setSelectedIndex(data.length > 0 ? 0 : -1);
}
ListControl.prototype.getSelectedIndex = function() {
return this.selectedIndex;
}
ListControl.prototype.setSelectedIndex = function(newIndex) {
if (newIndex != this.selectedIndex) {
if (newIndex >= 0) {
var li = this.getLIElement(newIndex);
if (li)
li.className = "listcontrol_li_selected";
}
if (this.selectedIndex >= 0) {
var li = this.getLIElement(this.selectedIndex);
if (li)
li.className = "";
}
this.selectedIndex = newIndex;
}
}
ListControl.prototype.getLIElement = function(index) {
return $('listcontrol_' + this.controlId + '_' + index);
}
ListControl.prototype.getSelected = function() {
return this.data[this.selectedIndex];
}
ListControl.prototype.goDown = function() {
if (this.selectedIndex < this.data.length - 1)
this.setSelectedIndex(this.selectedIndex + 1);
}
ListControl.prototype.goUp = function() {
if (this.selectedIndex > 0)
this.setSelectedIndex(this.selectedIndex - 1);
}
ListControl.prototype.onMouseSelect = function(event) {
this.setSelectedIndex(Event.element(event).value);
this.parent.completeTag();
this.parent.tagsEdit.focus();
Event.stop(event);
}
ListControl.prototype.onMouseOver = function(event) {
var index = Event.element(event).value;
this.setSelectedIndex(index);
}
ListControl.prototype.hide = function() {
this.setData([]);
this.selectedIndex = -1;
this.div.style.visibility = "hidden";
}
ListControl.prototype.show = function() {
this.div.style.visibility = "visible";
}
ListControl.prototype.isHidden = function() {
return this.div.style.visibility == "hidden";
}
ListControl.prototype.isJustClicked = function() {
var res = this.justClicked;
this.justClicked = false;
return res;
}
ListControl.prototype.stopEvent = function(event) {
this.justClicked = true;
Event.stop(event);
}
Scroller = function(reader) {
this.reader = reader;
this.railDiv = null;
this.thumbDiv = null;
this.pageDiv = null;
this.posRailDiv = null;
this.posThumbDiv = null;
this.timer = null;
this.active = false;
this.clickY = 0;
this.delta = 0;
this.damper = 0;
this.pageOrder;
this.firstPage;
this.totalPages;
this.page;
this.init();
}
Scroller.frequency = 4;
Scroller.prototype.makePageOrder = function() {
var sortedList = $H(Config.getPageMap()).keys().sort(function(a,b) {
return (b < a) - (a < b);
});
this.pageOrder = new Array();
this.firstPage = sortedList[0];
this.totalPages = sortedList.length;
for(var i = 1; i < this.totalPages - 1; ++i) {
this.pageOrder[sortedList[i]] = new Array(sortedList[i-1],
sortedList[i+1],
i / this.totalPages);
}
this.pageOrder[sortedList[0]] = new Array(null, sortedList[1], 0);
this.pageOrder[sortedList[sortedList.length-1]] =
new Array(sortedList[sortedList.length-2], null, 1);
}
Scroller.prototype.init = function() {
this.railDiv = $('vScrollerRail');
this.thumbDiv = $('vScrollerThumb');
this.pageDiv = $('vScrollerPage');
this.posRailDiv = $('vScrollerPosRail');
this.posThumbDiv = $('vScrollerPosThumb');
this.makePageOrder();
this.updateThumb(0);
Event.observe(this.thumbDiv, 'mousedown', this.activate.bind(this), false);
Event.observe(document, 'mousemove', this.onMouseMove.bind(this), true);
Event.observe(document, 'mouseup', this.deactivate.bind(this), false);
Event.observe(this.posRailDiv, 'mousedown', this.onClickPosRail.bind(this), false);
}
Scroller.prototype.onResize = function() {
var railHeight = document.body.clientHeight - browser.getAbsoluteTop(this.railDiv);
browser.setHeight(this.railDiv, railHeight);
browser.setTop(this.thumbDiv, (railHeight - browser.getHeight(this.thumbDiv)) / 2);
this.updatePosThumb(this.reader.GetCurrentPage());
}
Scroller.prototype.onClickPosRail = function(e) {
if(this.reader.permissions != 'SITBpaid') return;
var position = (e.clientY - browser.getAbsoluteTop(this.railDiv)) / this.posRailDiv.offsetHeight;
var pageIndex = Math.floor(position * this.totalPages);
this.page = this.firstPage;
this.pageJump(pageIndex);
this.leavePageMode();
}
Scroller.prototype.activate = function(e) {
if(this.reader.viewerType != "continuous") return;
this.clickY = e.clientY;
this.active = true;
this.damper = 0;
clearInterval(this.timer);
this.timer = window.setInterval(this.onTimer.bind(this), 200 / Scroller.frequency);
Event.stopBubble(e);
}
Scroller.prototype.deactivate = function(e) {
if(!this.active) return;
this.active = false;
clearInterval(this.timer);
this.leavePageMode();
this.page = null;
this.clickY = 0;
this.updateThumb(0);
}
Scroller.prototype.onMouseMove = function(e) {
if(this.active) this.updateThumb(e.clientY);
}
Scroller.prototype.updateThumb = function(y) {
var center = (this.railDiv.offsetHeight - this.thumbDiv.offsetHeight) / 2;
if(center > 0) {
this.delta = (Math.max(-1 * center, Math.min(center, y - this.clickY))) / center;
this.thumbDiv.style.top = center * (1 + this.delta);
}
}
Scroller.prototype.onTimer = function() {
var absDelta = Math.abs(this.delta);
if((absDelta > 0.5 || this.page != null) && this.reader.permissions == 'SITBpaid') {
this.damper++;
if (this.damper % Scroller.frequency != 0)
return;
if(this.page == null) this.page = this.reader.GetCurrentPage();
var direction = absDelta / this.delta;
var jumpSize = Math.ceil(Math.pow(2, 16 * (absDelta - 0.6)));
this.pageJump( direction * jumpSize );
this.pageDiv.innerHTML =
this.reader.pageManager.getLogicalPageNumber(this.page);
this.pageDiv.style.display = 'block';
this.pageDiv.style.top = this.thumbDiv.offsetTop + this.railDiv.offsetTop + 5;
this.pageDiv.style.left = this.railDiv.offsetLeft - this.pageDiv.clientWidth - 5;
} else {
var scroll = 200 * this.delta;
var viewer = this.reader.getViewer();
if( this.reader.viewerType != "continuous" ) {
throw new Exception("Scroller only works in continuous mode");
}
viewer.manualScroll(scroll);
}
}
Scroller.prototype.updatePosThumb = function(page) {
var range = this.posRailDiv.offsetHeight - this.posThumbDiv.offsetHeight;
var pageData = this.pageOrder[page];
if(range > 0 && pageData) {
this.posThumbDiv.style.top = range * pageData[2];
this.posThumbDiv.style.display = 'block';
} else {
this.posThumbDiv.style.display = 'none';
}
}
Scroller.prototype.onPageChange = function(e, pageObj) {
this.updatePosThumb(pageObj.getPageNum());
}
Scroller.prototype.pageJump = function(delta) {
var direction = (delta < 0) ? 0 : 1;
var newPage;
for(var i = 0; i < Math.abs(delta); ++i) {
newPage = this.pageOrder[this.page][direction];
this.page = (newPage != null) ? newPage: this.page;
this.updatePosThumb(this.page);
}
}
Scroller.prototype.leavePageMode = function() {
if(this.page != null) {
this.reader.DisplayPage(this.page, '');
this.page = null;
}
this.pageDiv.style.display = 'none';
}
Search = function(reader) {
this.keywords = null;
this.mode = Search.MODE_UNKNOWN;
this.reader = reader;
this.asin = reader.asin;
this.active = false;
this.modeString = new Array( 5 );
this.modeString[Search.MODE_BOOK]      = 'Text of this book';
this.modeString[Search.MODE_BOOKMARK]  = 'Your Bookmarks';
this.modeString[Search.MODE_HIGHLIGHT] = 'Your Highlighted Text';
this.modeString[Search.MODE_TAG]       = 'Tags';
this.modeString[Search.MODE_YOURTAG]   = 'Your Tags';
this.modeString[Search.MODE_NOTE]      = 'Your Notes';
this.returnLink =
'<a id="return_to_book" href="#" onClick="reader.search.hideSearch(true)">Return to book</a>';
this.sitb_tokens = new Object();
this.reader.pageManager.addListener('pageLoading', this, 'onPageLoading');
this.reader.pageManager.addListener('pageUnload', this, 'onPageUnload');
this.reader.pageManager.addListener('pageLoad', this, 'onPageLoad');
this.first_result = true;
this.indicators = new Array();
this.highlightShown = new Object();
}
Object.extend(Search.prototype, SmartObject.prototype);
Search.MODE_UNKNOWN     = -1;
Search.MODE_BOOK        = 0;
Search.MODE_BOOKMARK    = 1;
Search.MODE_HIGHLIGHT   = 2;
Search.MODE_TAG         = 3;
Search.MODE_YOURTAG     = 4;
Search.MODE_NOTE        = 5;
Search.prototype.go = function() {
this.keywords = document.getElementsByName('field-keywords')[0].value.trim();
this.asin     = this.reader.asin;
var searchOption = $("searchCombo").value;
this.deactivate();
this.active = true;
this.first_result = true;
if( this.keywords.length == 0 || searchOption.length == 0 )
{
}
else if( searchOption == 'stripsearch' )
{
this.stripSearch(1);
}
else if( searchOption == 'a9search' ) {
window.location = 'http://www.a9.com/' + this.keywords;
}
else if( searchOption == 'bookmarks' ) {
this.searchMyBookmarks();
}
else if( searchOption == 'highlights' ) {
this.searchMyHighlights();
}
else if( searchOption == 'notes' ) {
this.searchMyNotes();
}
else if( searchOption == 'tags' ) {
this.searchMyTags();
}
else if( searchOption == 'medialibrary' ) {
window.location = Config.getRootURL() + '/gp/library/?category=book&queryText=' + this.keywords;
}
else {
var searchForm = $('searchForm');
browser.setNodeAttribute(searchForm, 'action', $('searchFormAction').value);
searchForm.submit();
}
}
Search.prototype.getTokens = function( pnum ) {
var key = pnum + '_' + this.reader.GetZoom();
return this.sitb_tokens[key];
}
Search.prototype.setTokens = function( pnum, zoom, tokens ) {
var key = pnum + '_' + zoom;
this.sitb_tokens[key] = tokens;
}
Search.prototype.isHighlightShown = function( pnum ) {
var key = pnum + '_' + this.reader.GetZoom();
return this.highlightShown[key];
}
Search.prototype.setHighlightShown = function( pnum, value ) {
var key = pnum + '_' + this.reader.GetZoom();
this.highlightShown[key] = value;
}
Search.prototype.tagSearch = function( keyword ) {
this.deactivate();
this.active = true;
this.first_result = true;
this.keywords = keyword;
this.searchTags();
}
Search.prototype.stripSearch = function(resultsPage) {
if( this.asin == undefined )
this.asin = this.reader.asin;
if( this.keywords == undefined )
this.keywords = document.getElementsByName('field-keywords')[0].value;
var url = Config.getReaderURL() +
'?resultsPage=' + resultsPage +
'&asin=' + this.asin +
'&keywords=' + this.keywords +
'&v=search-inside-only';
extras.showLoader();
var searchRequest = new JSONCom( browser );
searchRequest.setIsHTML( true );
searchRequest.setCallback( this.showSearchCallback.bind(this) );
searchRequest.setURL( url );
searchRequest.sendRequest();
}
Search.prototype.highlightKeywords = function(str) {
var keywordList = this.keywords.split(' ');
var replaced;
for( var i = 0; i < keywordList.length; i++ ) {
var regex = new RegExp( keywordList[i], 'gi' );
replaced = str.replace(regex, '<span class="keyword">'+keywordList[i]+'</span>');
}
return replaced;
}
Search.prototype.getSearchLinks = function() {
var links = new Array();
var modeDisplay = this.modeString[Search.MODE_BOOK];
if (this.mode == Search.MODE_BOOK)
links.push( modeDisplay );
else
links.push( '<a href="#" onClick="reader.search.stripSearch(1)">' + modeDisplay + '</a>' );
modeDisplay = this.modeString[Search.MODE_BOOKMARK];
if (this.mode == Search.MODE_BOOKMARK)
links.push( modeDisplay );
else
links.push( '<a href="#" onClick="reader.search.searchMyBookmarks()">' + modeDisplay + '</a>' );
modeDisplay = this.modeString[Search.MODE_HIGHLIGHT];
if (this.mode == Search.MODE_HIGHLIGHT)
links.push( modeDisplay );
else
links.push( '<a href="#" onClick="reader.search.searchMyHighlights()">' + modeDisplay + '</a>' );
modeDisplay = this.modeString[Search.MODE_NOTE];
if (this.mode == Search.MODE_NOTE)
links.push( modeDisplay );
else
links.push( '<a href="#" onClick="reader.search.searchMyNotes()">' + modeDisplay + '</a>' );
modeDisplay = this.modeString[Search.MODE_TAG];
if (this.mode == Search.MODE_TAG)
links.push( modeDisplay );
else
links.push( '<a href="#" onClick="reader.search.searchTags()">' + modeDisplay + '</a>' );
return links.join( ' | ' );
}
Search.prototype.searchMyBookmarks = function() {
this.mode = Search.MODE_BOOKMARK;
var annotationList = this.reader.annotationManager.getAllAnnotations();
var searchObj = new AnnotationSearch(annotationList);
var res = searchObj.searchMyBookmarks(this.keywords);
res.sort(this.sortAnnotationByPage.bind(this));
this.showSearch(this.buildSearchResultHTML(res));
}
Search.prototype.searchMyHighlights = function() {
this.mode = Search.MODE_HIGHLIGHT;
var annotationList = this.reader.annotationManager.getAllAnnotations();
var searchObj = new AnnotationSearch(annotationList);
var res = searchObj.searchMyHighlights(this.keywords);
res.sort(this.sortAnnotationByPage.bind(this));
this.showSearch(this.buildSearchResultHTML(res));
}
Search.prototype.searchMyNotes = function() {
this.mode = Search.MODE_NOTE;
var annotationList = this.reader.annotationManager.getAllAnnotations();
var searchObj = new AnnotationSearch(annotationList);
var res = searchObj.searchMyNotes(this.keywords);
res.sort(this.sortAnnotationByPage.bind(this));
this.showSearch(this.buildSearchResultHTML(res));
}
Search.prototype.searchTags = function(keywords) {
if (keywords != undefined)
this.keywords = keywords;
this.mode = Search.MODE_TAG;
var annotationList = this.reader.annotationManager.getAllAnnotations();
var searchObj = new AnnotationSearch(annotationList);
var res = searchObj.searchAllTags(this.keywords);
res.sort(this.sortAnnotationByPage.bind(this));
this.showSearch(this.buildSearchResultHTML(res));
}
Search.prototype.searchMyTags = function(keywords) {
if (keywords != undefined)
this.keywords = keywords;
this.mode = Search.MODE_YOURTAG;
var annotationList = this.reader.annotationManager.getAllAnnotations();
var searchObj = new AnnotationSearch(annotationList);
var res = searchObj.searchMyTags(this.keywords);
res.sort(this.sortAnnotationByPage.bind(this));
this.showSearch(this.buildSearchResultHTML(res));
}
Search.prototype.searchTagsOnPage = function(keywords, pageNum) {
if (keywords != undefined) {
this.keywords = keywords.unescapeHTML();
}
var tag = this.keywords;
var annotationList = this.reader.annotationManager.annotationsList.get(pageNum);
var res = new Array();
annotationList.each( (function(annotation) {
var tagsList = annotation.getTags().split(",");
if (tagsList != "" && tagsList != undefined) {
for (var i = 0; i < tagsList.length; i++) {
if (tagsList[i].trim() == tag.trim()) {
res.push(annotation);
break;
}
}
}
}) );
res.sort(this.sortAnnotationByPage.bind(this));
this.showSearch(this.buildSearchTagsOnPageHTML(res, pageNum));
}
Search.prototype.buildSearchResultHTML = function(results) {
var title = (results.length > 0 ? results.length : 'No') +
' references to <span class="keyword">' + this.keywords +
'</span> in ' + this.modeString[this.mode];
html =
'<div id="excerpt-view" style="width: 600px">' +
'<p class="title">' + title + '</p>';
if (results.length > 0) {
html +=
'<p>' + this.returnLink + '</p><ul class="searchResults_ul">';
for (var i = 0; i < results.length; i++) {
var pageNumber = this.reader.pageManager.getLogicalPageNumber( results[i].startPage );
html += '<li>';
var eventLink = "reader.DisplayPage('" + results[i].startPage + "');" +
"reader.fireEvent('popUpAnnotation','" + results[i].startPage + "','" + results[i].getID() + "');";
switch (this.mode) {
case Search.MODE_NOTE:
html += '<a href="#" onClick="' + eventLink + '">Note on Page ' + pageNumber + '</a>:<br/>';
html += this.highlightKeywords(results[i].getNotes().escapeHTML());
break;
case Search.MODE_YOURTAG:
case Search.MODE_TAG:
if (results[i].getType() == results[i].BOOKMARK)
html += '<a href="#" onClick="' + eventLink + '">Bookmark on Page ' + pageNumber + '</a>:';
else
html += '<a href="#" onClick="' + eventLink + '">Highlighted text on Page ' + pageNumber + '</a>:';
var note = results[i].getNotes().escapeHTML();
if( note && note != "" ) {
html += "<br/>" + note;
}
var tags = results[i].getTags().split(/\s*,\s*/);
if( tags.length != 0 ) {
html += "<br/>";
}
html += "&nbsp;&nbsp;Tags: ";
var sep = "";
tags.each( (function(tag) {
html += sep + this.highlightKeywords(tag);
sep = ", ";
}).bind(this) );
break;
case Search.MODE_HIGHLIGHT:
html += '<a href="#" onClick="' + eventLink + '">On Page ' + pageNumber + '</a>:<br/>';
html += '...' + this.highlightKeywords(results[i].getRelatedContent().escapeHTML()) + '...';
break;
case Search.MODE_BOOKMARK:
html += '<a href="#" onClick="' + eventLink + '">Bookmark on Page ' + pageNumber + '</a>:<br/>';
html += '...' + this.highlightKeywords(results[i].getNotes().escapeHTML()) + '...';
break;
}
if( !results[i].isOwner && results[i].customerNameNoBadge != "" ) {
html += "<br/>By: " + results[i].customerNameNoBadge;
}
html += '</li>';
}
html += '</ul>';
}
html += '<p>' + this.returnLink + '</p></div>';
return html;
}
Search.prototype.buildSearchTagsOnPageHTML = function(results, pageNum) {
var title = (results.length > 0 ? results.length : 'No') +
' annotations with tag <span class="keyword">' + this.keywords +
'</span> on page ' + this.reader.pageManager.getLogicalPageNumber(pageNum);
var html =
'<div id="excerpt-view">' +
'<p class="title">' + title + '</p>';
if (results.length > 0) {
html += '<ul class="searchResults_ul">';
for (var i = 0; i < results.length; i++) {
var pageNumber = this.reader.pageManager.getLogicalPageNumber( results[i].startPage );
html += '<li>';
var pageLink = "reader.DisplayPage('" + results[i].startPage + "'); reader.fireEvent('popUpAnnotation','" + results[i].startPage + "','" + results[i].getDasID() + "');";
if (results[i].getType() == results[i].BOOKMARK)
html += '<a href="#" onClick="' + pageLink + '">Bookmark on Page ' + pageNumber + '</a>:<br/>';
else
html += '<a href="#" onClick="' + pageLink + '">Highlighted text on Page ' + pageNumber + '</a>:<br/>';
html += results[i].getNotes().escapeHTML();
html += '</li>';
}
html += '</ul>';
}
html += '<p>' + this.returnLink + '</p></div>';
return html;
}
Search.prototype.sortAnnotationByPage = function(obj1, obj2) {
if (obj1.startPage < obj2.startPage)
return -1;
else if (obj1.startPage > obj2.startPage)
return 1;
else
return 0;
}
Search.prototype.showSearchCallback = function( ajaxResponse ) {
this.showSearch(ajaxResponse.data["data"]);
var pageLinks = document.getElementsByClassName('sitbPageLink');
pageLinks.each((function(item) {
Event.observe(item, 'click', this.searchLinkHandler.bind(this), false);
}).bind(this));
var pagination = document.getElementsByClassName('sitbPagination');
pagination.each((function(item) {
Event.observe(item, 'click', this.paginationHandler.bind(this), false);
}).bind(this));
}
Search.prototype.showSearch = function( html ) {
var viewerOverlay = $('viewerOverlay');
extras.hideLoader();
viewerOverlay.innerHTML = html;
$("printSearchResults").innerHTML = '';
if (browser.mz7) {
this.layoutBodyOverflow = $('layoutBody').style.overflow;
$('layoutBody').style.overflow = 'auto';
}
this.setVisible(true);
}
Search.prototype.hideSearch = function( deactivate ) {
$("printSearchResults").innerHTML = '';
if (browser.mz7) {
$('layoutBody').style.overflow = this.layoutBodyOverflow;
}
this.setVisible(false);
if( deactivate ) {
this.deactivate();
}
}
Search.prototype.setVisible = function(visible) {
var backlinkVisibility = (this.active && !visible) ? 'show' : 'hide';
var searchVisibility = (visible) ? 'show' : 'hide';
this.reader.setViewerVisibility(!visible);
browser.setVisibility($('viewerOverlay'), searchVisibility);
browser.setVisibility($('sitbBackLink'), backlinkVisibility);
if( visible ) {
this.reader.setScrollTop(0);
if( $('return_to_book') ) {
if( this.reader.GetCurrentPage() ) {
Element.show($('return_to_book'));
} else {
Element.hide($('return_to_book'));
}
}
}
$("printImage").style.display = "none";
$("printBookInfo").style.display = "none";
$("printWarning").style.display = "none";
this.reader.sidebar.resizeComponents();
}
Search.prototype.searchLinkHandler = function(e) {
try {
var element = Event.element(e);
var args = element.name.split(',');
if( this.first_result ) {
this.first_result = false;
this.sitb_tokens = new Object();
this.loadSITBTokens(args[0], args[1]);
this.reader.pageManager.cache.each( (function(page) {
if( page.getPageNum() == args[0] ) throw $continue;
this.loadSITBTokens( page.getPageNum(), page.getChecksum() );
}).bind(this) );
}
this.hideSearch();
if( !Config.getReaderPermissions().pm_caching ) {
this.reader.viewer.releaseAll();
this.reader.pageManager.clearCache();
}
this.reader.DisplayPage(args[0], args[1], undefined, undefined, 'reader.search.setVisible(true);');
return false;
} catch(e) {
e.logError();
}
}
Search.prototype.paginationHandler = function(e) {
var element = Event.element(e);
this.stripSearch(element.name);
return false;
}
Search.prototype.onPageLoading = function(e, page) {
if(!this.active) return;
this.loadSITBTokens( page.getPageNum(), page.getChecksum(), page.getZoom() );
}
Search.prototype.onPageLoad = function(e, page) {
if( !this.active ) return;
this.showSITBHighlights( page.getPageNum() );
}
Search.prototype.onPageUnload = function(e, page) {
this.setHighlightShown( page.getPageNum(), false );
var indexesToRemove = new Array();
this.indicators.each( function(indicator,idx) {
if( indicator.getPageStart() == page.getPageNum() ) {
indicator.destroy();
indexesToRemove.push(idx);
}
} );
indexesToRemove.each( (function(indicator, idx) {
this.indicators.splice( indicator - idx, 1 );
}).bind(this) );
}
Search.prototype.loadSITBTokens = function(pageNum, checksum, zoom) {
if( !zoom ) zoom = this.reader.GetZoom();
this.setTokens(pageNum, zoom, []);
params = { action: "tokens", p1: this.asin, p2: pageNum, p3: zoom, p4: this.keywords, checksum: checksum };
if( !Config.getReaderPermissions().load_box_data ) {
try {
var page = this.reader.pageManager.getPageObj(pageNum);
page.boxLoaded = false;
} catch(e) {
if( !e.isType('PageNotReady') ) throw e;
}
}
var jsonTokens = new JSONCom( browser );
jsonTokens.setKey( pageNum + '_' + zoom );
jsonTokens.setCallback( this.sitbTokensCallback.bind(this) );
jsonTokens.setURL( Config.getServiceURL() );
jsonTokens.setParams( params );
jsonTokens.sendRequest();
}
Search.prototype.sitbTokensCallback = function(jCom) {
if( jCom.isError() ) {
_a=0;
} else {
var data = eval(jCom.getData());
if(data.length == 0) return;
var pnum = data[0]['page'];
var fields = jCom.getKey().split('_');
var zoom = fields[1];
if( !Config.getReaderPermissions().load_box_data )
{
this.reader.pageManager.getPageObj(pnum).boxDataCallback(jCom);
for( var i = 0; i < data.length; i++ )
{
data[i]['wordID'] = i;
data[i]['top'] -= 4;
data[i]['left'] -= 4;
data[i]['width'] += 8;
data[i]['height'] += 8;
}
}
this.setTokens(pnum, zoom, data);
this.showSITBHighlights(pnum);
}
}
Search.prototype.showSITBHighlights = function(pnum) {
if( !this.reader.pageManager.isPageInCache(pnum) ) {
return;
}
var page = this.reader.pageManager.getPageObj(pnum);
var tokens = this.getTokens(pnum);
if( typeof page == 'undefined' || !page.boxLoaded || !tokens ||
tokens.length == 0 || this.isHighlightShown(pnum) )
{
_a=0;
return;
}
this.setHighlightShown( pnum, true );
_a=0;
for (var i=0; i < tokens.length; ++i) {
var indicator = new Indicator(this.reader, Indicator.SITB, tokens[i]['page'], tokens[i]['wordID']);
indicator.setEnd( tokens[i]['page'], tokens[i]['wordID'] );
this.indicators.push(indicator);
}
}
Search.prototype.deactivate = function() {
this.active = false;
browser.setVisibility($('sitbBackLink'), 'hide');
this.reader.sidebar.resizeComponents();
this.sitb_tokens = new Object();
this.highlightShown = new Object();
for(var i = 0; i < this.indicators.length; ++i) {
this.indicators[i].destroy();
}
this.indicators = new Array();
}
function Sidebar(asin) {
this.asin = asin;
this.bookmark_index = new Array();
this.notes_index    = new Array();
this.annotations =    new Array();
this.bodyHeight = 0;
this.bodyWidth  = 0;
this.width = 0;
Event.observe( $('showHidePalettesTab'), 'click', showHidePalettes, false );
}
Sidebar.MIN_WIDTH = 250;
Object.extend(Sidebar.prototype, SmartObject.prototype);
Sidebar.prototype.isOpen = function() {
var display = $("layoutSidebar").style.display;
return (display == "block" || display == "");
}
Sidebar.prototype.setOpen = function(open) {
if (open && !this.isOpen()) {
showHidePalettes();
}
else if (!open && this.isOpen()){
showHidePalettes();
}
}
Sidebar.prototype.findReferenceObject = function(parentObj, page) {
var elems = parentObj.childNodes;
for(var i = 0; i < elems.length; i++) {
var elemPage = elems[i].getAttribute('page');
if(elemPage > page) {
return elems[i];
}
}
return;
}
Sidebar.prototype.onWindowResize = function( event ) {
_a=0;
this.bodyHeight = document.body.clientHeight;
this.bodyWidth  = document.body.clientWidth;
var sidebarClip = $('layoutSidebarClip');
var tab = $("showHidePalettesTab");
var layoutSidebar = $("layoutSidebar");
if( !this.isOpen() ) {
this.width = 17;
} else {
this.width = this.bodyWidth * 0.27;
if( this.width < Sidebar.MIN_WIDTH ) {
this.width = Sidebar.MIN_WIDTH;
}
}
browser.setLeft(tab, this.width);
browser.setWidth(sidebarClip, this.width);
browser.setWidth(layoutSidebar, this.width);
this.resizeComponents();
this.resizeRealNamePipeline();
}
Sidebar.prototype.resizeComponents = function() {
var layoutSidebar = $('layoutSidebar');
var closedSidebar = $('closedSidebar');
var holder = $('tabbedContentHolder');
var content = $('tabbedContentTOC');
var tabs = $('tabs');
if( content.style.display == 'none' )
content = $('tabbedContentAnnotations');
var navbarCompensation = (browser.ie) ? 0 : 63;
var sidebarHeight = this.bodyHeight - browser.getAbsoluteTop(layoutSidebar)
- navbarCompensation;
var tabsHeight = this.bodyHeight - browser.getAbsoluteTop(tabs) - 7;
browser.setHeight(layoutSidebar, sidebarHeight);
browser.setHeight(closedSidebar, sidebarHeight);
browser.setHeight(tabs, tabsHeight);
browser.setHeight(content, tabsHeight - browser.getAbsoluteTop(content) - 17 );
}
Sidebar.prototype.resizeRealNamePipeline = function() {
var realNamePipeline = $('realNamePipeline');
if( realNamePipeline.style.display == 'block' )
{
var realNamePipelineContent = $('realNamePipelineContent');
var realNameWidth  = realNamePipelineContent.clientWidth;
var realNameHeight = realNamePipelineContent.clientHeight;
if( realNameWidth == 578 )
{
if( this.bodyHeight < (realNameHeight + 46) )
{
browser.setHeight( realNamePipelineContent, this.bodyHeight - 46 );
}
else
{
realNamePipelineContent.style.height = 'auto';
}
}
else
{
browser.setHeight( realNamePipelineContent, this.bodyHeight - 46 );
if( realNamePipelineContent.clientWidth == 578 )
{
realNamePipelineContent.style.height = 'auto';
}
}
realNameHeight = realNamePipeline.clientHeight;
realNamePipeline.style.top = '50%';
realNamePipeline.style.marginTop = -Math.floor( realNameHeight/2 );
}
}
Sidebar.prototype.getWidth = function() {
return this.width;
}
Sidebar.prototype.centerDialog = function( dialogID ) {
var dialog = $(dialogID);
if( dialog != undefined && dialog.style.display == 'block' )
{
dialog.style.marginTop = -Math.floor( dialog.clientHeight/2 );
dialog.style.marginLeft = -Math.floor( dialog.clientWidth/2 );
}
}
StripAuthenticator = function() {
this.clientCallback = undefined;
this.browser = new Browser();
this.error = undefined;
var self = this;
this.getCallbackConduit = function(jsoncom) {
return self.getCallback(jsoncom);
}
this.initiateCallbackConduit = function(jsoncom) {
return self.initiateCallback(jsoncom);
}
this.completeCallbackConduit = function(jsoncom) {
return self.completeCallback(jsoncom);
}
}
StripAuthenticator.prototype.getCallback = function (jsoncom) {
if (jsoncom.isError()) {
window.location = Config.getReaderURL + "?v=error";
}
else {
if (jsoncom.getData().result != "0") {
this.error = jsoncom.getError();
this.clientCallback();
return;
}
}
var json = new JSONCom( this.browser );
json.setCallback( this.initiateCallbackConduit );
json.setKey("initiate");
json.setURL( Config.getServiceURL() );
json.setParams( { action: "getSTRIPAccountID", stage: "initiate" } );
json.sendRequest();
}
StripAuthenticator.prototype.initiateCallback = function (jsoncom) {
if (jsoncom.isError()) {
window.location = Config.getReaderURL + "?v=error";
}
setTimeout("stripAuthenticator.delayedQuery()", 100);
}
StripAuthenticator.prototype.delayedQuery = function () {
var json = new JSONCom( browser );
json.setCallback( this.completeCallbackConduit );
json.setKey("complete");
json.setURL( Config.getServiceURL() );
json.setParams( { action: "getSTRIPAccountID", stage: "complete" } );
json.sendRequest();
}
StripAuthenticator.prototype.completeCallback = function (jsoncom) {
if (jsoncom.getError() == "IN_PROGRESS") {
setTimeout("stripAuthenticator.delayedQuery()", 500);
return;
}
this.error = jsoncom.getError();
this.clientCallback();
}
StripAuthenticator.prototype.getError = function() {
return this.error;
}
StripAuthenticator.prototype.isError = function() {
return (this.error != "");
}
StripAuthenticator.prototype.init = function (clientCallback) {
this.clientCallback = clientCallback;
var json = new JSONCom( this.browser );
json.setCallback( this.getCallbackConduit );
json.setKey("get");
json.setURL( Config.getServiceURL() );
json.setParams( { action: "getSTRIPAccountID", stage: "get" } );
json.sendRequest();
}
TagManager = function() {
Object.extend(this, new EventDispatcher());
this.tagList = new Array();
this.hasChanged = false;
this.load();
}
TagManager.MAX_SAVED_TAGS = 100;
Object.extend(TagManager.prototype, SmartObject.prototype);
TagManager.prototype.getTagIndex = function(tag) {
var tagList = this.tagList;
var length = tagList.length;
for (var i = 0; i < length; i++) {
if (tagList[i].tag == tag)
return i;
}
return -1;
}
TagManager.prototype.addTag = function(tag) {
var tagIndex = this.getTagIndex(tag);
var date = new Date();
if (tagIndex != -1) {
this.tagList[tagIndex].count++;
this.tagList[tagIndex].timestamp = date.getTime();
}
else {
var newTag = new Object();
newTag.tag = tag;
newTag.count = 1;
newTag.timestamp = date.getTime();
this.tagList.push(newTag);
}
this.hasChanged = true;
this.tagList.sort(this.sortFunc);
}
TagManager.prototype.sortFunc = function(a, b) {
return (a.count == b.count)?(b.timestamp - a.timestamp):(b.count-a.count);
}
TagManager.prototype.getLink = function(tag) {
}
TagManager.prototype.getClosestMatches = function(word, maxSize) {
var matches = new Array();
for (var i = 0; i < this.tagList.length && (maxSize == undefined || matches.length < maxSize); i++) {
if ( this.tagList[i].tag.indexOf(word) == 0 )
matches.push( this.tagList[i].tag );
}
return matches;
}
TagManager.prototype.load = function() {
if( !Config.getReaderPermissions().save_settings ) {
return;
}
var json = new JSONCom( browser );
json.setCallback( this.loadCallback.bind(this) );
json.setURL( Config.getServiceURL() );
json.setParams( { action: "loadTags" } );
json.sendRequest();
}
TagManager.prototype.save = function() {
if ( this.hasChanged && Config.getReaderPermissions().save_settings ) {
var json = new JSONCom( browser );
json.setCallback( this.saveCallback.bind(this) );
json.setURL( Config.getServiceURL() );
json.setParams( { action: "saveTags", tags: this.serialize() } );
json.sendRequest();
_a=0;
}
}
TagManager.prototype.serialize = function () {
var tagList = this.tagList;
var length = tagList.length;
if (length > TagManager.MAX_SAVED_TAGS)
length = TagManager.MAX_SAVED_TAGS;
var tempList = new Array();
for (var i = 0; i < length; i++) {
tempList.push(tagList[i].tag);
tempList.push(tagList[i].count);
tempList.push(tagList[i].timestamp);
}
return tempList.join(",");
}
TagManager.prototype.deserialize = function (tagString) {
var tempList = tagString.split(",");
var length = tempList.length;
var tagList = this.tagList;
for (var i = 0, j = 0; j < length; i++, j = j + 3) {
tagList[i] = new Object();
tagList[i].tag = tempList[j];
tagList[i].count = tempList[j+1];
tagList[i].timestamp = tempList[j+2];
}
}
TagManager.prototype.loadCallback = function(jsoncom) {
if (jsoncom.isError()) {
_a=0;
}
else {
var data = jsoncom.getData();
if (data != "" && data != undefined)
this.deserialize(data);
this.hasChanged = false;
_a=0;
this.fireEvent('tagsLoaded', true, false);
}
}
TagManager.prototype.saveCallback = function(jsoncom) {
if (jsoncom.isError()) {
_a=0;
}
else {
_a=0;
this.hasChanged = false;
this.fireEvent('tagsSaved', true, false);
}
}
function menuOver(element) {
if( element.className.match('divider') != null ) {
element.className = 'divider menu';
}
else if( element.className.match('seperate') != null ) {
element.className = 'seperate menu';
}
else {
element.className = 'menu';
}
}
function menuOut(element) {
if( element.className.match('divider') != null ) {
element.className = 'divider';
}
else if( element.className.match('seperate') != null ) {
element.className = 'seperate';
}
else {
element.className = '';
}
}
Triangle = function( color ) {
this.color = color;
this.basediv = null;
if(browser.ie) {
Object.extend(this, TriangleIE.prototype);
} else {
Object.extend(this, TriangleFF.prototype);
}
}
Triangle.BORDER_COLOR = 'A19C98';
Object.extend(Triangle.prototype, SmartObject.prototype);
TriangleFF = function() {
this.canvas = null;
this.ctx = null;
if( browser.saf ) {
this.canvas2 = null;
this.ctx2 = null;
this.count = 0;
}
}
TriangleFF.prototype.init = function() {
try {
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext("2d");
this.ctx.globalAlpha = 0.6;
this.prevWidth = 0;
this.prevHeight = 0;
browser.setPositioning(this.canvas,'absolute');
this.basediv.appendChild(this.canvas);
if( browser.saf ) {
this.canvas2 = document.createElement('canvas');
this.ctx2 = this.canvas2.getContext("2d");
this.ctx2.globalAlpha = 0.6;
browser.setPositioning(this.canvas2, 'absolute');
this.basediv.appendChild(this.canvas2);
browser.setLeft(this.canvas2, -1500);
browser.setTop(this.canvas2, -1500);
this.primaryCanvas = true;
this.firstResize = true;
this.count = 0;
}
} catch(e) {}
}
TriangleFF.prototype.hide = function() {
try {
Element.hide( this.canvas );
if( browser.saf ) {
Element.hide( this.canvas2 );
}
} catch(e) {}
}
TriangleFF.prototype.show = function() {
try {
Element.show( this.canvas );
if( browser.saf ) {
Element.show( this.canvas2 );
}
} catch(e) {}
}
TriangleFF.prototype.reattach = function() {
try {
if( this.canvas.parentNode ) {
this.canvas.parentNode.removeChild(this.canvas);
}
this.basediv.appendChild(this.canvas);
if( browser.saf ) {
if( this.canvas2.parentNode ) {
this.canvas2.parentNode.removeChild(this.canvas2);
}
this.basediv.appendChild(this.canvas2);
}
} catch(e) {}
}
TriangleFF.prototype.draw = function(xStart, yStart, xEnd, yEnd) {
try {
var x = xEnd - xStart;
var y = yEnd - yStart;
var angle;
var pi = Math.PI;
var _ctx = this.ctx;
var _canvas = this.canvas;
var _back_canvas = this.canvas;
if( browser.saf ) {
if( this.primaryCanvas == true ) {
_ctx = this.ctx;
_canvas = this.canvas;
_back_canvas = this.canvas2;
} else {
_ctx = this.ctx2;
_canvas = this.canvas2;
_back_canvas = this.canvas;
}
}
_ctx.clearRect(0,0,this.prevWidth, this.prevHeight);
if(x == 0) {
angle = pi / 2;
if(y < 0) angle *= -1;
} else {
angle = Math.atan(y/x);
if(x < 0) angle -= Math.PI;
}
var xOffset = parseInt( 20 * Math.sin(angle) );
var yOffset = parseInt( 20 * Math.cos(angle) );
var xVertex1 = xEnd - xOffset;
var yVertex1 = yEnd + yOffset;
var xVertex2 = xEnd + xOffset;
var yVertex2 = yEnd - yOffset;
var xMin = Math.min(Math.min(xStart, xVertex1), xVertex2);
var xMax = Math.max(Math.max(xStart, xVertex1), xVertex2);
var yMin = Math.min(Math.min(yStart, yVertex1), yVertex2);
var yMax = Math.max(Math.max(yStart, yVertex1), yVertex2);
var height = yMax - yMin;
var width = xMax - xMin;
_back_canvas.setAttribute('height', height);
_back_canvas.setAttribute('width', width);
if( browser.saf ) {
browser.setLeft(_back_canvas, -1500);
browser.setTop(_back_canvas, -1500);
if( this.firstResize ) {
_canvas.setAttribute('height', height);
_canvas.setAttribute('width', width);
this.firstResize = false;
}
this.count++;
if( this.count % 2 == 0 ) {
this.primaryCanvas = !this.primaryCanvas;
}
}
browser.setLeft( _canvas, xMin )
browser.setTop( _canvas, yMin );
_ctx.beginPath();
_ctx.moveTo(xStart - xMin, yStart - yMin);
_ctx.lineTo(xVertex1 - xMin, yVertex1 - yMin);
_ctx.lineTo(xVertex2 - xMin, yVertex2 - yMin);
_ctx.closePath();
_ctx.fill();
this.prevWidth = width;
this.prevHeight = height;
} catch(e) {}
}
TriangleFF.prototype.getObject = function() {
return this.canvas;
}
TriangleFF.prototype.remove = function() {
try {
this.basediv.removeChild(this.canvas);
if( browser.saf ) {
this.basediv.removeChild(this.canvas2);
}
} catch(e) {}
}
TriangleFF.prototype.setColor = function(color) {
try {
this.ctx.fillStyle = color;
if( browser.saf ) {
this.ctx2.fillStyle = color;
}
} catch(e) {}
}
TriangleIE = function() {
this.obj = null;
}
TriangleIE.PIOverTwo = Math.PI / 2;
TriangleIE.oneEightyOverPI = 180 / Math.PI;
TriangleIE.prototype.init = function() {
this.obj = document.createElement('v:shape');
this.obj.style.position = 'absolute';
Event.observe( this.obj, 'mousedown', preventContext, true );
Event.observe( this.obj, 'contextmenu', preventContext, true );
var f = document.createElement('v:fill');
f.opacity = 0.6;
this.obj.appendChild(f);
this.basediv.appendChild(this.obj);
}
TriangleIE.prototype.show = function() {
Element.show( this.obj );
}
TriangleIE.prototype.hide = function() {
Element.hide( this.obj );
}
TriangleIE.prototype.destroy = function() {
if( this.obj ) {
Event.stopObserving( this.obj, 'mousedown', preventContext, true );
Event.stopObserving( this.obj, 'contextmenu', preventContext, true );
}
}
TriangleIE.prototype.reattach = function() {
if( this.obj.parentNode ) {
this.obj.parentNode.removeChild(this.obj);
}
this.basediv.appendChild( this.obj );
}
TriangleIE.prototype.draw = function(xStart, yStart, xEnd, yEnd) {
var x = xEnd - xStart;
var y = yEnd - yStart;
var length = Math.round(Math.sqrt(Math.pow(x, 2) + Math.pow(y,2)));
var angle;
if(x == 0) {
angle = TriangleIE.PIOverTwo;
if(y < 0) angle *= -1;
} else {
angle = Math.atan(y/x);
if(x < 0) angle -= Math.PI;
}
var tWidth = 40;
var s = this.obj;
s.style.top =  (yStart - length) + 'px';
s.style.left = (xStart - tWidth/2) + 'px';
s.style.width = tWidth + 'px';
s.style.height = length * 2 + 'px';
s.coordsize = tWidth + ',' + (length * 2);
s.path = 'm ' + (tWidth/2) + ',' + length +
' l ' + tWidth + ',' + (2*length) +
' 0,' + (2*length) + ' x e';
s.style.rotation = TriangleIE.oneEightyOverPI * angle - 90;
}
TriangleIE.prototype.getObject = function() {
return this.obj;
}
TriangleIE.prototype.remove = function() {
this.basediv.removeChild(this.obj);
}
TriangleIE.prototype.setColor = function(color) {
this.obj.fillColor = color;
this.obj.strokeColor = color;
}
UserSettings = function(asin) {
this.asin = asin;
this.settings = new Array();
this.settings["viewMode"] = "single";
this.settings["sidebar"] = true;
this.settings["showAnnotations"] = true;
this.settings["annotationColor"] = "green";
this.settings["defaultAnnotationScope"] = false;
this.settings["showCopyDialog"] = true;
this.settings["showPrintDialog"] = true;
this.settings["showBackDialog"] = true;
this.settings["showIncompatibleBrowserDialog"] = true;
this.settings["lastPageViewed"] = "";
this.callbackFunc = undefined;
this.settingsChanged = false;
this.settingsLoaded = false;
toolbar.addListener('highlightSettingsRequest', this, 'onSettingsDialogOpen');
toolbar.addListener('bookmarkSettingsRequest', this, 'onSettingsDialogOpen');
toolbar.addListener('viewSettingsRequest', this, 'onSettingsDialogOpen');
toolbar.addListener( 'annotationsOnPageRequest', this, 'onShowHideAnnotationsRequest' );
}
Object.extend(UserSettings.prototype, SmartObject.prototype);
UserSettings.prototype.onPageChange = function(event, pageObj) {
this.set("lastPageViewed", pageObj.getPageNum());
}
UserSettings.prototype.onShowHideAnnotationsRequest = function() {
var enabled = this.settings["showAnnotations"] ? false : true;
this.set("showAnnotations", enabled);
}
UserSettings.prototype.onSettingsDialogOpen = function() {
if (this.settings["viewMode"] == "single") {
$("viewModeSingle").checked = true;
}
else {
$("viewModeContinuous").checked = true;
}
if (this.settings["sidebar"]) {
$("sidebarOpen").checked = true;
}
else {
$("sidebarClosed").checked = true;
}
if (this.settings["showAnnotations"]) {
$("showAnnotationsShow").checked = true;
}
else {
$("showAnnotationsHide").checked = true;
}
if (this.settings["annotationColor"] == "gold") {
$("annotationColorGold").checked = true;
}
else if (this.settings["annotationColor"] == "blue") {
$("annotationColorBlue").checked = true;
}
else if (this.settings["annotationColor"] == "pink") {
$("annotationColorRed").checked = true;
}
else if (this.settings["annotationColor"] == "green") {
$("annotationColorGreen").checked = true;
}
if (this.settings["defaultAnnotationScope"]) {
$("defaultAnnotationScopePublic").checked = true;
}
else {
$("defaultAnnotationScopePrivate").checked = true;
}
displayDialog("settingsDialog");
}
UserSettings.prototype.onSettingsDialogCancel = function() {
hideDialog( "settingsDialog" );
}
UserSettings.prototype.onSettingsDialogSave = function() {
if ($("viewModeSingle").checked) {
this.settings["viewMode"] = "single";
reader.SetViewer("single");
}
else {
this.settings["viewMode"] = "continuous";
reader.SetViewer("continuous");
}
this.settings["sidebar"] = $("sidebarOpen").checked;
reader.sidebar.setOpen($("sidebarOpen").checked);
this.settings["showAnnotations"] = $("showAnnotationsShow").checked;
reader.annotationManager.onShowHideAnnotations(undefined, true, $("showAnnotationsShow").checked);
this.settings["defaultAnnotationScope"] = $("defaultAnnotationScopePublic").checked;
reader.annotationManager.setDefaultAnnotationScope($("defaultAnnotationScopePublic").checked?
Annotation.PUBLIC : Annotation.PRIVATE);
if ($("annotationColorGold").checked) {
this.settings["annotationColor"] = "gold";
}
else if ($("annotationColorGreen").checked) {
this.settings["annotationColor"] = "green";
}
else if ($("annotationColorRed").checked) {
this.settings["annotationColor"] = "pink";
}
else if ($("annotationColorBlue").checked) {
this.settings["annotationColor"] = "blue";
}
reader.annotationManager.updateAnnotationColor(this.settings["annotationColor"]);
this.save();
hideDialog("settingsDialog");
}
UserSettings.prototype.set = function(name, value) {
if( this.settings[name] == value )
return;
_a=0;
this.settings[name] = value;
this.settingsChanged = true;
this.save();
}
UserSettings.prototype.get = function(name) {
return this.settings[name];
}
UserSettings.prototype.save = function() {
if( !Config.getReaderPermissions().save_settings ) {
return;
}
var json = new JSONCom( browser );
json.setCallback( this.saveCallback.bind(this) );
json.setURL( Config.getServiceURL() );
json.setParams( { action: "saveSettings",
asin: this.asin,
viewMode: this.settings["viewMode"],
sidebar: this.settings["sidebar"]?"true":"false",
showAnnotations: this.settings["showAnnotations"]?"true":"false",
annotationColor: this.settings["annotationColor"],
defaultAnnotationScope: this.settings["defaultAnnotationScope"]?"true":"false",
lastPageViewed: this.settings["lastPageViewed"],
showCopyDialog: this.settings["showCopyDialog"]?"true":"false",
showPrintDialog: this.settings["showPrintDialog"]?"true":"false",
showBackDialog: this.settings["showBackDialog"]?"true":"false",
showIncompatibleBrowserDialog: this.settings["showIncompatibleBrowserDialog"]?"true":"false"
} );
json.sendRequest();
}
UserSettings.prototype.saveCallback = function(jsoncom) {
if (jsoncom.isError()) {
_a=0;
}
else {
_a=0;
this.settingsChanged = false;
}
}
UserSettings.prototype.load = function( callbackFunc ) {
if( !Config.getReaderPermissions().save_settings ) {
return;
}
this.callbackFunc = callbackFunc;
var json = new JSONCom( browser );
json.setCallback( this.loadCallback.bind(this) );
json.setURL( Config.getServiceURL() );
json.setParams( { action: "loadSettings" } );
json.sendRequest();
}
UserSettings.prototype.loadCallback = function(jsoncom) {
if (jsoncom.isError()) {
_a=0;
}
else {
var data = jsoncom.getData();
if (data.viewMode != "" && data.viewMode != undefined)
this.settings["viewMode"] = data.viewMode;
if (data.annotationColor != "" && data.annotationColor != undefined)
this.settings["annotationColor"] = data.annotationColor;
(["sidebar", "showAnnotations", "defaultAnnotationScope", "showCopyDialog",
"showPrintDialog", "showIncompatibleBrowserDialog", "showBackDialog"]).each(
(function(id) {
if(data[id] != '' && data[id] != undefined) {
this.settings[id] = (data[id] == "true") ? true: false;
}
}).bind(this));
_a=0;
_a=0;
this.settingsLoaded = true;
}
this.callbackFunc();
this.settingsChanged = false;
}
UserSettings.prototype.isLoaded = function() {
return ( this.settingsLoaded || !Config.getReaderPermissions().save_settings );
}

