var d = document;
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var isNs = (navigator.appName.indexOf("Netscape") != -1);

var MooTools = false;

function getE(id,parent){
	if(defined(parent)) {
		if(parent==true) return window.parent.document.getElementById(id);
		else return document.getElementById(id);
	}
	return document.getElementById(id);
}

function $(el){
	return document.getElementById(el);
};

function defined(x){
	return typeof(x) != 'undefined' && x != null;
}

function getElementsByName(name, tag) {
	var elements = document.getElementsByTagName(tag);
	var ret = new Array();
	for(var i = 0;i < elements.length;i++) {
		if(elements[i].name == name) { ret[ret.length] = elements[i]; }
	}
	if(ret.length > 0) { return ret; }
	return false;
}

function addListener(element, event, func){
	if(element.attachEvent)
		element.attachEvent('on' + event, function(){ func(window.event) });
	else if(element.addEventListener)
		element.addEventListener(event, func, false);
}

function ShowWin(url,x,y,name,isscrollbars) {
	cx=screen.width / 2 - (x / 2);
	cy=(screen.height/2-(y/2));
    
    isscrollbars=(isscrollbars=="no")?"no":"yes";
	window.open(url,name,"toolbar=no,status=no,directories=no,menubar=no,resizable=yes,width="+x+",height="+y+",scrollbars="+isscrollbars+",top="+cy+",left="+cx);
}

function ShowWinMod(options) {
	if (!defined(options.url)) { alert('Не указана сылка на страницу!'); return false; }
	if (!defined(options.name)) { alert('Не указано название окна!'); return false; }
	if (defined(options.prx) && defined(options.pry)) {
		var x,y;
		y=screen.availHeight
		if(!y) y=screen.height
		x=screen.availWidth
		if(!x) x=screen.width
		x = parseInt(options.prx*x/100);
		y = parseInt(options.pry*y/100);
		cx=screen.width / 2 - (x / 2);
		cy=(screen.height/2-(y/2));
	} else if (defined(options.x) && defined(options.y)) {
		var x,y;
		x = options.x;
		y = options.y;
		cx=screen.width / 2 - (x / 2);
		cy=(screen.height/2-(y/2));
	} else { alert('Не заданы размеры окна!'); return false; }
	
	options.isscrollbars=(defined(options.isscrollbars))?((options.isscrollbars=="no")?"no":"yes"):"yes";
	options.toolbar=(defined(options.toolbar))?((options.toolbar=="no")?"no":"yes"):"no";
	options.status=(defined(options.status))?((options.status=="no")?"no":"yes"):"no";
	options.directories=(defined(options.directories))?((options.directories=="no")?"no":"yes"):"no";
	options.menubar=(defined(options.menubar))?((options.menubar=="no")?"no":"yes"):"no";
	options.resizable=(defined(options.resizable))?((options.resizable=="no")?"no":"yes"):"no";
	options.wlocation=(defined(options.wlocation))?((options.wlocation=="no")?"no":"yes"):"no";
	window.open(options.url,options.name,"toolbar="+options.toolbar+",location="+options.wlocation+",status="+options.status+",directories="+options.directories+",menubar="+options.menubar+",resizable="+options.resizable+",width="+x+",height="+y+",scrollbars="+options.isscrollbars+",top="+cy+",left="+cx);
}

function MOver(MySrc,MyColor) { MySrc.style.cursor="auto"; MySrc.bgColor=MyColor; }
function MOut (MySrc,MyColor) { MySrc.style.cursor="auto"; MySrc.bgColor=MyColor; }

function setstat(banishment) {
	//if(defined(banishment)) {
		//new Image().src = '/setstat/?href='+rawurlencode(banishment);
	//}
	return true;
}


function trim(str) {
    var newstr = str.replace(/^\s*(.+?)\s*$/, "$1");
    if (newstr == " ") { return ""; }
    return newstr;
}

function dropSpaces(str) {
    var newstr = trim(str);
    return newstr.replace(/(\s)+/g, ""); 
}

function checkEmail(email) {
    var template = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z])+$/;
    email = dropSpaces(email);
    if (template.test(email)) { return true; }
    return false;
}


/**
 * Параметры:
 * str - путь
 * addarray - переменные, которые надо добавить в путь (array('name1','value1','name2','value2',...))
 * removearray - перменные, которые необходимо убрать из пути (array('name1','name2',...))
 */
function get_qs(str,addarray,removearray) {
	farr = str.split('?');

	var vars = new Array();
	var varval = new Array();

	if(defined(farr[1])) {
		arr = farr[1].split('&');

		for(i=0;i<arr.length;i++) {
			variable = arr[i].split('=');
			vars[i] = variable[0];
			varval[i] = variable[1];
		}
		if(defined(removearray)) {
			if(removearray.length>0) {
				for(i=0;i<vars.length;i++) {
					for(j=0;j<removearray.length;j++) {
						if(vars[i]==removearray[j]) {
							vars[i] = false;
							varval[i] = false;
						}
					}
				}
			}
		}
	}

	if(defined(addarray)) {
		if(addarray.length>0) {
			for(j=0;j<addarray.length;j++) {
				find = false;
				for(i=0;i<vars.length;i++) {
					if(vars[i]==addarray[j]) {
						varval[i] = addarray[j+1];
						find = true;
					}
				}
				if(!find) {
					vars[vars.length] = addarray[j];
					varval[varval.length] = addarray[j+1];
				}
				j++;
			}
		}
	}

	qs = '';
	for(i=0;i<vars.length;i++) {
		if(vars[i]!=false)
			qs = qs+vars[i]+'='+varval[i]+'&';
	}
	return farr[0]+'?'+qs;
}

function reload(elements) {
	elements = new String(elements);
	elements = elements.split(',');
	varsadd = new Array();
	varsdel = new Array();
	l = 0;
	for (i=0;i<elements.length;i++) {
		if(defined(getE(elements[i]))) {
			varsadd[l] = elements[i]; l++;
			varsadd[l] = getE(elements[i]).value; l++;
		}
		varsdel[i] = elements[i];
	}

	qs = get_qs(window.location.href,varsadd,varsdel);
	window.location.replace(qs);
}

function show_series() {
	if (getE('series_id').checked) {
		for (i=1;i<5;i++) {
			getE('ser'+i).style.display = '';
		}
	} else {
		for (i=1;i<5;i++) {
			getE('ser'+i).style.display = 'none';
		}
	}
}

function sel_album() {
	if (getE('album').value>0) {
		getE('country').disabled = true;
		getE('resort').disabled = true;
		getE('category').disabled = true;
		getE('subcategory').disabled = true;
	} else {
		getE('country').disabled = false;
		getE('resort').disabled = false;
		getE('category').disabled = false;
		getE('subcategory').disabled = false;
	}
}


function getAbsolutePosition(el) {
	var r = { x: el.offsetLeft, y: el.offsetTop };
	if (el.offsetParent) {
		var tmp = getAbsolutePosition(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
}

function get_cb_values(form_name,parent,name,separator) {
	if(!parent) {
		var form = getE(form_name);
	} else {
		var form = window.parent.document.getElementById(form_name);
	}
	var values = '';

	if(!defined(separator))
		separator = '_';

	if(defined(form)) {
		var element = form.elements;
		var checkbox = Array();
		
		if(defined(element)) {
			for (i=0; i<element.length; i++){
				if (element[i].type=='checkbox' && element[i].name==name) {
					checkbox[checkbox.length] = element[i];
				}
			}
			if (checkbox.length>0) {				
				for (i=0;i<checkbox.length;i++){	
					if (checkbox[i].checked) {
						values += checkbox[i].value+separator;
					}		
				}
				values = values.substr(0,values.length-1);
			}
		}
	}
	return values;
}

function rawurlencode(str) {
	var url = new String(str);
	url = url.replace(/([^a-z0-9_\-\.])/gi, function (str, p1, offset, s) {	var hex = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"); val = p1.charCodeAt(0); s = ""; while (val>=16) { s += hex[val%16]; val = Math.floor(val/16); } s += hex[val]; N = s.length; for (i=0,t="";i<N;i++) t += s.substring(N-i-1,N-i); return "%"+t; });
	return url;
}

function rawurldecode(str) {
	var url = new String(str);
	url = url.replace(/%([0-9ABCDEF]{2}|[0-9ABCDEF]{4})/g, function (str, p1, offset, s) { return String.fromCharCode(parseInt("0x"+p1,16)); });
	return url;
}

// перемещение div по экрану за полосой прокрутки
function JSFX_FloatTopDiv() {

	this.timer = null;
	this.ftlObj = {};
	this.startDiv = null;

	this.DeLayer = function(id) {
		var placeX = (d.body.clientWidth - d.body.clientWidth / 2),
		placeY = (d.body.clientHeight - d.body.clientHeight / 2) + 100;
		var GetElements = d.getElementById ? d.getElementById(id) : d.all ? d.all[id] : d.layers[id];
		if (d.layers)
			GetElements.style = GetElements;
		GetElements.sP = function(x,y) {
			this.style.right = x;
			this.style.top = y;
		};
		GetElements.x = placeX;
		GetElements.y = isNs ? pageYOffset + innerHeight : d.body.scrollTop + d.body.clientHeight;
		GetElements.y -= placeY;
		return GetElements;
	}

	this.add = function(divid) {
		if (!defined(this.ftlObj[divid])) {
			this.ftlObj[divid] = this.DeLayer(divid);
		}
	}
	
	this.stop = function() {
		clearTimeout(this.timer);
		clearInterval(this.timer);
		if (defined(this.startDiv)) {
			this.startDiv.style.display = 'none';
		}
		this.startDiv = null;
	}

	this.stayTopright = function() {
		placeY = (d.body.clientHeight - d.body.clientHeight / 2) + 100;
		var pY = isNs ? pageYOffset + innerHeight : d.body.scrollTop + d.body.clientHeight;
		this.startDiv.y += (pY - placeY - this.startDiv.y) / 15;
		this.startDiv.sP(this.startDiv.x, this.startDiv.y);
		var obj = this;
		this.timer = setTimeout(function() { obj.stayTopright(); }, 10);
	}

	this.start = function(divid) {
		this.stop();
		if (defined(this.ftlObj[divid])) {
			this.startDiv = this.ftlObj[divid];
			if (defined(this.startDiv)) {
				this.startDiv.style.display = '';
			}
			this.stayTopright();
		}
	}
}

JSFX = new JSFX_FloatTopDiv();


function setContest(el) {
	url = el.attributes['href'].value + 'action=' + el.attributes['action'].value;

	jQuery.get(url, {}, function(data) {
		if (defined(data)) {
			if (defined(data.contest)) {
				if(data.contest == 'set') {
					getE("contestlabel").innerHTML = "<b>Участвует в конкурсе!</b>";
					getE("contestbuttom").value = "Снять с участия в конкурсе";
					el.attributes['action'].value = 'unset';
				} else {
					getE("contestlabel").innerHTML = "<b>Не участвует в конкурсе!</b>";
					getE("contestbuttom").value = "Разместить на конкурс";
					el.attributes['action'].value = 'set';
				}
				return true;
			}
		}

		alert('Ошибка при размещении на конкурс!');
	}, 'json');

	return true;
}






function showEditForm() {
	getE('editWorkBlock').style.display='block';
	getE('commentWorkBlock').style.display= 'none';
	getE('editHref').className="edit_active";
	getE('commentHref').className="edit_noactive";
}

function showCommentForm() {
	getE('editWorkBlock').style.display='none';
	getE('commentWorkBlock').style.display='block';
	getE('editHref').className="edit_noactive";
	getE('commentHref').className="edit_active";
}


function hiddenCommentForm(dis) {
	jQuery("#commentName").attr('disabled', dis);
	jQuery("#commentEmail").attr('disabled', dis);
	jQuery("#commentText").attr('disabled', dis);
	jQuery("#commentCode").attr('disabled', dis);
	jQuery("#commentSubmit").attr('disabled', dis);
	
	if (dis==true) {
		jQuery("#errInsertComment").css('display', 'none');
		jQuery("#errValidateComment").css('display', 'none');
		jQuery("#errNameComment").css('display', 'none');
		jQuery("#errEmailComment").css('display', 'none');
		jQuery("#errTextComment").css('display', 'none');
		jQuery("#errCodeComment").css('display', 'none');
	}
}

function loadComment(options) {
	if (!defined(options.url)) {
		return false;
	}

	params = defined(options.params) ? options.params : {};
	blockId = defined(options.blockId) ? options.blockId : 'commentShow';
	loadBlockId = defined(options.loadBlockId) ? options.loadBlockId : 'loadComment';

	if (loadBlockId != null) {
		h = jQuery("#" + blockId).height();
		w = jQuery("#" + blockId).width();
		jQuery('#' + loadBlockId).css({
			height: (h < 40 ? 40 : h) + 'px', 
			width: w + 'px',
			filter: "alpha(opacity=50)",
			opacity: "0.5",
			display: ''
		});
	}

	hiddenCommentForm(true);

	jQuery.get(options.url, params, function(data) {
		if (defined(data)) {
			jQuery("#" + blockId).html(data);
		} else {
			jQuery("#" + blockId).html("Ошибка при получении данных");
		}

		if (loadBlockId != null) {
			jQuery('#' + loadBlockId).css({ display: 'none' });
		}

		hiddenCommentForm(false);
	}, 'html');

	return true;
}


function saveComment(form, options) {
	getE('commentReply').value = get_cb_values('commentForm',true,'comment[]',',');
	err = '';
	if (!form.commentText.value.length) { err += 'Укажите комментарий!\n'; }
	if (!form.commentUserId.value.length) {
		if (!form.commentName.value.length) { err += 'Укажите Ваше имя!\n'; }
		if (!form.commentEmail.value.length) { err += 'Укажите E-mail в формате somename@domain.ru!\n'; } else {
			if (!checkEmail(form.commentEmail.value)) { err += 'Укажите E-mail в формате somename@domain.ru!\n'; }
		}
		if (!form.commentCode.value.length) { err += 'Введите защитный код!\n'; }
	}
	if (err.length) {
		alert(err);
		return false
	} else {

		blockId = defined(options.blockId) ? options.blockId : 'commentShow';
		loadBlockId = defined(options.loadBlockId) ? options.loadBlockId : 'loadComment';
		loadUrl = defined(options.loadUrl) ? options.loadUrl : null;
		
		params = {
			commentWorkId: defined(form.commentWorkId) ? form.commentWorkId.value : '',
			commentUserId: defined(form.commentUserId) ? form.commentUserId.value : '',
			commentName: defined(form.commentName) ? trim(form.commentName.value) : '',
			commentEmail: defined(form.commentEmail) ? trim(form.commentEmail.value) : '',
			commentText: defined(form.commentText) ? trim(form.commentText.value) : '',
			commentAlbum: defined(form.commentAlbum) ? form.commentAlbum.value : '',
			commentReply: defined(form.commentReply) ? form.commentReply.value : '',
			commentCode: defined(form.commentCode) ? form.commentCode.value : ''
		};

		if (loadBlockId != null) {
			h = jQuery("#" + blockId).height();
			w = jQuery("#" + blockId).width();
			jQuery('#' + loadBlockId).css({
				height: (h < 40 ? 40 : h) + 'px', 
				width: w + 'px',
				filter: "alpha(opacity=50)",
				opacity: "0.5",
				display: ''
			});
		}

		hiddenCommentForm(true);
		
		jQuery.post(form.action, params, function(data) {
			err = false;
			if (defined(data.result)) {

				if (parseInt(data.result)) {

					jQuery("#commentReply").attr('value', '');
					jQuery("#commentName").attr('value', '');
					jQuery("#commentEmail").attr('value', '');
					jQuery("#commentText").attr('value', '');
					jQuery("#commentCode").attr('value', '');
					jQuery("input[@name='comment[]']").attr('checked', false);

					loadComment({ params: { workId: params.commentWorkId }, url: loadUrl });

				} else {
					err = true;
					if (defined(data.err_insert)) jQuery("#errInsertComment").css('display', '');
					if (defined(data.err_validate)) jQuery("#errValidateComment").css('display', '');
					if (defined(data.err_commentName)) jQuery("#commentName").css('display', '');
					if (defined(data.err_commentEmail)) jQuery("#commentEmail").css('display', '');
					if (defined(data.err_commentText)) jQuery("#errTextComment").css('display', '');
					if (defined(data.err_capcha)) jQuery("#errCodeComment").css('display', '');
				}

			} else {
				err = true;
				jQuery("#errInsertComment").css('display', '');
			}
			
			if (err == true) {
				if (loadBlockId != null) {
					jQuery('#' + loadBlockId).css({ display: 'none' });
				}
				hiddenCommentForm(false);
			}
			
		}, "json");
	}

	return false;
}


function delComment(options) {
	if (!defined(options.url)) {
		return false;
	}
	blockId = defined(options.blockId) ? options.blockId : 'commentShow';
	loadBlockId = defined(options.loadBlockId) ? options.loadBlockId : 'loadComment';
	params = defined(options.params) ? options.params : {};
	loadUrl = defined(options.loadUrl) ? options.loadUrl : null;

	if (loadBlockId != null) {
		h = jQuery("#" + blockId).height();
		w = jQuery("#" + blockId).width();
		jQuery('#' + loadBlockId).css({
			height: (h < 40 ? 40 : h) + 'px', 
			width: w + 'px',
			filter: "alpha(opacity=50)",
			opacity: "0.5",
			display: ''
		});
	}

	hiddenCommentForm(true);

	jQuery.post(options.url, params, function(data) {
		err = false;
		if (defined(data.result)) {
			if (parseInt(data.result)) {
				loadComment({ params: { workId: params.workId }, url: loadUrl });
			} else {
				err = true;
				alert('Ошибка при удалении комментария.');
			}
		} else {
			err = true;
			alert('Ошибка при удалении комментария.');
		}

		if (err == true) {
			if (loadBlockId != null) {
				jQuery('#' + loadBlockId).css({ display: 'none' });
			}
			hiddenCommentForm(false);
		}
		
	}, "json");
	
	return false;
}


function setVote(id,contest,type,vote) {
	if (!defined(getE('voteBlock'+id).attributes['vote'])) { alert('Ошибка при добавлении голоса!'); return false; }
	switch (parseInt(getE('voteBlock'+id).attributes['vote'].value))
	{
	case 1: alert('Ваш голос уже принят!'); return false; break;
	case -1: alert('Голосование доступно только авторизованным пользователям!'); return false; break;
	case -2: alert('Автор не может голосовать за свою работу!'); return false; break;
	}

	var voteCount = 0;
	var elVote = getElementsByName(vote,'input');
	if (elVote!=false) {
		for (i=0; i<elVote.length; i++) { if (elVote[i].checked==true){ voteCount = elVote[i].value } }
	}
	
	if (parseInt(voteCount) != 0) {
		url = '/file/vote?work_id='+id+'&contest='+contest+'&type='+type+'&count='+voteCount+'&';
		Json.call(url, function(data){
			if(data.id) {
				if (!data.contest) {
					getE('voteCount'+data.id).innerHTML = data.count;
					//getE('voteBlock'+data.id).innerHTML = '';
					getE('voteBlock'+data.id).attributes['vote'].value = '1';
					getE('voteSelectBlock'+data.id).innerHTML = '&nbsp;Спасибо, Ваш голос принят';
				} else {
					getE('voteContestCount'+data.id).innerHTML = data.count;
					//getE('voteContestBlock'+data.id).innerHTML = '';
					getE('voteContestBlock'+data.id).attributes['vote'].value = '1';
					getE('voteSelectContestBlock'+data.id).innerHTML = '&nbsp;Спасибо, Ваш голос принят';
				}
				alert('Спасибо!\nВаш голос принят!');
			} else {
				alert('Ошибка при добавлении голоса!');
			}
		});
		return true;
	}

	return false;
}


function getVoteValue(name) {
	var voteCount = 0;
	var elVote = getElementsByName(name,'input');
	if (elVote!=false) {
		for (i=0; i<elVote.length; i++) { if (elVote[i].checked==true){ voteCount = elVote[i].value } }
	}
	return voteCount;
}

function selectAllImg(album,chk) {
	var elements = document.getElementsByTagName('img');
	if (defined(elements)) {
		var search = new RegExp("^nti"+album+"_");
		for ( i=0; i<elements.length; i++ ) {
			if (search.test(elements[i].id)) {
				if (chk==1) { elements[i].src = '/i/fav_1.gif'; }
				else { elements[i].src = '/i/fav_2.gif'; }
			}
		}
	}
}

function ntpAlbum(album,file) {
	img = getE('nti'+album+'_'+file);
	if (img.attributes['chk'].value>=1) { url = '/notepad?ntp=album&id='+album+'&chk='+0;
	} else { url = '/notepad?ntp=album&id='+album+'&chk='+1; }
	Json.call(url, function(data){
		if(data.ok==true) {
			if (parseInt(data.chk)==1) {
				img.attributes['chk'].value = 1;
				img.src = '/i/fav_1.gif';
				selectAllImg(album,1);
				alert('Альбом добавлен в избранное!');
			} else {
				img.attributes['chk'].value = 0;
				img.src = '/i/fav_2.gif';
				selectAllImg(album,0);
				alert('Альбом удален из избранного!');
			}
		} else {
			alert('Ошибка при добавлении в избранное!');
		}
	});
}


function ntpFile(file,type) {
	img = getE('nti_'+file);
	if (img.attributes['chk'].value>=1) { url = '/notepad?ntp=file&id='+file+'&type='+type+'&chk='+0;
	} else { url = '/notepad?ntp=file&id='+file+'&type='+type+'&chk='+1; }
	Json.call(url, function(data){
		if(data.ok==true) {
			if (parseInt(data.chk)==1) {
				img.attributes['chk'].value = 1;
				img.src = '/i/fav_1.gif';
				alert('Работа добавлена в избранное!');
			} else {
				img.attributes['chk'].value = 0;
				img.src = '/i/fav_2.gif';
				alert('Работа удалена из избранного!');
			}
		} else {
			alert('Ошибка при добавлении в избранное!');
		}
	});
}
function pageBookmark(url,title) {
	if (!url) url = location.href;
	if (!title) title = document.title;

	//Gecko
	if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) window.sidebar.addPanel (title, url, "");
	//IE4+
	else if (typeof window.external == "object") window.external.AddFavorite(url, title);
	//Opera7+
	else if (window.opera && document.createElement)
	{
		var a = document.createElement('A');
		if (!a) return false; //IF Opera 6
		a.setAttribute('rel','sidebar');
		a.setAttribute('href',url);
		a.setAttribute('title',title);
		a.click();
	}
	else return false;
	return true;
}