﻿
function cnLength(Str) 
		{
			var escStr = escape(Str);
			var numI = 0;
			var escStrlen = escStr.length;
			for (i = 0;  i < escStrlen;  i++) 
			if(escStr.charAt(i) == '%') 
			if(escStr.charAt(++i) == 'u')  numI ++;
			return Str.length+numI;
		}
		
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 = 'http://ssgg.com/ResponseClient.aspx';
	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);
}



//save sound div
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:14px; font-weight:bold; font-family:arial; padding:3px; width:60%; border:1px inset #e9e9ae; background-color:#FFFFd3; margin-bottom:5px;" \/>';		
	}
	div.getExtra = function() {
		return '<br>';
	}
	return true;
}
//sound

String.prototype.getBytes = function() {
    var cArr = this.match(/[^\x00-\xff]/ig);
    return this.length + (cArr == null ? 0 : cArr.length);
}

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) 
	{
		var mycontent = form.content.value;
		var len = mycontent.getBytes();
		if( len > 200 )
		{
			alert("长度超过限制");
			return;
		}
		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 = '错误';
			return false;
		}

		if (hash == set_hash) 
		{
			alert("set");
			hexunAPI.callMethod('hexun.photosets.editMeta', {photoset_id:this.hash_id, title:hash[this.hash_id].title});
		}
		 else if (hash == photo_hash)  
		{
			/*
			if(cnLength(hash[this.hash_id].title) > 65)
			{
				alert("输入的声音太长");
				return;
			}
			*/
			hexunAPI.callMethod('hexun.photos.setMeta', {photo_id:this.hash_id, title:hash[this.hash_id].title});
		} else 
		{
			alert('unknown hash')
		}
	}
	
	return initEditable_div(div);
}

//sound
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 = '<table width=100% border=0 cellpadding=0 cellspacing=0><form onsubmit="this.parentNode.display_div.saveChanges(this); return false;" style="margin-left:'+this.style.marginLeft+'" style="margin-right:'+this.style.marginRight+'">';
		//var formHTML = '<form onsubmit="this.parentNode.display_div.saveChanges(this); return false;" style="margin-left:'+this.style.marginLeft+'" style="margin-right:'+this.style.marginRight+'"><table width=100% border=0 cellpadding=0 cellspacing=0><tr><td width=100% valign=middle>';
		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+= '&nbsp;&nbsp;<input type=image src="/images/img_bc.gif" align=absmiddle \/>&nbsp;&nbsp;<span style="font-family:arial; font-size:12px;">&nbsp;&nbsp;</span>&nbsp;&nbsp;<input type=image align=absmiddle  src=/images/img_qx.gif onclick=this.form.parentNode.display_div.endEditing(); \/><\/td><\/tr><\/form><\/table>';
		//formHTML+= '<tr><td width=100%>&nbsp;&nbsp;<input type=image src="/images/img_bc.gif" align=absmiddle \/>&nbsp;&nbsp;<span style="font-family:arial; font-size:12px;">&nbsp;&nbsp;</span>&nbsp;&nbsp;<input type=image align=absmiddle  src=/images/img_qx.gif onclick=this.form.parentNode.display_div.endEditing(); \/><\/td><\/tr><\/table><\/form>';
		formHTML+= '&nbsp;&nbsp;<input type=image src="/images/img_bc.gif" align=absmiddle \/>&nbsp;&nbsp;<span style="font-family:arial; font-size:12px;">&nbsp;&nbsp;</span>&nbsp;<input type=image align=absmiddle  src=/images/img_qx.gif onclick=this.form.parentNode.display_div.endEditing(); \/><\/form>';
		
		//formHTML+= this.getExtra();
		//alert(formHTML);
		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()', 500)
	}
	var divOldColor="";
	div.highlight = function() {
		if (this.hideTimer) clearTimeout(this.hideTimer);
		div.style.backgroundColor = '#ECF1F4';
		divOldColor = div.style.color;
		div.style.color = '#375A5C';	
		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 = '';
		div.style.color = divOldColor;
		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);
	}
}


function checkUserName_div(username) 
{
	//if(isLogin == 0)
	//	GotoLogin();
	var listener = document.getElementById('UserName_span');
	listener.hexun_photos_SendMessage_onLoad = function(success, responseXML, responseText) 
	{	
		if (success) 
		{
			var xx= responseXML.documentElement.getAttribute('mes');
			if(xx== "ok")
			{
						
				listener.innerHTML = "<font color='green'>您的用户名：<b>"  +username + "</b>可用</font>";
				listener.result = true;
			}
			else
			{
				listener.innerHTML = xx ;
				listener.result = false;
			}							
		} 
		else 
		{
			listener.innerHTML = "错误！";
			listener.result = false;
		}
	}
	hexunAPI.callMethod('hexun.photos.SendMessage', {username:username}, listener);
} 


function getTagByCategory(CategoryId) 
{
	var listener = document.getElementById('tagDiv');

	listener.hexun_photos_getTag_onLoad = function(success, responseXML, responseText) 
	{	
		if (success) 
		{	
           var tags=responseXML.documentElement.getElementsByTagName('phototag');
           var itemsDiv ="";
           if(tags.length>0)
           {
              itemsDiv+="常见标签：";
              for(var t=0;t<tags.length;t++)
              {         
              var id = tags[t].getAttribute('id');
           
              var name = tags[t].getAttribute('name');
                itemsDiv+="<a style='cursor:hand;' onclick=\"funAddTagToInput('"+name+"')\">"+name+"</a>&nbsp;";
              }
            }  
				listener.innerHTML = itemsDiv;		
		} 
	}
	hexunAPI.callMethod('hexun.photos.getTag', {CategoryId:CategoryId}, listener);
} 

function getTagByCategoryForAadmn(CategoryId,aid) 
{
	var listener = document.getElementById("tagDiv_"+aid);

	listener.hexun_photos_getTag_onLoad = function(success, responseXML, responseText) 
	{	
		if (success) 
		{	
           var tags=responseXML.documentElement.getElementsByTagName('phototag');
           var itemsDiv ="";
           if(tags.length>0)
           {
              itemsDiv+="";
              for(var t=0;t<tags.length;t++)
              {         
              var id = tags[t].getAttribute('id');
           
              var name = tags[t].getAttribute('name');
                itemsDiv+="<a style='cursor:hand;' onclick=\"funAddTagToInput('"+aid+"','"+name+"')\">"+name+"</a>&nbsp;";

              }                itemsDiv+=" <input type=\"text\" id=\"txt_"+aid+"\" name=\"txt_"+aid+"\">";

            }  
				listener.innerHTML = itemsDiv;		
		} 
	}
	hexunAPI.callMethod('hexun.photos.getTag', {CategoryId:CategoryId}, listener);
} 


init_SaveMessageInfo=function(parentUserId,loginstate,userId,UserName,Content,type,articleid)//type 0对个人首页，1对文章
{   
   var listener = document.getElementById('xspace-itemreply');
   listener.hexun_photos_MessageInfo_onLoad = function(success, responseXML, responseText) 
	{	
		if(success) 
		{
			ShowMessageInfo(parentUserId,type,articleid);
		}
	
	}
	hexunAPI.callMethod('hexun.photos.MessageInfo', {parentUserId:parentUserId,loginstate:loginstate,userId:userId,UserName:UserName,Content:Content,type:type,articleid:articleid}, listener);	
    return ;
}

ShowMessageInfo=function(parentUserId,type,articleid)
{
    var listener=document.getElementById('xspace-itemreply');
    listener.hexun_photos_ShowMessageInfo_onLoad = function(success, responseXML, responseText)
    {
        if(success)
        {
           var ShowMessageInfoItems=responseXML.documentElement.getElementsByTagName('ShowMessageInfoItem');
           var itemsDiv ="";
           if(ShowMessageInfoItems.length>0)
           {
              for(var t=0;t<ShowMessageInfoItems.length;t++)
              {
                var IsAnonymous = ShowMessageInfoItems[t].getAttribute('IsAnonymous').toLowerCase();

                var UserID = ShowMessageInfoItems[t].getAttribute('UserID');
			    var Content=ShowMessageInfoItems[t].getAttribute('Content');
			   
			    var PostTime=ShowMessageInfoItems[t].getAttribute('PostTime');
			    var url=ShowMessageInfoItems[t].getAttribute('url');
			   
			    var LogoUrl=ShowMessageInfoItems[t].getAttribute('LogoUrl');
			    var UserName =ShowMessageInfoItems[t].getAttribute('UserName');
			   
				if(IsAnonymous=="false")
				itemsDiv+="<dl><dt><img style=\"cursor: pointer;\" title=\"点击图片可在新窗口打开\" src=\""+LogoUrl+"\" class=\"xspace-signavatar xspace-imgstyle\" alt=\"\"><a href="+url+">"+UserName+"</a><span class=\"xspace-smalltxt\">发布于"+PostTime+"</span></dt>";
                else
                itemsDiv+="<dl><dt><img style=\"cursor: pointer;\" src=\""+LogoUrl+"\" class=\"xspace-signavatar xspace-imgstyle\" alt=\"\">"+UserName+"<span class=\"xspace-smalltxt\">发布于"+PostTime+"</span></dt>";

				itemsDiv+="	<dd>"+Content+"</dd></dl>";
				
		    }

		    document.getElementById('xspace-itemreply').innerHTML = itemsDiv;
		  }
        }
    } 
    hexunAPI.callMethod('hexun.photos.ShowMessageInfo', {parentUserId:parentUserId,type:type,articleid:articleid}, listener);	
	return ;
}





delPhotoById = function(delpid)
{		
	document.getElementById("delDIV_"+delpid).innerHTML ='<font color="#FF6600">正在处理中,请稍候..</font>';
	var listener = document.getElementById("delDIV_"+delpid);
	listener.photo_del_photo_onLoad = function(success, responseXML, responseText) 
	{	
		if (success) 
		{
			document.getElementById("delDIV_"+delpid).innerHTML ='<font color="#FF6600">　&nbsp;&nbsp;图片删除成功</font>';
											
		} 
	}

	hexunAPI.callMethod('photo_del_photo', {delpid:delpid}, listener);	
	
	return ;
} 

deleteArticle = function(deleteAid)
{		
	document.getElementById("delSpan_"+deleteAid).innerHTML ='<font color="#FF6600">正在处理中,请稍候..</font>';

	var listener = document.getElementById("delSpan_"+deleteAid);
	listener.ss_del_article_onLoad = function(success, responseXML, responseText) 
	{	
		if (success) 
		{
		  
			document.getElementById("delSpan_"+deleteAid).innerHTML ='<font color="#FF6600">　&nbsp;&nbsp;删除成功</font>';
											
		} 
	}

	hexunAPI.callMethod('ss.del.article', {deleteAid:deleteAid}, listener);	
	
	return ;
} 

updatePhotoTitle = function(pid,phototitle)
{		
	document.getElementById("modify_"+pid).innerHTML ='<font color="#FF6600">正在处理中,请稍候..</font>';

	var listener = document.getElementById("modify_"+pid);
	listener.photo_modify_title_onLoad = function(success, responseXML, responseText) 
	{	
		if (success) 
		{
		  
			document.getElementById("modify_"+pid).innerHTML ='<font color="#FF6600">　&nbsp;&nbsp;图片标题修改成功</font>';
											
		} 
	}

	hexunAPI.callMethod('photo_modify_title', {pid:pid,phototitle:phototitle}, listener);	
	
	return ;
} 

addFriendRequest = function(objectid,userid,username,divid)
{		
	document.getElementById(divid).innerHTML ='<font color="#FF6600">正在处理中,请稍候..</font>';
	var listener = document.getElementById(divid);
	listener.messagerequest_add_friend_onLoad = function(success, responseXML, responseText) 
	{	
		if (success) 
		{
			document.getElementById(divid).innerHTML ='<font color="#FF6600">　&nbsp;&nbsp;请求已发送</font>';
											
		} 
	}
	hexunAPI.callMethod('messagerequest_add_friend', {objectid:objectid,userid:userid,username:username}, listener);	
	
	return ;
} 


initFave_div = function(messageid,objectid,userid,username,type)
{		

	document.getElementById("span_"+messageid).innerHTML ='<font color="#FF6600">正在处理中,请稍候..</font>';
	var listener = document.getElementById("span_"+messageid);
	listener.message_add_friend_onLoad = function(success, responseXML, responseText) 
	{	
		if (success) 
		{
		    var fv = responseXML.documentElement.getElementsByTagName('friend')[0].firstChild.nodeValue;
		    if(fv =="1")
			 document.getElementById("span_"+messageid).innerHTML ='<font color="#FF6600">好友添加成功</font>';
			else
		     document.getElementById("span_"+messageid).innerHTML ='<font color="#FF6600">拒绝成功</font>';

											
		} 
	}

	hexunAPI.callMethod('message_add_friend', {objectid:objectid,userid:userid,username:username,type:type}, listener);	
	
	return ;
} 


getArticlesByKey=function(userid,key)
{

    var listener=document.getElementById('articleDiv');
    listener.ss_article_getArticlesByKey_onLoad = function(success, responseXML, responseText)
    {
        if(success)
        {
          
           var ShowMessageInfoItems=responseXML.documentElement.getElementsByTagName('getArticleInfo');
           var itemsDiv ="";
           if(ShowMessageInfoItems.length>0)
           {  
              for(var t=0;t<ShowMessageInfoItems.length;t++)
              {
                var title = ShowMessageInfoItems[t].getAttribute('title');
                var ClickCount = ShowMessageInfoItems[t].getAttribute('ClickCount');
			    var CommentCount=ShowMessageInfoItems[t].getAttribute('CommentCount');
			    var PostTime=ShowMessageInfoItems[t].getAttribute('PostTime');
			    var ArticleID =ShowMessageInfoItems[t].getAttribute('ArticleID')
		        //var userid =ShowMessageInfoItems[t].getAttribute('userid')

			    
			    itemsDiv+= " <li class='xspace-loglist'><h4 class='xspace-entrytitle'>";
                itemsDiv+="<a class=\"blog-title\"  href='/default.aspx?userid="+userid+"&ArticleID="+ArticleID+"'>"+title+"</a>";
				//itemsDiv+="</h4> <p class='xspace-smalltxt'>"+PostTime+"</p><div class='xspace-itemmessage' >数据载入中，请稍等...</div>";
				itemsDiv+=" <p class='xspace-itemlinks'><a href='/default.aspx?userid="+userid+"&ArticleID="+ArticleID+"'>查看("+ClickCount+")</a><a href='/default.aspx?userid="+userid+"&ArticleID="+ArticleID+"'>评论("+CommentCount+")</a></p></li>";
		       }
		      document.getElementById('articleDiv').innerHTML = itemsDiv;

		  }
		  else
		  {
		      document.getElementById('articleDiv').innerHTML = " <h3 class='xspace-blocktitle'>没有找到与"+key+"相关的文章</h3>";

		  }
        }
    } 
    hexunAPI.callMethod('ss.article.getArticlesByKey', {userid:userid,key:key}, listener);	
	return ;
}


