var AJAX_SUCCESS		= 0;
var AJAX_INVALIDOBJECT		= 1;
var AJAX_INVALIDCALLBACK	= 2;
var AJAX_FAILEDOPEN		= 3;

function Ajax () {
	this.version		= '0.01';
	this.isAsync		= false;
	this.agent		= null;
	this.lastException	= '';

	if( typeof XMLHttpRequest != 'undefined' )
		this.agent = new XMLHttpRequest();

	if( this.agent == null ) {

		var axos = new Array(
//			'MSXML2.XMLHTTP.4.0',
			'MSXML2.XMLHTTP.3.0',
			'MSXML2.XMLHTTP',
			'Microsoft.XMLHTTP'
		);

		for( var i = 0; this.agent == null && i < axos.length; i++ ) {
			try {
				this.agent		= new ActiveXObject(axos[i]);

			} catch(e) {
				this.lastException	= e;
				this.agent		= null;
			}
		}
	}

	this.isValid	= callAjaxIsValid;
	this.get	= callAjaxGet;
	this.post	= callAjaxPost;
	this.open	= callAjaxOpen;
	this.request	= callAjaxRequest;
	this.response	= callAjaxResponse;
}

function AjaxResponse() {
	this.status	= 0;
	this.statusText	= '';
	this.headers	= new Array();
	this.body	= '';
	this.text	= '';
	this.xml	= '';
}

function AjaxRequest() {
	this.method	= 'GET';
	this.url	= '';
	this.headers	= new Array();
	this.body	= null;
	this.callback	= null;
}

function callAjaxGet( url, callback, headers ) {
	return this.open( 'GET', url, null, callback, headers );
}

function callAjaxIsValid() {
	return this.agent != null;
}

function callAjaxOpen( method, url, data, callback, headers ) {
	if (this.isValid()) {
		if (!method)	method		= 'GET';
		if (!data)	data		= null;
		if (callback)	this.isAsync	= true;

		if (this.isAsync) {
			if ( typeof callback != 'function' )
				return AJAX_INVALIDCALLBACK;
			this.agent.onreadystatechange = callback;
		}

		try {
			this.agent.open( method, url, this.isAsync );
		} catch(e) {
			this.lastException = e;
			return AJAX_FAILEDOPEN;
		}

		if ( method == 'POST' ) {
			this.agent.setRequestHeader( 'Connection', 'close' );
			this.agent.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );
		}

		if ( headers != null ) {
			for ( var header in headers ) {
				this.agent.setRequestHeader( header, headers[header] );
			}
		}

		this.agent.send(data);
		return AJAX_SUCCESS;
	}
	return AJAX_INVALIDOBJECT;
}

function callAjaxPost( url, data, callback, headers ) {
	return this.open( 'POST', url, data, callback, headers );
}

function callAjaxResponse() {
	if ( this.agent.readyState != 4 )
		return null;

	var res = new AjaxResponse();

	res.status	= this.agent.status;
	res.statusText	= typeof this.agent.statusText == 'undefined'
		? ''
		: this.agent.statusText;
	res.body	= typeof this.agent.responseBody == 'undefined'
		? ''
		: this.agent.responseBody;
	res.text	= typeof this.agent.responseText == 'undefined'
		? ''
		: this.agent.responseText;
	res.xml		= this.agent.responseXML == null
		? ''
		: this.agent.responseXML;

	var string = this.agent.getAllResponseHeaders();
	if (!string) string = '';

	var lines = string.split("\\n");
	for ( var i = 0; i < lines.length; i++ ) {
		var header = lines[i].split(": ");
		if(header.length >= 2) {
			var headername	= header.shift();
			var headervalue	= header.join(": ");

			res.headers[headername] = headervalue;
		}
	}

	return res;
}

function callAjaxRequest(req) {
	return this.Open(
		req.method,
		req.url,
		req.body,
		req.callback,
		req.headers
	);
}


//////////////////////////////// UPLOAD////////////////////////

var processing = 0;

function uploadPhoto(sid) {
	if(processing==1) {return false;}
	var upForm = document.forms['upForm'];
	var upload = document.getElementById('uploadForm');
	var ajax = new Ajax();
	if (ajax.isValid) {
		ajax.post(
			'http://'+document.domain+'/?sectionid='+sid+'&a=uploadbegin',
			'albumid='+upForm.elements[0].value,
			function() {
				var response = ajax.response();
				if (response && response.status >= 500 && response.status != 200) {
					upload.innerHTML = '<i>(��������� ������!)</i>';
				} else {
					upForm.submit();
					upload.innerHTML = '<img src="/mounting/photostore/upload.gif" align="absmiddle" /> Идет загрузка фотографий...<br><br>Пожалуйста, не закрывайте это окно, пока идет загрузка!';
				}
			}
		);
		return true;
	} else {
		upload.innerHTML = '<i>(AJAX error!)</i>';
		return true;
	}
}

///////////////////////////////////// WATCH SECTION /////////////////////////////////////

function loadPhoto(albumid,dataid) {
	var ajax = new Ajax();
	if (ajax.isValid) {
		var photoblock=document.getElementById('photoblock');
//		photoblock.innerHTML='Подождите...';
		ajax.post(
			'http://photo.reborn.ru/?a=watch&id='+albumid+'&pic='+dataid+'&photo=1',
			'',
			function() {
				var response = ajax.response();
				if ((response && response.status == 200 && response.text!='')) {
					photoblock.innerHTML=response.text;
					if(response.text.indexOf("<script>")>0){
						var script_rt = response.text.split("<script>");
						script_rt = script_rt[1].split("</script>");
						eval(script_rt[0]);
						if(response.text.indexOf("try {")>0){
							var script_cm = response.text.split("try {");
							script_cm = script_cm[1].split("} catch(e)");
							eval(script_cm[0]);
						}
					}
				}else{
//					alert('Ошибка при загрузке фотографии!'+response.text);
				}
			}
		);
		return true;
	} else {
		upload.innerHTML = '<i>(AJAX error!)</i>';
		return true;
	}
}

var vote=0;
var rate_off = false;
var force = false
var new_rate = 0;
var new_votes = 0;
sred = new Image(); sred.src='/mounting/videostore/star-red.gif';
sgrey = new Image(); sgrey.src='/mounting/videostore/star-grey.gif';
sredvote = new Image(); sredvote.src='/mounting/videostore/star-red-vote.gif';
sgreyvote = new Image(); sgreyvote.src='/mounting/videostore/star-grey-vote.gif';

function show_rate(rate) {
	if(!rate_off || force) {
		for(i=1;i<=rate;i++)
			document.getElementById('rate'+i).src = i==vote ? sredvote.src : sred.src;
		for(i=rate+1;i<=5;i++)
			document.getElementById('rate'+i).src = i==vote ? sgreyvote.src : sgrey.src;
	}
}

function rate(dataid, rate) {
	if(!rate_off) {
		vote=rate;
		rate_off=true;
		var ajax = new Ajax();
		if (ajax.isValid) {
			ajax.post(
				'http://'+document.domain+'/?sectionid='+sid+'&a=watch&id='+albumid+'&pic='+dataid,
				'rate='+rate,
				function() {
					var response = ajax.response();
					if (response && response.status == 200 && response.text!='') {
						eval(response.text);
						if(!new_rate || !new_votes) return;
						force=true;
						show_rate(new_rate);
						force=false;
						document.getElementById('new_votes').innerHTML=new_votes;
		            }
				}
			);
		}
		document.getElementById('rate_block').className='rate-off';
	}
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);

    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }

    var end = document.cookie.indexOf(";", begin);

    if (end == -1) {
        end = dc.length;
    }

    return unescape(dc.substring(begin + prefix.length, end));
}

function postComment(sid,aid,did,mode) {
	var ajax = new Ajax();
	if (ajax.isValid) {
		var filter='';
		if(mode) filter='&b=comments';
		xcomment=document.getElementById('comment');
		xpostbutton=document.getElementById('postbutton');
		xcomment.disabled=true;
		xpostbutton.disabled=true;
		xpostbutton.value=' Подождите... ';
		ajax.post(
			'http://'+document.domain+'/?sectionid='+sid+'&a=watch'+filter+'&id='+aid+'&pic='+did,
			'comment='+encodeURIComponent(xcomment.value),
			function() {
//				alert(xcomment.value);
				var response = ajax.response();
				if (response && response.status == 200 && response.text!='' && xcomment.value!=null) {
					document.getElementById('commentlist').innerHTML=response.text;
					xcomment.value='';
	            }else{
//	            	alert('!');
	            }
				xpostbutton.value=' Сохранить ';
				xpostbutton.disabled=false;
				xcomment.disabled=false;
			}
		);
	}
}

function removeComment(sid,aid,did,cid) {
	if (confirm('Вы действитeльно хотите удалить этот комментарий?')==true) {
		var ajax = new Ajax();
		if (ajax.isValid) {
			ajax.post('http://'+document.domain+'/?sectionid='+sid+'&a=watch&id='+aid+'&pic='+did+'&commentid='+cid,
				'b=commentremove',
				function() {
					var response = ajax.response();
//					alert(response.text);
					if (response && response.status == 200 && response.text=='removed') {
						document.getElementById('id_'+cid).outerHTML='';
					} else {
						alert('Ошибка при удалении комментария! '+response.status);
					}
				}
			);
		}

	}
}

function applyNewComment(sid,cid) {
	var ajax = new Ajax();
	if (ajax.isValid) {
		ajax.post(
			'http://'+document.domain+'/?sectionid='+sid+'&a=newcomments&commentid='+cid,
			'b=apply',
			function() {
				var response = ajax.response();
				if (response && response.status == 200 && response.text=='applied') {
					location='?sectionid='+sid+'&a=newcomments';
				} else {
					alert('Ошибка при прочтении комментария!'+response.status);
				}
			}
		);
	}
}

function removeUComment(sid,cid,a) {
	var ajax = new Ajax();
	if (ajax.isValid) {
		if(a==0){c='newcomments';}else{c='allcomments';}
		ajax.post('http://'+document.domain+'/?sectionid='+sid+'&a='+c+'&commentid='+cid,
				'b=remove',
			function() {
				var response = ajax.response();
//				alert(sid+', '+c+', '+cid);
				if (response && response.status == 200 && response.text=='removed') {
					location='?sectionid='+sid+'&a='+c;
//					document.getElementById('id_'+cid).outerHTML='';
				} else {
					alert('Ошибка при удалении комментария! '+response.status);
				}
			}
		);
	}
}

var abuse=0;
var noabuse=0;
var notvalid=0;
function showAbuse() {
	abuseForm=document.getElementById('abuse-form');
	abuseButton=document.getElementById('abuse-button');
	if(!abuse) {
		abuseForm.className='abuse-table visible';
		abuseButton.innerHTML='Не жаловаться';
		abuse=1;

	} else {
		abuseForm.className='abuse-table invisible';
		abuseButton.innerHTML='Пожаловаться на фотографию';
		abuse=0;
	}
}

function postAbuse(sid,aid,did) {
	var ajax = new Ajax();
	if (ajax.isValid) {
		abuseText=document.getElementById('abuse-text');
		abuseCode=document.getElementById('abuse-code');
		abusePost=document.getElementById('abuse-post');
		abuseText.disabled=true;
		abuseCode.disabled=true;
		abusePost.disabled=true;
		abusePost.value=' Подождите... ';
		ajax.post(
			'http://'+document.domain+'/?sectionid='+sid+'&a=watch&id='+aid+'&pic='+did,
			'b=abuse&abuse_text='+encodeURIComponent(abuseText.value)+'&abuse_code='+abuseCode.value,
			function() {
				var response = ajax.response();
				if (response && response.status == 200 && response.text!='') {
//					alert(response.text);
					if(response.text=='redirect') {
						location='/?sectionid='+sid+'&a=watch&id='+aid;
						return true;
					}
					eval(response.text);
					document.getElementById('abuse-text-message').style.display = noabuse ? 'block' : 'none';
					document.getElementById('abuse-code-message').style.display = notvalid ? 'block' : 'none';
					abuseText.disabled=false;
					abuseCode.disabled=false;
					abusePost.disabled=false;
					abusePost.value='Послать';
	            }
			}
		);
	}
}

function removeAbuse(sid,aid) {
	if (confirm('Вы действитeльно хотите удалить эту жалобу?')==true) {
		var ajax = new Ajax();
		if (ajax.isValid) {
			ajax.post(
				'http://'+document.domain+'/?sectionid='+sid+'&a=abuse&abuseid='+aid,
				'b=abuseremove',
				function() {
					var response = ajax.response();
					if (response && response.status == 200 && response.text=='removed') {
						location='?sectionid='+sid+'&a=abuse';
					} else {
						alert(responce.text);
						alert('Ошибка при удалении жалобы!'+response.status);
					}
				}
			);
		}

	}
}

function rotatePhoto(sid,albumid,dataid,direction) {
	var ajax = new Ajax();
	if (ajax.isValid) {
		ajax.post(
			'http://'+document.domain+'/?sectionid='+sid+'&a=watch&id='+albumid+'&dataid='+dataid,
			'b=rotate&direction='+direction,
			function() {
				var response = ajax.response();
				document.getElementById('rotate').innerHTML = '<img src="/mounting/photostore/upload.gif" align="absmiddle" /> Переворачиваем...';
//				alert(response.text);
				if (response && response.status == 200 && response.text=='rotated') {
					location.reload(true);
				} else {
					alert(response.status+': Ошибка при повороте фото!');
				}
			}
		);
	}
}

function removePhoto(sid,albumid,dataid) {
	if (confirm('Вы действитeльно хотите удалить это фото?')==true) {
		var ajax = new Ajax();
		if (ajax.isValid) {
			ajax.post(
				'http://'+document.domain+'/?sectionid='+sid+'&a=watch&id='+albumid+'&dataid='+dataid,
				'b=remove',
				function() {
					var response = ajax.response();
					if (response && response.status == 200 && response.text=='removed') {
//						alert(response.text);
						location='?sectionid='+sid+'&a=watch&id='+albumid;
					} else {
						alert(response.status+': Ошибка при удалении фот!');
					}
				}
			);
		}
	}
}

function albumPage(sid,albumid,pagenum) {
	var ajax = new Ajax();
	if (ajax.isValid) {
		ajax.post(
			'http://'+document.domain+'/?sectionid='+sid+'&a=watch&id='+albumid+'&pagenum=1',
			'p='+pagenum,
			function() {
				var response = ajax.response();
				if (response && response.status == 200 && response.text!='') {
					document.getElementById('albumblock').innerHTML=response.text;
	            }else{
	            }
			}
		);
	}
}
function commentPage(sid,id,pic,pagenum) {
	var ajax = new Ajax();
	if (ajax.isValid) {
		ajax.post(
			'http://'+document.domain+'/?sectionid='+sid+'&a=watch&id='+id+'&pic='+pic+'&pagenum=1',
			'page='+pagenum,
			function() {
				var response = ajax.response();
				if (response && response.status == 200 && response.text!='') {
//					alert(other);
					document.getElementById('commentlist').innerHTML=response.text;
	            }else{
	            }
			}
		);
	}
}
