﻿////////// global + api + xmlhttprequest + commonJS /////////////


//////////////////////////  global.js ///////////////////////////////////////


String.prototype.chop = function() {
	return this;
}

function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}

String.prototype.nl2br = function() {
	return this.split('\n').join('<br \/>\n');
}

String.prototype.replace = function(find,replace) {
	return this.split(find).join(replace);
}

String.prototype.escapeForXML = function() {
	return this.replace('&', '&amp;').replace('"', '&quot;').replace('<', '&lt;').replace('>', '&gt;');
}

String.prototype.escapeForDisplay = function() {
	return this.replace('<', '&lt;');
}


function okForXMLHTTPREQUESTandResponseXML(){
	if (global_fakeOperaXMLHttpRequestSupport) return false; // this is set in xmlhtttprequest.js
	return okForXMLHTTPREQUEST();
}

function okForXMLHTTPREQUEST(){
	if (!window.XMLHttpRequest) return false;
	if (navigator.appVersion.toLowerCase().indexOf("mac") > 0 && navigator.userAgent.indexOf('MSIE') > 0 && navigator.userAgent.indexOf('Opera') == -1) return false;
	return true;
}

function insertMarketBankerScript(divholder, div) {
	var mb_holderdiv = document.getElementById(divholder);
	var mb_scriptdiv = document.getElementById(div);
	if (!mb_scriptdiv || !mb_holderdiv) {
		return;
	}
	mb_scriptdiv.innerHTML = mb_holderdiv.innerHTML;
		
	//alert(mb_scriptdiv.innerHTML)
}


function escape_utf8(data) {

	if (data == '' || data == null){
		return '';
	}
	data = data.toString();
	var buffer = '';
	for(var i=0; i<data.length; i++){
		var c = data.charCodeAt(i);
		var bs = new Array();

		if (c > 0x10000){
			// 4 bytes
			bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
			bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
			bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
			bs[3] = 0x80 | (c & 0x3F);

		}else if (c > 0x800){
			// 3 bytes
			bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
			bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
			bs[2] = 0x80 | (c & 0x3F);

		}else if (c > 0x80){
			// 2 bytes
			bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
			bs[1] = 0x80 | (c & 0x3F);

		}else{
			// 1 byte
			bs[0] = c;
		}

		for(var j=0; j<bs.length; j++){
			var b = bs[j];
			var hex = nibble_to_hex((b & 0xF0) >>> 4) + nibble_to_hex(b & 0x0F);
			buffer += '%'+hex;
		}
	}

	return buffer;
}

function nibble_to_hex(nibble){
	var chars = '0123456789ABCDEF';
	return chars.charAt(nibble);
}




// srcElement getter courtesy Erik Arvidsson
// http://www.webfx.nu/dhtml/ieemu/eventobject.html
if (!document.all) {
	Event.prototype.__defineGetter__("srcElement", function () {
		var node = this.target;
		while (node.nodeType != 1) node = node.parentNode;
		return node;
	});
}


// findPosX & findPosY courtesy PPK
// http://www.quirksmode.org/js/findpos.html
function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x) curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y) curtop += obj.y;
	return curtop;
}

_pi = function(str) {
	return parseInt(str);
}
_ge = function(id) {
	return document.getElementById(id);
}

function decorate() {
	var el = arguments[0];
	if (!el) return;
	arguments[0] = el;
	if (window['decorate_'+el.className]) return window['decorate_'+el.className](arguments);
}


//////////////////////////////// api.js //////////////////////////////////////////


var photo_hash = {};
var set_hash = {};

var hexunAPI = {};
hexunAPI.callMethod = function(APIMethod, params, listener, testingURL, attempts) {
	
	if (typeof params != 'object') params = {}; // because we are going to stick a few things in even if no params are passed
	params.method = APIMethod; // see? And this also makes sure a method parameter is not passed
	
	var RESTURLROOT = '/ResponseClient.aspx';
	var RESTURL='';
	for (var p in params) {
		if(RESTURL=='')
			RESTURL=p + '=' + escape_utf8(params[p]);
		else
			RESTURL+= '&' + p + '=' + escape_utf8(params[p]);
	}
	
	params.RESTURL = RESTURL; // again. we stick this in here because we pass params to the callback, and it might want to see the URL
	
	var attempts = (attempts == undefined) ? 1 : attempts;
	var req = new XMLHttpRequest();
	if (req) {
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				if (req.responseText == '' && attempts<2) {
					attempts++;
					req.abort();
					hexunAPI.callMethod(APIMethod, params, listener, testingURL, attempts);
				} else {
					hexunAPI.handleResponseForTitle(req.responseXML, APIMethod, params, req.responseText, listener);
				}
			}
		}
		if (testingURL) RESTURLROOT = testingURL;
		req.open('POST', RESTURLROOT);
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

		req.send(RESTURL);
	}
}


hexunAPI.getCallBackName = function (dotted) {
	return dotted.split('.').join('_')+'_onLoad';
}

hexunAPI.handleResponseForTitle = function(responseXML, APIMethod, params, responseText, listener) {
	if (!responseXML) { //OPERA!
		var success = (responseText.indexOf('stat="ok"') > -1) ? true : false;
	} else {
		var success = (responseXML.documentElement && responseXML.documentElement.getAttribute('stat') == 'ok') ? true : false;
	}
	listener = (listener) ? listener : this;
	listener[this.getCallBackName(APIMethod)](success, responseXML, responseText);
}

// FOR A SET'S PAGE

initPageSetDescription_div = function(set_id) {
	if (!okForXMLHTTPREQUEST()) return false; 
	var div = initGenericDescription_div(set_id, set_hash);
	div.getInput = function() {
		return '<textarea name="content" style="font-family:arial; font-size:12px; padding:3px; margin-top:14px; width:100%; height:75px;border:1px inset #e9e9ae; background-color:#ffffd3; margin-bottom:5px;">'+this.form_content+'<\/textarea>';
	}
	return true;
}

initPageSetTitle_div = function(set_id) {
	if (!okForXMLHTTPREQUEST()) return false; 
	var div = initGenericTitle_div(set_id, set_hash);
	div.getInput = function() {
		return '<input name="content" value="'+this.form_content.replace('"', '&#34;')+'" style="font-size:32px; font-family:arial; padding:3px; width:100%; border:1px inset #e9e9ae; background-color:#ffffd3; margin-bottom:5px;">';
	}
	div.getExtra = function() {
		return '<br>';
	}
	return true;
}

// FOR PHOTO.GNE

initPagePhotoDescription_div = function(photo_id) {
	if (!okForXMLHTTPREQUEST()) return false; 
	var div = initGenericDescription_div(photo_id, photo_hash);
	div.getInput = function() {
		return '<textarea name="content" style="font-family:arial; font-size:12px; padding:3px; margin-top:0px; width:100%; height:100px; border:1px inset #e9e9ae; background-color:#ffffd3; margin-bottom:5px;">'+this.form_content+'<\/textarea>';
	}
	div.getExtra = function() {
		return '<br>';
	}
	return true;
}

initPagePhotoTitle_div = function(photo_id) {
	if (!okForXMLHTTPREQUEST()) return false; 
	var div = initGenericTitle_div(photo_id, photo_hash);
	div.getInput = function() {
		return '<input name="content" value="'+this.form_content.replace('"', '&#34;')+'" style="font-size:22px; font-weight: bold; font-family: Arial; padding:4px; width:100%; border:1px inset #e9e9ae; background-color:#ffffd3; margin-bottom:5px;">';
	}
	div.getExtra = function() {
		return '<br>';
	}
	return true;
}

// FOR PHOTOS/USER PAGES

initPhotosUserPageDescription_div = function(photo_id) {
	if (!okForXMLHTTPREQUEST()) return false; 
	var div = initGenericDescription_div(photo_id, photo_hash);
	div.getInput = function() {
		return '<textarea name="content" style="font-family:arial; font-size:12px; padding:3px; margin-top:0px; width:240px; height:75px;border:1px inset #e9e9ae; background-color:#ffffd3; margin-bottom:5px;">'+this.form_content+'<\/textarea>';
	}
	return true;
}

initPhotosUserPageTitle_div = function(photo_id) {
	if (!okForXMLHTTPREQUEST()) return false; 
	var div = initGenericTitle_div(photo_id, photo_hash);
	div.getInput = function() {
		return '<input name="content" value="'+this.form_content.replace('"', '&#34;')+'" style="font-size:14px; font-weight:bold; font-family:arial; padding:3px; width:240px; border:1px inset #e9e9ae; background-color:#ffffd3; margin-bottom:5px;" \/>';
	}
	return true;
}


// FOR ALL PAGES

initGenericDescription_div = function(hash_id, hash) {
	if (!okForXMLHTTPREQUEST()) return false; 
	var div = document.getElementById('description_div'+hash_id);
	div.title = '点击编辑';
	div.hash_id = hash_id;
	if (!hash[div.hash_id]) {
		alert('ERROR: no hash ob exists for '+div.hash_id);
		return false;
	}
	div.form_content = hash[div.hash_id].description;
	div.emptyText = '单击此处添加描述';
	
	div.getExtra = function() {
		return '';
	}
	
	div.saveChanges = function(form) {
		hash[this.hash_id].description = form.content.value;
		this.innerHTML = '<i>保存...</i>';
		this.endEditing();
		hexunAPI.hexun_photos_setMeta_onLoad = hexunAPI.hexun_photosets_editMeta_onLoad = function(success, responseXML) {
			if (success) {
				div.form_content = hash[div.hash_id].description;
				div.innerHTML = (hash[div.hash_id].description=='') ? '&nbsp;' : hash[div.hash_id].description.chop().nl2br();
			} else {
				hash[div.hash_id].description = div.form_content;
				div.innerHTML = (hash[div.hash_id].description=='') ? '&nbsp;' : hash[div.hash_id].description.chop().nl2br();
				alert('Error: your description was NOT saved.');
			}
		}
		if (!hash[this.hash_id]) {
			this.innerHTML = 'ERROR: no hash ob exists for '+this.hash_id;
			return false;
		}
		if (hash == set_hash) {
			hexunAPI.callMethod('hexun.photosets.editMeta', {photoset_id:this.hash_id, title:hash[this.hash_id].title, description:hash[this.hash_id].description});
		} else if (hash == photo_hash)  {
			hexunAPI.callMethod('hexun.photos.setMeta', {photo_id:this.hash_id, title:hash[this.hash_id].title, description:hash[this.hash_id].description});
		} else {
			alert('unknown hash')
		}
	}
	return initEditable_div(div);
}

initGenericTitle_div = function(hash_id, hash) {
	if (!okForXMLHTTPREQUEST()) return false; 
	var div = document.getElementById('title_div'+hash_id);
	div.title = '点击编辑';
	div.hash_id = hash_id;
	if (!hash[div.hash_id]) {
		alert('ERROR: no hash ob exists for '+div.hash_id);
		return false;
	}
	div.form_content = hash[div.hash_id].title;
	
	div.emptyText = '单击此处添加标题';
	
	div.getExtra = function() {
		return '';
	}
	
	div.saveChanges = function(form) {
		hash[this.hash_id].title = form.content.value;
		this.innerHTML = '<i>保存...</i>';
		this.endEditing();
		hexunAPI.hexun_photos_setMeta_onLoad = hexunAPI.hexun_photosets_editMeta_onLoad = function(success, responseXML, responseText) {
			if (success) {
				div.form_content = hash[div.hash_id].title;
				div.innerHTML = (hash[div.hash_id].title=='') ? '&nbsp;' : hash[div.hash_id].title.escapeForDisplay();
			} else {
				hash[div.hash_id].title = div.form_content;
				div.innerHTML = (hash[div.hash_id].title=='') ? '&nbsp;' : hash[div.hash_id].title.escapeForDisplay();
				
				alert('错误: 未能成功保存图片标题。');
			}
		}
		if (!hash[this.hash_id]) {
			this.innerHTML = 'ERROR: no hash ob exists for '+this.hash_id;
			return false;
		}
		
		if (hash == set_hash) {
			hexunAPI.callMethod('hexun.photosets.editMeta', {photoset_id:this.hash_id, title:hash[this.hash_id].title, description:hash[this.hash_id].description});
		} else if (hash == photo_hash)  {
			hexunAPI.callMethod('hexun.photos.setMeta', {photo_id:this.hash_id, title:hash[this.hash_id].title, description:hash[this.hash_id].description});
		} else {
			alert('unknown hash')
		}
	}
	
	return initEditable_div(div);
}

initEditable_div = function(div) {
	div.startEditing = function() {
		this.isEditing = true;
		this.unhighlight();
		this.style.display = 'none';
		var form_div = this.getForm_div();
		form_div.style.display = 'block';
		var form = form_div.firstChild;
		form.content.focus();
		form.content.select();
	}
	div.endEditing = function() {
		this.isEditing = false;
		var form_div = this.getForm_div();
		form_div.innerHTML = '';
		form_div.style.display = 'none';
		this.style.display = 'block';
	}
	div.onclick = div.startEditing;
	
	div.getForm_div = function() {
		if (!this.form_div) {
			this.form_div = document.createElement('div');
			this.parentNode.insertBefore(this.form_div, this);
			this.form_div.display_div = this;
		}
		
		var formHTML = '<form onsubmit="this.parentNode.display_div.saveChanges(this); return false;" style="margin-left:'+this.style.marginLeft+'" style="margin-right:'+this.style.marginRight+'">';
		formHTML+= this.getInput();
		formHTML+= '<br \/><input type=image src="/img/img_bc.gif" align=absmiddle \/>&nbsp;&nbsp;<span style="font-family:arial; font-size:12px;">或</span>&nbsp;&nbsp;<input type=image align=absmiddle  src=/img/img_qx.gif onclick=this.form.parentNode.display_div.endEditing(); \/><\/form>';
		formHTML+= this.getExtra();
		this.form_div.innerHTML = formHTML
		return this.form_div;
	}
	
	div.onmouseover = function() {
		this.highlight();
	}
	
	div.onmouseout = function() {
		if (this.hideTimer) clearTimeout(this.hideTimer);
		this.hideTimer = setTimeout('document.getElementById("'+this.id+'").unhighlight()', 1000)
	}
	
	div.highlight = function() {
		if (this.hideTimer) clearTimeout(this.hideTimer);
		div.style.backgroundColor = '#ffffd3';
		if (this.emptyText && (div.innerHTML=='&nbsp;' || div.innerHTML==' ' || div.innerHTML.charCodeAt(0) == 160)) {
			div.style.fontStyle = 'italic';	
			div.style.color = '#888';	
			div.innerHTML = this.emptyText;
		}
	}
	
	div.unhighlight = function() {
		if (this.hideTimer) clearTimeout(this.hideTimer);
		div.style.backgroundColor = '';
		if (this.emptyText && div.innerHTML==this.emptyText) {
			div.innerHTML = '&nbsp;';
			div.style.fontStyle = 'normal';
			div.style.color = '#000';
		}
	}
	return div;
}
hexunAPI.hexun_test_echo_onLoad = function(success, responseXML) {
	var mom = responseXML.documentElement;
	var str = '';
	for (var t=0;t<mom.childNodes.length;t++) {
		var node = mom.childNodes[t];
		if (node.nodeType != 3 && node.nodeType != 8) {
			str+= node.nodeType+' '+node.nodeName+' '+node.firstChild.nodeValue+' ';
		}
	}
	alert(str);
}

hexunAPI.hexun_photos_getInfo_onLoad = function(success, responseXML) {
	var tags = responseXML.documentElement.getElementsByTagName('tag');
	if (responseXML.documentElement.getElementsByTagName('description')[0].firstChild) {
		var description = responseXML.documentElement.getElementsByTagName('description')[0].firstChild.nodeValue;
	} else {
		var description = '<i>add your description here.<\/i>';
	}
	var title = responseXML.documentElement.getElementsByTagName('title')[0].firstChild.nodeValue;
	var str = title+'/'+description+'/ ';
	for (var t=0;t<tags.length;t++) {
		var node = tags[t];
		if (node.nodeType != 3 && node.nodeType != 8) {
			str+= node.nodeType+' '+node.nodeName+' '+node.firstChild.nodeValue+' ';
		}
	}
	document.getElementById('title_div').innerHTML = title.escapeForDisplay();
	document.getElementById('description_div').innerHTML = description.chop().nl2br();
}


function rebuild_tags_for_photo_hash(photo_id, tags) {
	if (photo_hash[photo_id] == undefined) return;
	photo_hash[photo_id].tagsA = [];
	photo_hash[photo_id].tags_rawA = [];
	photo_hash[photo_id].tags_idA = [];
	photo_hash[photo_id].tags_canDeleteA = [];
	for (var t=0;t<tags.length;t++) {
		var node = tags[t];
		
		var tag = node.firstChild.nodeValue; // this is clean
		var tag_raw = node.getAttribute('raw');
		var tagId = node.getAttribute('id');
		var adderId = node.getAttribute('author');
		var canDelete = (photo_hash[photo_id].isOwner || global_nsid == adderId) ? true : false;
		
		photo_hash[photo_id].tagsA.push(tag);
		photo_hash[photo_id].tags_rawA.push(tag_raw);
		photo_hash[photo_id].tags_idA.push(tagId);
		photo_hash[photo_id].tags_canDeleteA.push(canDelete);
	}
}


ManageFlag = function(itemID,isFlaged,feedID) 
{
	var listener = document.getElementById("divTitleFlag_"+itemID);
	listener.hexun_photos_AddFlag_onLoad = function(success, responseXML, responseText) 
	{	
		if (success) 
		{
			if(responseXML.documentElement.getElementsByTagName('flag')[0].firstChild.nodeValue=="2")
			{
				GotoLogin();
			}
			else if(responseXML.documentElement.getElementsByTagName('flag')[0].firstChild.nodeValue=="1")
			{
				//flag succeed
				document.getElementById("divTitleFlag_"+itemID).innerHTML = document.getElementById("divTitleFlag_"+itemID).innerHTML.replace("/img/FeedItem001.GIF","/img/FeedItem003.GIF").replace("/img/FeedItem002.GIF","/img/FeedItem003.GIF");//"<img src=/img/flag.gif>"+document.getElementById("divTitle_"+itemID).innerHTML;
				document.getElementById("divFlag_"+itemID).innerHTML  = "<a href=javascript:ManageFlag('"+itemID+"','1') class='org'>取消标记</a>";
			}
			else
			{
				//Unflag succeed
				document.getElementById("divTitleFlag_"+itemID).innerHTML = document.getElementById("divTitleFlag_"+itemID).innerHTML.replace("/img/FeedItem002.GIF","/img/FeedItem001.GIF").replace("/img/FeedItem003.GIF","/img/FeedItem001.GIF");
				document.getElementById("divFlag_"+itemID).innerHTML  = "<a href=javascript:ManageFlag('"+itemID+"','0') class='org'>标记为重要</a>";
				
			}									
		} 
		else 
		{
			alert("无法修改！");
		}
	}
	hexunAPI.callMethod('hexun.photos.AddFlag', {itemID1:itemID, ManageFlagOp:1, isFlaged1:isFlaged, feedID1:feedID}, listener);
	
	return ;
} 

MarkUnread = function(itemID) 
{
	var listener = document.getElementById("divTitle_"+itemID);
	listener.hexun_photos_MarkItemUnread_onLoad = function(success, responseXML, responseText) 
	{	
		if (success) 
		{
			if(responseXML.documentElement.getElementsByTagName('mark')[0].firstChild.nodeValue=="2")
			{
				GotoLogin();
			}
			else
			{
				document.getElementById("divTitle_"+itemID).innerHTML =document.getElementById("divTitle_"+itemID).innerHTML.replace("itemRead","itemUnRead");//"<font class='uhei5'>"+responseXML.documentElement.getElementsByTagName('mark')[0].firstChild.nodeValue+"</font>" ;								
			}
		} 
		else 
		{
			alert("错误！");
		}
	}
	hexunAPI.callMethod('hexun.photos.MarkItemUnread', {itemID1:itemID, markUnreadOp:1}, listener);
	return ;
} 

initfriend_div = function(friendID) 
{
	var listener = document.getElementById('Friend_div');
	listener.hexun_photos_AddFriend_onLoad = function(success, responseXML, responseText) 
	{	
		if (success) 
		{
			if(responseXML.documentElement.getElementsByTagName('friend')[0].firstChild.nodeValue=="请先登录")
			{
				alert("请先登录");
				return;
			}
			else
			{
				document.getElementById("Friend_div").innerHTML ="<font color=#9a9a9a>"+responseXML.documentElement.getElementsByTagName('friend')[0].firstChild.nodeValue+"</font>" ;								
			}
		} 
		else 
		{
			alert("错误！");
		}
	}
	hexunAPI.callMethod('hexun.photos.AddFriend', {friend:friendID}, listener);	
	
	return ;
}


/////////////////////////////////////////////// xmlhttprequest.js /////////////////////////////////////////////////////


/*

Cross-Browser XMLHttpRequest v1.1
=================================

Emulate Gecko 'XMLHttpRequest()' functionality in IE and Opera. Opera requires
the Sun Java Runtime Environment <http://www.java.com/>.

by Andrew Gregory
http://www.scss.com.au/family/andrew/webdesign/xmlhttprequest/

This work is licensed under the Creative Commons Attribution License. To view a
copy of this license, visit http://creativecommons.org/licenses/by/1.0/ or send
a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305,
USA.

Not Supported in Opera
----------------------
* user/password authentication
* responseXML data member

Not Fully Supported in Opera
----------------------------
* async requests
* abort()
* getAllResponseHeaders(), getAllResponseHeader(header)

*/
// IE support
if (window.ActiveXObject && !window.XMLHttpRequest) {
  window.XMLHttpRequest = function() {
    return new ActiveXObject((navigator.userAgent.toLowerCase().indexOf('msie 5') != -1) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP');
  };
}
// Gecko support
/* ;-) */
// Opera support
global_fakeOperaXMLHttpRequestSupport = false;
//if (window.opera && !window.XMLHttpRequest) { THIS IS COMMENTED OUT BECAUSE OPERA 8 has window.XMLHttpRequest but still does not support setRequestHeader
if (window.opera) {
	global_fakeOperaXMLHttpRequestSupport = true;
  window.XMLHttpRequest = function() {
    this.readyState = 0; // 0=uninitialized,1=loading,2=loaded,3=interactive,4=complete
    this.status = 0; // HTTP status codes
    this.statusText = '';
    this._headers = [];
    this._aborted = false;
    this._async = true;
    this.abort = function() {
      this._aborted = true;
    };
    this.getAllResponseHeaders = function() {
      return this.getAllResponseHeader('*');
    };
    this.getAllResponseHeader = function(header) {
      var ret = '';
      for (var i = 0; i < this._headers.length; i++) {
        if (header == '*' || this._headers[i].h == header) {
          ret += this._headers[i].h + ': ' + this._headers[i].v + '\n';
        }
      }
      return ret;
    };
    this.setRequestHeader = function(header, value) {
      this._headers[this._headers.length] = {h:header, v:value};
    };
    this.open = function(method, url, async, user, password) {
		
		//alert(method+"]["+url+"]["+async+"]["+user+""+""+"");
      this.method = method;
      this.url = url;
      this._async = true;
      this._aborted = false;
      if (arguments.length >= 3) {
        this._async = async;
      }
      if (arguments.length > 3) {
        // user/password support requires a custom Authenticator class
        opera.postError('XMLHttpRequest.open() - user/password not supported');
      }
      this._headers = [];
      this.readyState = 1;
      if (this.onreadystatechange) {
        this.onreadystatechange();
      }
    };
    this.send = function(data) {
      if (!navigator.javaEnabled()) {
        alert("XMLHttpRequest.send() - Java must be installed and enabled.");
        return;
      }
      if (this._async) {
        setTimeout(this._sendasync, 0, this, data);
        // this is not really asynchronous and won't execute until the current
        // execution context ends
      } else {
        this._sendsync(data);
      }
    }
    this._sendasync = function(req, data) {
      if (!req._aborted) {
        req._sendsync(data);
      }
    };
    this._sendsync = function(data) {
      this.readyState = 2;
      if (this.onreadystatechange) {
        this.onreadystatechange();
      }
      // open connection
      var url = new java.net.URL(new java.net.URL(window.location.href), this.url);
      var conn = url.openConnection();
      for (var i = 0; i < this._headers.length; i++) {
        conn.setRequestProperty(this._headers[i].h, this._headers[i].v);
      }
      this._headers = [];
      if (this.method == 'POST') {
        // POST data
        conn.setDoOutput(true);
        var wr = new java.io.OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        wr.close();
      }
      // read response headers
      // NOTE: the getHeaderField() methods always return nulls for me :(
      var gotContentEncoding = false;
      var gotContentLength = false;
      var gotContentType = false;
      var gotDate = false;
      var gotExpiration = false;
      var gotLastModified = false;
      for (var i = 0; ; i++) {
        var hdrName = conn.getHeaderFieldKey(i);
        var hdrValue = conn.getHeaderField(i);
        if (hdrName == null && hdrValue == null) {
          break;
        }
        if (hdrName != null) {
          this._headers[this._headers.length] = {h:hdrName, v:hdrValue};
          switch (hdrName.toLowerCase()) {
            case 'content-encoding': gotContentEncoding = true; break;
            case 'content-length'  : gotContentLength   = true; break;
            case 'content-type'    : gotContentType     = true; break;
            case 'date'            : gotDate            = true; break;
            case 'expires'         : gotExpiration      = true; break;
            case 'last-modified'   : gotLastModified    = true; break;
          }
        }
      }
      // try to fill in any missing header information
      var val;
      val = conn.getContentEncoding();
      if (val != null && !gotContentEncoding) this._headers[this._headers.length] = {h:'Content-encoding', v:val};
      val = conn.getContentLength();
      if (val != -1 && !gotContentLength) this._headers[this._headers.length] = {h:'Content-length', v:val};
      val = conn.getContentType();
      if (val != null && !gotContentType) this._headers[this._headers.length] = {h:'Content-type', v:val};
      val = conn.getDate();
      if (val != 0 && !gotDate) this._headers[this._headers.length] = {h:'Date', v:(new Date(val)).toUTCString()};
      val = conn.getExpiration();
      if (val != 0 && !gotExpiration) this._headers[this._headers.length] = {h:'Expires', v:(new Date(val)).toUTCString()};
      val = conn.getLastModified();
      if (val != 0 && !gotLastModified) this._headers[this._headers.length] = {h:'Last-modified', v:(new Date(val)).toUTCString()};
      // read response data
      var reqdata = '';
      var stream = conn.getInputStream();
      if (stream) {
        var reader = new java.io.BufferedReader(new java.io.InputStreamReader(stream));
        var line;
        while ((line = reader.readLine()) != null) {
          if (this.readyState == 2) {
            this.readyState = 3;
            if (this.onreadystatechange) {
              this.onreadystatechange();
            }
          }
          reqdata += line + '\n';
        }
        reader.close();
        this.status = 200;
        this.statusText = 'OK';
        this.responseText = reqdata;
        this.readyState = 4;
        if (this.onreadystatechange) {
          this.onreadystatechange();
        }
        if (this.onload) {
          this.onload();
        }
      } else {
        // error
        this.status = 404;
        this.statusText = 'Not Found';
        this.responseText = '';
        this.readyState = 4;
        if (this.onreadystatechange) {
          this.onreadystatechange();
        }
        if (this.onerror) {
          this.onerror();
        }
      }
    };
  };
}
// ActiveXObject emulation
if (!window.ActiveXObject && window.XMLHttpRequest) {
  window.ActiveXObject = function(type) {
    switch (type.toLowerCase()) {
      case 'microsoft.xmlhttp':
      case 'msxml2.xmlhttp':
        return new XMLHttpRequest();
    }
    return null;
  };
}


/////////////////////////////////////////// commonJS.js ////////////////////////////////////////////////////////


//replace before Space and end Space in the String "str"
function trim(str)
{
	var str1,str2
	str1=str
	str2=ltrim(str1)
	return rtrim(str2)
}

//replace before Space  in the String "str"
function ltrim(str)
{
	var len,strTemp,strSub,i
	strTemp=new String(str)
	strSub=new String(strTemp)
	len=strTemp.length
	i=0
	if (len<1) 
		{ return "";}
	else
	{
	while (len>=1)
		{
			if (strTemp.charAt(i)==" ")
			{
				strSub=strTemp.substring(i+1);
				len=strSub.length;
				i=i+1;
				}
			else
			return strSub;
			}
			return ""
		}
			
}

//replace end Space in the String "str"
function rtrim(str)
{
	var len,strTemp,strSub,i
	strTemp=new String(str)
	strSub=new String(strTemp)
	len=strTemp.length
	i=len
	if (len<1) 
		{ return "";}
	else
	{
	    while (len>=1)
		{
			if (strTemp.charAt(i-1)==" ")
			{strSub=strTemp.substring(0,i-1);
				len=strSub.length;
				i=i-1;}
			else
				{return strSub;}
		}
		return ""
	}
	
}

