avweb.js 25.7 KB
Newer Older
1 2 3 4 5 6
/**
 *  ABook Viewer for WEB
 *	Common Library
 *  Copyright (C) Agentec Co, Ltd. All rights reserved.
 */

Masaru Abe committed
7 8 9 10 11
//グローバルの名前空間用のオブジェクトを用意する
var AVWEB = {};

AVWEB.hasErrorKey = 'AVW_HASERR';

Masaru Abe committed
12 13 14
/*
 * User Environment Check Class
 */
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
var UserEnvironment = function() {
		
	this.appName = navigator.appName;
	this.userAgent = navigator.userAgent;
	this.os = checkOS(this.userAgent);
	this.browser = checkBrowser(this.userAgent);
	
	/* windows os check */
	this.isWindows = function() {
		return (this.os == "windows");
	};
	/* mac os check */
	this.isMac = function() {
		return (this.os == "mac");
	};
	
	/* ipad check */
	this.isIpad = function() {
		return (this.os == "ipad");
	};
	
	/* iphone check */
	this.isIphone = function() {
		return (this.os == "iphone");
	};
	/* android check */
	this.isAndroid = function() {
		return (this.os == "android");
	};
Masaru Abe committed
44 45 46 47
	/* iOS check */
	this.isIos = function() {
		if(this.os == "ipad" || this.os == "iphone"){
			return true;
Masaru Abe committed
48 49 50 51 52 53 54 55
		} else {
			return false;
		}
	};
	/* mobile check */
	this.isMobile = function() {
		if(this.os == "ipad" || this.os == "iphone" || this.os == "android"){
			return true;
Masaru Abe committed
56 57 58 59 60 61
		} else {
			return false;
		}
	};
	
	/** check operating system */
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
	function checkOS(userAgent) {
		if(userAgent.toLowerCase().indexOf("windows") >= 0) {
			return "windows";
		}
		if(userAgent.toLowerCase().indexOf("mac") >= 0) {
			if(userAgent.toLowerCase().indexOf("ipad") >= 0) {
				return "ipad";
			}
			if(userAgent.toLowerCase().indexOf("iphone") >= 0) {
				return "iphone";
			}
			return "mac";
		}
		if(userAgent.toLowerCase().indexOf("android") >= 0) {
			return "android";
		}
		return "unknown";
	};
	/** check user browser */
	function checkBrowser(userAgent) {
82
		
83 84 85
		if(userAgent.toLowerCase().indexOf("msie") >= 0) {
			return "msie";
		}
86 87 88
		if(userAgent.toLowerCase().indexOf("trident") >= 0) {
			return "msie";
		}
89 90 91 92 93 94 95 96 97 98 99 100
		if(userAgent.toLowerCase().indexOf("firefox") >= 0) {
			return "firefox";
		}
		if(userAgent.toLowerCase().indexOf("safari") >= 0) {
			if(userAgent.toLowerCase().indexOf("chrome") >= 0) {
				return "chrome";
			}
			return "safari";
		}
		if(userAgent.toLowerCase().indexOf("opera") >= 0) {
			return "opera";
		}
101
		
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
		return "unknown";
	};
};
/*
 * User Settings Class Definition
 */
var UserSetting = function() {
	this.US_KEY="AVWUS";
	this.userSetting = this.load();
};
/* get user setting from localStorage */
UserSetting.prototype.load = function () {
    var storage = window.localStorage;
    var value = null;
    var js = null;
    if (storage) {
        var value = storage.getItem(this.US_KEY);
        if (!value) {
            value = "{}"; // 空JSON文字列
        }
        js = JSON.parse(value);
    }
    return js;
};
/* store user setting */
UserSetting.prototype.set = function(key, value) {
128
	//if(!this.userSetting) {
129
		this.userSetting = this.load();
130
	//}
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
	var values = this.userSetting;
	if(!values) {
		values = { key: value };
	} else {
		values[key] = value;
	}
	var storage = window.localStorage;
	if(storage) {
		var jsonStr = JSON.stringify(values);
		storage.setItem(this.US_KEY, jsonStr);
	}
	this.userSetting = values;
};
/* grab user setting */
UserSetting.prototype.get = function(key) {
146
	//if(!this.userSetting) {
147
		this.userSetting = this.load();
148
	//}
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
	var values = this.userSetting;
	if(values) {
		return values[key];
	}
	return null;
};
/* show user setting object list */
UserSetting.prototype.show = function(elmid) {
	var storage = window.localStorage;
	var tags = "<p>";
	if(storage) {
		var value = storage.getItem(this.US_KEY);
		if(value) {
			var js = JSON.parse(value);
			$.each(js, function(k, v) {
Masaru Abe committed
164
				tags = tags + "<b>" + k + "</b>:" + v + "<br />";
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
			});
		}
		tags = tags + "</p>";
		$(elmid).html(tags);
	}	
};
/* ユーザ設定のキーリストを取得 */
UserSetting.prototype.keys = function() {
	var storage = window.localStorage;
	var keyList = [];
	if(storage) {
		var value = storage.getItem(this.US_KEY);
		if(value) {
			var js = JSON.parse(value);
			var i = 0;
			$.each(js, function(k, v) {
				keyList[i++] = k;
			});
		}
		return keyList;
	}
	return null;
};
/* ユーザ設定を削除 */
UserSetting.prototype.remove = function(key) {
	var storage = window.localStorage;
	if(storage) {
		var value = storage.getItem(this.US_KEY);
		if(value) {
			var js = JSON.parse(value);
			if(js) {
				delete js[key];
				storage.setItem(this.US_KEY, JSON.stringify(js));
			}
		}
	}
};
/* ユーザ設定をすべて削除 */
UserSetting.prototype.removeAll = function() {
	var storage = window.localStorage;
	if(storage) {
		storage.remove(this.US_KEY);
	}	
};

/*
 * User Session Class Definition
 */
var UserSession = function() {
	this.available = false;
};
/* Initialize User Session */
UserSession.prototype.init = function(option) {
	
	this.available = false;
	if(option == 'restore') {
		var value = null;
		try {
			value = this._get('init');
		} catch(e) {
			value = null;
		} finally {
			if(value) {
				this.available = true;
			}
		}
	} else {
		this.set("init", new Date().toLocaleString());
		this.available = true;		
	}
};
/* store key, value item to user session */
UserSession.prototype.set = function(key, value) {
	var storage = window.sessionStorage;
	if(storage) {
		if(this.available == false) {
			if(key == "init") {
Masaru Abe committed
242
				storage.setItem("AVWS_" + key, value);
243 244 245 246 247 248 249 250 251 252 253 254
			} else {
				throw new Error("Session destoryed.");
			}
		} else {
			storage.setItem("AVWS_" + key, value);
		}
	}	
};
/* get session item value */
UserSession.prototype.get = function(key) {
	var value = null;
	if(this.available) {
Masaru Abe committed
255
		value = this._get(key);
256
	} else {
Masaru Abe committed
257
		throw new Error("Session Destroyed.");
258 259 260 261 262 263 264 265
	}
	return value;	
};
/* get item value from session storage */
UserSession.prototype._get = function(key) {
	var storage = window.sessionStorage;
	var value = null;
	if(storage) {
Masaru Abe committed
266
		value = storage.getItem("AVWS_" + key);
267
	}
Masaru Abe committed
268
	return value;
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
};
/* destroy user session */
UserSession.prototype.destroy = function() {
	var storage = window.sessionStorage;
	if(storage) {
		storage.clear();
		this.available = false;
	}	
};
/* show user session object list */
UserSession.prototype.show = function(elmid) {
	var storage = window.sessionStorage;
	var tags = "<p>";
	if(storage) {
		for(var i = 0; i < storage.length; i++) {
			var key = storage.key(i);
			var value = storage.getItem(key);
			tags = tags + "<b>" + key + "</b>:" + value + "<br />";
		}
		tags = tags + "</p>";
		$(elmid).html(tags);
	}	
};
/*
 * Variables
 */
295 296 297 298
AVWEB.avwUserSessionObj = null;
AVWEB.avwUserSettingObj = null;
//AVWEB.avwUserEnvObj = null;
AVWEB.avwSysSettingObj = null;
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318

/* Initialize system */
$(function () {
	
    // システム設定ファイルの配置先パスの決定
	var location = window.location.toString().toLowerCase();
	var sysFile = '';
	if (location.indexOf('/abvw') < 0) {
 		sysFile = './abvw/common/json/sys/conf.json';
 	} else {
        sysFile = './common/json/sys/conf.json';
	}

    // システム設定ファイルを読み込む
    $.ajax({
        url: sysFile,
        async: false,
        cache: false,
        dataType: 'json',
        success: function (data) {
319
            AVWEB.avwSysSettingObj = data;
320 321 322 323 324 325 326 327 328
        },
        error: function (xmlHttpRequest, txtStatus, errorThrown) {
            var error = 'Could not load the system configuration file. Please check it.';
            error += '\n' + xmlHttpRequest.status + ' ' + txtStatus + ' ' + errorThrown + ' : ' + sysFile;
            alert(error);
        }
    });
    
    // ロード時に一旦エラー状態をクリアしておく
329
    AVWEB.avwClearError();
330 331 332
});

/* get system setting object */
333 334
AVWEB.avwSysSetting = function() {
	return AVWEB.avwSysSettingObj;
335 336
};

337 338 339 340 341 342 343
///* get user environment object */
//function avwUserEnv() {
//	if(AVWEB.avwUserEnvObj == null) {
//		AVWEB.avwUserEnvObj = new UserEnvironment();
//	}
//	return AVWEB.avwUserEnvObj;
//};
344
/* get user session object */
345 346
AVWEB.avwUserSession = function() {
	if(!AVWEB.avwUserSessionObj) {
347 348 349
		var obj = new UserSession();
		obj.init('restore');
		if(obj.available) {
350 351
			AVWEB.avwUserSessionObj = obj;
			return AVWEB.avwUserSessionObj;
352 353 354 355
		} else {
			return null;
		}
	}
356
	return AVWEB.avwUserSessionObj;
357 358
};
/* create user session object */
359 360 361
AVWEB.avwCreateUserSession = function() {
	if(AVWEB.avwUserSessionObj) {
		AVWEB.avwUserSessionObj.destroy();
362
	} else {
363 364
		AVWEB.avwUserSessionObj = new UserSession();
		AVWEB.avwUserSessionObj.init();
365
	}
366
	return AVWEB.avwUserSessionObj;
367 368
};
/* check Login or not */
369 370
AVWEB.avwCheckLogin = function(option) {
	var userSession = AVWEB.avwUserSession();
371 372 373 374 375 376
	if(!userSession) {

		/* エラー画面を表示 */
		var tags = '<div id="avw-auth-error">' +
				   '<div style="display:table; width:100%; height:100%;">' + 
				   '<div style="display:table-cell; text-align:center; vertical-align:middle;">' +
377
				   '<p><h4>Authentication error</h4>Please use it after login.</p>' + 
378 379 380
				   '<div><button id="avw-unauth-ok">OK</button></div>' +
				   '</div></div></div>';
		$('body').prepend(tags);
Vo Duc Thang committed
381
		$('#avw-auth-error').css({		    
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
		    'opacity': 1,
		    'position': 'fixed',
		    'top': '0',
		    'left': '0',
		    'width': $(window).width(),
		    'height': $(window).height(),
		    'zIndex': '10000'
		});
		// resize error page	
		$(window).resize(function() {
			$('#avw-auth-error').css( {
				'width': $(window).width(),
				'height': $(window).height()
			});			
		});
			
		var returnPage;
		if(option) {
			returnPage = option
		} else {
402
			var sysSetting = AVWEB.avwSysSetting();
403 404 405 406
			returnPage = sysSetting.loginPage;
		}
		/* ログイン画面に戻る */
		$('#avw-unauth-ok').click(function() {
Masaru Abe committed
407 408
			window.location = returnPage;
		});
409 410 411 412
		return false;
	}
	return true;
};
Masaru Abe committed
413
/* get user setting object */
414 415 416
AVWEB.avwUserSetting = function() {
	if(AVWEB.avwUserSettingObj == null) {
		AVWEB.avwUserSettingObj = new UserSetting();
417
	}
418
	return AVWEB.avwUserSettingObj;
419 420 421
};

/* CMS API Call(async. call) */
422 423 424
AVWEB.avwCmsApi = function(accountPath, apiName, type, params, success, error) {
	//var sysSettings = AVWEB.avwSysSetting();
	AVWEB._callCmsApi(ClientData.conf_apiUrl(), accountPath, apiName, type, params, true, success, error);
425 426
};
/* CMS API Call(sync. call) */
427 428 429
AVWEB.avwCmsApiSync = function(accountPath, apiName, type, params, success, error) {
	//var sysSettings = AVWEB.avwSysSetting();
	AVWEB._callCmsApi(ClientData.conf_apiUrl(), accountPath, apiName, type, params, false, success, error);
430 431
};
/* CMS API Call(async. call) */
432 433
AVWEB.avwCmsApiWithUrl = function(url, accountPath, apiName, type, params, success, error) {
	AVWEB._callCmsApi(url, accountPath, apiName, type, params, true, success, error);
434 435
};
/* CMS API Call(sync. call) */
436 437
AVWEB.avwCmsApiSyncWithUrl = function(url, accountPath, apiName, type, params, success, error) {
	AVWEB._callCmsApi(url, accountPath, apiName, type, params, false, success, error);
438 439 440
};

/* CMS API Call */
441
AVWEB._callCmsApi = function(url, accountPath, apiName, type, params, async, success, error) {
442 443
	
	// アプリケーション設定取得
444
	var sysSettings = AVWEB.avwSysSetting();
445 446 447 448
	
	// url 構築
	var apiUrl;
	if(!url) {
Masaru Abe committed
449
		apiUrl = ClientData.conf_apiUrl(); //sysSettings.apiUrl;
450 451 452 453
	} else {
		apiUrl = url;
	}
	if(accountPath) {
454
		apiUrl = AVWEB.format(apiUrl, accountPath);
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
	}
	apiUrl = apiUrl + '/' + apiName + '/';
	
	//----------------------------------------------------------------------------------
	// for IE: 暫定的に対応 (これをすることでIE9でもCrossDomainリクエストが可能だがアクセスのたびに警告が出る)
	$.support.cors = true;
	//----------------------------------------------------------------------------------
	
	// ajax によるAPIの実行(json)
	$.ajax( {
		async:		(async) ? async : false,
		type:		(type) ? type : 'get',
		url:		apiUrl,
		cache: 		false,
		dataType:	'json',
		data:		params,
		crossDomain: true,
		beforeSend:	function(xhr) {
			/*
			 * ABook viewer for WEB 用のリクエストヘッダに、以下のヘッダを付加する
			 * X-AGT-AppId: ABookWebCL
			 * X-AGT-AppVersion: 0.0.1
			 */
			xhr.setRequestHeader('X-AGT-AppId', sysSettings.appName);
			xhr.setRequestHeader('X-AGT-AppVersion', sysSettings.appVersion);
		},
		success:	function(data) {
			if(success) {
Masaru Abe committed
483
				success(data);
484 485 486 487 488 489 490
			}
		},
		error:		function(xmlHttpRequest, txtStatus, errorThrown) {
			/* call custom error process */
			if(error) {
				error(xmlHttpRequest, txtStatus, errorThrown);
			} else {
491 492 493 494 495 496 497
				if(xmlHttpRequest.status == 403) {
					AVWEB.showSystemError('sysErrorCallApi02');
				}
				else {
					AVWEB.showSystemError();
				}
			
498 499
			}
		}
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
	});
	
};


/* CMS API Call */
AVWEB._callCmsApiWhen = function(accountPath, apiName, type, params ) {
	
	// アプリケーション設定取得
	var sysSettings = AVWEB.avwSysSetting();
	
	// url 構築
	var apiUrl = ClientData.conf_apiUrl();
	if(accountPath) {
		apiUrl = AVWEB.format(apiUrl, accountPath);
	}
	apiUrl = apiUrl + '/' + apiName + '/';
	
	//----------------------------------------------------------------------------------
	// for IE: 暫定的に対応 (これをすることでIE9でもCrossDomainリクエストが可能だがアクセスのたびに警告が出る)
	$.support.cors = true;
	//----------------------------------------------------------------------------------
	
	// ajax によるAPIの実行(json)
	var ajaxObj = $.ajax( {
		async:		true,
		type:		(type) ? type : 'get',
		url:		apiUrl,
		cache: 		false,
		dataType:	'json',
		data:		params,
		crossDomain: true,
		beforeSend:	function(xhr) {
			/*
			 * ABook viewer for WEB 用のリクエストヘッダに、以下のヘッダを付加する
			 * X-AGT-AppId: ABookWebCL
			 * X-AGT-AppVersion: 0.0.1
			 */
			xhr.setRequestHeader('X-AGT-AppId', sysSettings.appName);
			xhr.setRequestHeader('X-AGT-AppVersion', sysSettings.appVersion);
		}
	});
	
	return ajaxObj;
	
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
};

/*
 * Create Image Data Scheme URI
 */
var ImageDataScheme = function () {

    // バイナリデータを文字列に変換
    this.convBinaryToString = function (filestream) {
        var bytes = [];
        for (var i = 0; i < filestream.length; i++) {
            bytes[i] = filestream.charCodeAt(i) & 0xff;
        }
        return String.fromCharCode.apply(String, bytes);
    };

    // 画像のバイト文字列をdataスキームURIに変換
    this.convImageToDataScheme = function (binaryData, ie) {
        var b64Data;
        var imgHeader;
        var imgType = 'png';

        if (ie) {
            // binary to base64 for ie
            b64Data = this.base64encodeForIE(binaryData);
        } else {
            // binary to base64 for FF, Chrome, Safari
            var bin = this.convBinaryToString(binaryData);
            b64Data = btoa(bin);
            imgHeader = bin.substring(0, 9);
            imgType = this.checkImageType(imgHeader);
        }
        return 'data:image/' + imgType + ';base64,' + b64Data;
    };

    // 画像タイプ(種類をチェック)
    this.checkImageType = function (header) {
        if (header.match(/^\x89PNG/)) {
            return 'png';
        } else if (header.match(/^GIF87a/) || header.match(/^GIF89a/)) {
            return 'gif';
        } else if (header.match(/^\xff\xd8/)) {
            return 'jpeg';
        } else {
            // デフォルトはPNG画像として扱う
            return 'png';
        }
    };

    // バイナリデータをBase64文字列に変換する(IE専用)
    this.base64encodeForIE = function (binaryData) {
        // 新規XMLデータを作成
        var xml = new ActiveXObject("Microsoft.XMLDOM");
        xml.loadXML('<?xml version="1.0" ?> <root/>');
        xml.documentElement.setAttribute("xmlns:dt", "urn:schemas-microsoft-com:datatypes");

        // バイナリデータを格納するためのノードを作成
        var node = xml.createElement("file-node");
        node.dataType = "bin.base64";

        // バイナリデータを格納
        node.nodeTypedValue = binaryData;
        xml.documentElement.appendChild(node);

        // そのノードからBASE64エンコード済み文字列を取り出す
        var base64encoded_text = node.text;
        return base64encoded_text;
    };
};

/* Grab Content Page Image Function
 * <parameters>
 * 	accountPath: accountPath
 * 	params: request parameters (data type: json, see below)
 * 			{ 'sid': sid, contentId: 'contentId', pageNo: 'pageNo' }
 * 	success: function(string: this is image binary encoded string)
 * 	error: function(XMLHttpRequest, XMLHttpRequest.status, XMLHttpRequest.statusText)
 */
623
AVWEB.avwGrabContentPageImage = function(accountPath, params, success, error) {
624 625

	// API実行準備
626
	var sysSettings = AVWEB.avwSysSetting();
627 628 629 630
	var apiName = 'webContentPageImage';	// API名

	//url 構築
	var apiUrl;
Masaru Abe committed
631
	apiUrl = ClientData.conf_apiUrl(); //sysSettings.apiUrl;
632
	if(accountPath) {
Masaru Abe committed
633
		apiUrl = AVWEB.format(apiUrl, accountPath)
634 635 636 637 638 639
	}
	apiUrl = apiUrl + '/' + apiName + '/';

	// 送信パラメータの構築
	var requestParams = 'contentId=' + params.contentId + '&sid=' + params.sid + '&pageNo=' + params.pageNo;
	apiUrl += '?' + requestParams + '&isBase64=true';
Masaru Abe committed
640 641 642
	if( ClientData.isStreamingMode() ){
		apiUrl += '&isStreaming=true';
	}
643 644 645 646
	
	// バイナリ形式で画像イメージを取得し、Base64にエンコードする
	var xmlHttp;
	var ie = false;
647 648 649 650 651 652 653 654 655 656
	
	//if(window.ActiveXObject) {
	//	xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
	//	ie = true;
	//} else {
	//xmlHttp = new XMLHttpRequest();
	//}
	
	//IE10以降はXMLHttpRequestを優先して使う
	try{
657
		xmlHttp = new XMLHttpRequest();
658 659 660 661 662
	}catch(e){
		try{
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			ie = true;
		}catch(e){
663
			AVWEB.showSystemError();
664 665
			return;
		}
666
	}
667
	
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
	xmlHttp.open('get', apiUrl);
	xmlHttp.setRequestHeader('X-AGT-AppId', sysSettings.appName);
	xmlHttp.setRequestHeader('X-AGT-AppVersion', sysSettings.appVersion);
	/*
	if(xmlHttp.overrideMimeType) {
		// for FF, Chrome, Safari
		xmlHttp.overrideMimeType('text/plain; charset=x-user-defined');		
	}
	*/
	xmlHttp.onreadystatechange = function () {
	    if (xmlHttp.readyState == 4) {
	        if (xmlHttp.status == 200) {
	            /*
	            //base64 encode
	            var ids = new ImageDataScheme();
683
	            var src; // Image Data URI
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
				
	            if(ie) {
	            // for IE
	            src = ids.convImageToDataScheme(xmlHttp.responseBody, ie);
	            } else {
	            // for FF, Chrome, Safari
	            src = ids.convImageToDataScheme(xmlHttp.responseText, ie);					
	            }
	            */
	            var src; // Image Data URI
	            /*
	            if(ie) {
	            // for IE
	            src = 'data:image/png;base64,' + xmlHttp.responseBody;
	            } else {
	            // for FF, Chrome, Safari
	            src = 'data:image/png;base64,' + xmlHttp.responseText;					
	            }
	            */
	            src = 'data:image/png;base64,' + xmlHttp.responseText;

	            if (success) {
	                success(src);
	            }
	        } else {
	            if (error) {
	                error(xmlHttp, xmlHttp.status, xmlHttp.statusText);
	            } else {
712
	                AVWEB.avwLog(xmlHttp.status + ' ' + xmlHttp.statusText);
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
	            }
	        }
	    }
	};
	xmlHttp.send();
};

/*
 * file upload function: call uploadBackupFile API
 * <params>
 * [
 * 	{ name: 'sid', content: 'content' }
 * 	{ name: 'deviceType', content: '4' }
 * 	{ name: 'formFile', fileName: 'filename', contentType: 'text-plain' }
 * ]
 */
729
AVWEB.avwUploadBackupFile = function(accountPath, params, async, success, error) {
730 731
	
	/* API実行準備*/
732
	var sysSettings = AVWEB.avwSysSetting();
733 734 735 736
	var apiName = 'uploadBackupFile';	// API名
	
	//url 構築
	var apiUrl;
Masaru Abe committed
737
	apiUrl = ClientData.conf_apiUrl(); //sysSettings.apiUrl;
738
	if(accountPath) {
Masaru Abe committed
739
		apiUrl = AVWEB.format(apiUrl, accountPath)
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
	}
	apiUrl = apiUrl + '/' + apiName + '/';
	
	/* POST(multipart/form-data)送信準備 */
	var body = '';
	var boundary = '';

	// boundaryを構築
	var date = new Date();
	boundary = '------------------------' + date.getMilliseconds() 
				+ (date.getMonth() + 1)
				+ date.getMinutes()
				+ date.getFullYear()
				+ date.getDay()
				+ date.getHours()
				+ date.getSeconds();
	
	// bodyを構築
	for(var i = 0; i < params.length; i++) {
		var item = params[i];
		body += '--' + boundary + '\r\n';	
		body += 'Content-Disposition: form-data; name="' + item.name + '"';
		if(item.fileName) {
			body += '; filename="' + item.fileName + '"\r\n';
		} else {
			body += '\r\n';
		}
		if(item.contentType) {
			body += 'Content-Type="' + item.contentType + '"\r\n';
		}
		body += '\r\n';
		body += item.content + '\r\n';
	}
	body += '--' + boundary + '--\r\n';
	
	// ajax によるAPIの実行(json)
	$.ajax( {
		async:		(async) ? async : false,
		type:		'post',
		url:		apiUrl,
		data:		body,
		beforeSend:	function(xhr) {
			/*
			 * ABook viewer for WEB 用のリクエストヘッダに、以下のヘッダを付加する
			 * X-AGT-AppId: ABookWebCL
			 * X-AGT-AppVersion: 0.0.1
			 */
			xhr.setRequestHeader('X-AGT-AppId', sysSettings.appName);
			xhr.setRequestHeader('X-AGT-AppVersion', sysSettings.appVersion);
			
			/*
			 * uploadBackupFileは multipart/form-data でPOST送信する
			 */
            xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
Masaru Abe committed
794
            //xhr.setRequestHeader('Content-Length', AVWEB.getByte(body));
795 796 797
		},
		success:	function(data) {
			if(success) {
Masaru Abe committed
798
				success(data);
799 800 801 802 803 804 805
			}
		},
		error:		function(xmlHttpRequest, txtStatus, errorThrown) {
			/* call custom error process */
			if(error) {
				error(xmlHttpRequest, txtStatus, errorThrown);
			} else {
806
				AVWEB.showSystemError();
807 808 809 810 811
			}
		}
	});	
};
/* show system error message */
812
AVWEB.showSystemError = function(textId) {
813
	
814
	if(AVWEB.avwHasError()) {
815 816 817 818
		// すでにエラー状態であればエラーを表示しない
		return;
	} else {
		// エラー状態にセット
819
		AVWEB.avwSetErrorState();
820 821
	}
	
822 823 824 825
	if( !textId ){
		textId = 'sysErrorCallApi01';
	}
	
826
	// create DOM element for showing error message
827
	var errMes = I18N.i18nText(textId);
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
	var tags = '<div id="avw-sys-error"></div>';
	//$('body').prepend(tags);
	$('body').append(tags);
	$('#avw-sys-error').css({
	    'opacity': 0.7,
	    'position': 'fixed',
	    'top': '0',
	    'left': '0',
	    'width': $(window).width(),
	    'height': $(window).height(),
	    'background': '#999',
	    'z-index': 90000
	});
	// resize error page	
	$(window).resize(function() {
		$('#avw-sys-error').css( {
			'width': $(window).width(),
			'height': $(window).height()
		});			
	});
	// show error messages
	$().toastmessage({ position: 'middle-center' });
	$().toastmessage('showToast', {
		type: 'error',
		sticky: true,
853 854
		text: errMes,
		close: function() {
Masaru Abe committed
855 856 857 858 859
			if( ClientData.isStreamingMode() == false ){
				//ストリーミングでなければログアウト時と同じ後始末処理をしてログイン画面に戻す
				if( !HEADER.webLogoutEvent() ){
					//ログアウト出来なかった
					SessionStorageUtils.clear();
860
					//カスタムURI起動対応のため sidのバックアップは消さない
Masaru Abe committed
861
					AVWEB.avwUserSetting().remove(COMMON.Keys.userInfo_sid);
862
					//AVWEB.avwUserSetting().remove(COMMON.Keys.userInfo_sid_bak);
Masaru Abe committed
863 864
					AVWEB.avwScreenMove(COMMON.ScreenIds.Login);
				}
865 866 867
			}
		}
	});
868 869 870 871 872 873 874 875 876 877
/*
	$().toastmessage('showToast', {
		type: 'error',
		sticky: true,
		text: errMes,
		close: function() { isShowErrorMessage = false; }
	});				
*/
};
/* エラー状態を取得 */
878
AVWEB.avwHasError = function() {
879 880 881
	var session = window.sessionStorage;
	var isError = false;
	if(session) {
Masaru Abe committed
882
		isError = session.getItem(AVWEB.hasErrorKey);
883 884 885 886
	}
	return (isError == 'true');
};
/* エラー状態にセット */
887
AVWEB.avwSetErrorState = function() {
888 889
	var session = window.sessionStorage;
	if(session) {
Masaru Abe committed
890
		session.setItem(AVWEB.hasErrorKey, true);
891 892 893
	}
};
/* エラー状態をクリア */
894
AVWEB.avwClearError = function() {
895 896
	var session = window.sessionStorage;
	if(session) {
Masaru Abe committed
897
		session.setItem(AVWEB.hasErrorKey, false);
898 899 900
	}
};
/* ブラウザunload時に警告メッセージの出力設定を行う関数 */
901
AVWEB.avwSetLogoutNortice = function() {
902
	window.onbeforeunload = function(event) {
Masaru Abe committed
903 904 905 906 907
		if(ClientData.isGetitsMode() || ClientData.isStreamingMode()){
			if(ClientData.isGetitsMode()){
				COMMON.SetEndLog(CONTENTVIEW_GENERAL.contentID);
				COMMON.RegisterLog();
			}
Masaru Abe committed
908 909 910
		} else {
			// メッセージ表示
			// FFでは、https://bugzilla.mozilla.org/show_bug.cgi?id=588292 によりメッセージが出力されない
911
			var message = I18N.i18nText('sysInfoWithoutLogout');
Masaru Abe committed
912 913 914 915 916 917
			var e = event || window.event;
			if(e) {
				e.returnValue = message;
			} 
			return message;
		}
918 919 920
	};
};
/* 警告メッセージを出力しないでページ遷移を行う関数 */
921
AVWEB.avwScreenMove = function(url) {
922 923 924 925
	window.onbeforeunload = null;
	window.location = url;
};
/* Debug Log */ 
926 927
AVWEB.avwLog = function(msg) {
	if(AVWEB.avwSysSetting().debug) {
Masaru Abe committed
928
		console.log(msg);
929 930
	}
};
931

Masaru Abe committed
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
/* get bytes of text */
AVWEB.getByte = function(text) {
	var count = 0;
	var n;
	for(var i=0; i<text.length; i++) {
		n = escape(text.charAt(i));
		if (n.length < 4) {
			count++;
		}
		else {
			count+=2;
		}
	}
	return count;
};

AVWEB.getApiUrl = function(accountPath) {
949 950

	// url 構築
951
	//var sysSettings = AVWEB.avwSysSetting();
Masaru Abe committed
952
	var apiUrl = ClientData.conf_apiUrl(); //sysSettings.apiUrl;
953
	if(accountPath) {
Masaru Abe committed
954
		apiUrl = AVWEB.format(apiUrl, accountPath);
955 956 957
	}
	return apiUrl;
	
Masaru Abe committed
958 959 960 961
};

/* get url */
AVWEB.getURL = function(apiName) {
962
    //var sysSettings = AVWEB.avwSysSetting();
Masaru Abe committed
963 964 965 966 967 968
    
    var isStreaming = "false";
    if(ClientData.isStreamingMode()){
        isStreaming = "true";
    }
    
Masaru Abe committed
969
    var url = ClientData.conf_apiResourceDlUrl(); //sysSettings.apiResourceDlUrl;
Masaru Abe committed
970 971
    url = AVWEB.format(url, ClientData.userInfo_accountPath()) + '/' + apiName + '/?isStreaming=' + isStreaming;
    
Masaru Abe committed
972 973 974 975 976 977 978 979 980 981 982 983
    return url;
};

/* String.format function def. */
AVWEB.format = function(fmt) {
    for (var i = 1; i < arguments.length; i++) {
        var reg = new RegExp("\\{" + (i - 1) + "\\}", "g");
        fmt = fmt.replace(reg,arguments[i]);
    }
    return fmt;
};