var frame;

var rate = new Array();
var mark = new Array();

var modal;
var gallery;
var oImage;
var Loaded;

$(document).ready(function(){
	frame = 1;
	gallery = false;
	cash();
	preload();

	$("#getques").click(function(){
		$("#m_q").val('Введите вопрос и свои контактные данные');
		$("#m_q").css("color","#666666");
		$(".ques-form").show("slow");
		return false;
		});
	$("#m_q").click(function(){

		$("#m_q").css("color","#000");
	});
	$("#ques-form").submit(function(){
	    var text = $("#m_q").val();
		var mailstr= new String(text);
		var indexOfDog = mailstr.indexOf("@");
	    var isphone=/[0-9]{3,}/;

	    if(indexOfDog<=0 && !isphone.test(text))
		{
			alert("Похоже что Вы не указали контактных данных для связи\nУкажите Email или телефон.");
			return false;
		}
		else return true;

	});

	$('.mnu ul li a').click(
			function() {
				$(this).parent().children('ul').toggle();
				$('.mnu ul li ul .active').css('display', 'block');
				$('ul', this).css('display', 'block');
			},
			function() { $('ul', this).css('display', 'none'); });

	$('ul.bottom-menu li a').click(
			function() {
				$('ul.bottom-menu li ul').css('display', 'none');
				$(this).parent().children('ul').toggle();
				$('ul.bottom-menu li ul .active').css('display', 'block');
				$('ul', this).css('display', 'block');
			},
			function() { $('ul', this).css('display', 'none'); });

	});





     // vote for picture
	$(".picture-vote a").live("click", function(e) {
		var action = this.className;
		var pic_id;
		var val;
		pic_id = $(this).closest("div.picture-vote").attr("id");

		$.post("/includes/modules/articles/vote/picture-vote.php",{ act: action , id: pic_id },
		   function(data){

	    	val = $("#"+action+"_"+pic_id).text();

		   	if(data=='1') 	{
   		    	$.cookie("artego_"+pic_id, 'true', {expires: 365, path: "/"});
	   			if(action=='plus')
	   				$("#"+action+"_"+pic_id).text(Math.abs(parseInt(val))+1);
	   			else if(action=='minus' && val!='0' && val!='')
	   				$("#"+action+"_"+pic_id).text(Math.abs(parseInt(val))+1);
   				else
	   				$("#"+action+"_"+pic_id).text(1);
		   		alert('Спасибо за ваш голос!');
	   		}
	   		else if(data=='2')
	   		{
	   			alert('Вы уже голосовали за это фото!');

	   		}
	   	});
	   	return false;
	});

//rating
function cash(){
	for(var i=1;i<=20;i++)
		rate[i] = this.document.getElementById('r'+i+'f'+frame);
	for(var i=1;i<=5;i++)
		mark[i] = this.document.getElementById('rate'+i+'f'+frame);
}
function r(n){//mouseover
	for(var i=1;i<=n*4;i++)
		rate[i].src = '/images/'+i+'.gif';
	mark[n].src = '/images/r'+n+'a.gif';
}
function o(){//mouseout
	for(var i=20;i>=1;i--)
		rate[i].src = '/images/l.gif';
	for(var i=1;i<=5;i++)
		mark[i].src = '/images/r'+i+'.gif';
}
function f(d){//n,m
	var n = Math.floor(d);
	var m = Math.floor((d-n)*4);
	var k = 4*n+m;
	for(var i=1;i<=k;i++)
		rate[i].src = '/images/'+i+'.gif';
}
function vote(person, value)
{
	if(person>0 && value>0)
	{
		$.post("/includes/ajax/vote_vote.php", { person:person,value:value,rand:Math.random() } ,function(response) {
		if(response>0)
		{
			$('#result'+person).html(response);
			alert('Спасибо! Ваш голос принят!');
		}
		else
		{
			alert(response);
		}
		});
	}
	return false;
}
//photos
function p(src, title){
	gallery = true;
	shade();
	modal = this.document.getElementById('photo');
	modal.innerHTML = '<div style="padding-top:200px;">Пожалуйста, подождите. Фотография загружается.</div>';
	var top = $(window).scrollTop()+30;
	modal.style.top = top+'px';

	Loaded = 0;
	oImage = new Image;
	oImage.onload = checkLoad;
	oImage.src = src;
	oImage.title = title;
	checkLoad();

	modal.className = '';
	var margin = Math.floor(modal.offsetWidth/2);
	modal.style.marginLeft = '-'+margin+'px';
}
function checkLoad(){
	if(oImage.complete){
		$("#photo").animate({height:"0px"}, 100,function(){
			var marginLeft = Math.floor(oImage.width/2);
			var marginTop = Math.floor(oImage.height/2);
			modal.innerHTML = oImage.title+'<br /><img src="'+oImage.src+'" alt="" title="'+oImage.title+'" onclick="unshade()" />';
			modal.style.marginLeft = '-'+marginLeft+'px';
			modal.style.marginTop = marginTop+'px';
			$("#photo").animate({height:oImage.height+"px",marginTop:"0px"},400);
		});
		return
	}
	timerID = setTimeout("checkLoad()",10)
}
//map
function preload(){
	Loaded = 0;
	oImage = new Image;
	oImage.onload = check;
	oImage.src = '/images/map.png';
	check();
}
function check(){
	if(oImage.complete){
		return
	}
	timerID = setTimeout("check()",10)
}
function map(){
	/*shade();
	modal = this.document.getElementById('map');
	var top = $(window).scrollTop()+30;
	modal.style.top = top+'px';
	modal.className = '';*/
	$("#map").toggle();
	return false;
}
//shade
function shade(){
	var shade = this.document.getElementById('shade');
	shade.style.height = this.document.getElementById('container').offsetHeight + 'px';
	shade.className = '';
}
function unshade(){
	if(gallery){
		gallery = false;
		var marginTop = Math.floor(oImage.height/2);
		$("#photo").animate({height:0+"px",marginTop:marginTop+"px"},600,function(){
			hide();
		});
	}
	else{
		this.document.getElementById('shade').className = 'hidden';
		modal.className = 'hidden';
	}
}
function hide(){
	this.document.getElementById('shade').className = 'hidden';
	modal.className = 'hidden';
	$("#photo").css({height:"100px"});
}
//movie
function nxt(){
	frame++;
	cash();
	var x = document.body.scrollWidth*(frame-1);
	$("#movie").animate({left:"-"+x+"px"}, 600);
	this.document.getElementById('nxt').className = (frame<3)? "clickable nav" : "hidden";
	this.document.getElementById('prv').className = (frame>1)? "clickable nav" : "hidden";
}
function prv(){
	frame--;
	cash();
	var x = document.body.scrollWidth*(frame-1);
	$("#movie").animate({left:"-"+x+"px"}, 600);
	this.document.getElementById('nxt').className = (frame<3)? "clickable nav" : "hidden";
	this.document.getElementById('prv').className = (frame>1)? "clickable nav" : "hidden";
}
//more/less
function more(){
	$("#random").animate({top:"0px"}, 600);
}
function less(){
	$("#random").animate({top:"409px"}, 600);
}
//subscribe
function validate(){
	var notvalid;
	notvalid = this.document.getElementById('submit').disabled = !((this.document.getElementById('mail').value!='e-mail')&&(this.document.getElementById('news').checked||this.document.getElementById('events').checked));
	return notvalid;
}
//news archive
var news = true;
var flag = false;
function read(){
	if(!flag){
		flag=true;
		if(news){
			$("#btn").addClass('expanded');
			$("#allnews").show();
			var height = this.document.getElementById('allnews').offsetHeight+50;
			$("#newsrar").animate({height:height+"px"},600,function(){flag=false;});
		}
		else{
			$("#allnews").hide();
			$("#newsrar").animate({height:"0px"},600,function(){
				$("#btn").removeClass('expanded');
				flag=false;
			});
		}
		news = !news;
	}
}
//man
var m_styles = new Array('as_is','brut','e_vag','strgo','g','g_no');
var m_img = new Array('0.png','0.png','1.png','0.png','0.png','0.png');
var m_cur = 0;
function m(n){
	if(n<m_styles.length){
		if(n!=m_cur){
			for(var i=0;i<m_styles.length;i++){
				this.document.getElementById(m_styles[i]).className = 'howto';
			}
			var stl = (m_styles[n]!='g')? 'howto noborder' : 'howto noborderbot';
			this.document.getElementById(m_styles[n]).className = stl;
			this.document.getElementById('man').src = '/images/'+m_img[n];
			m_cur = n;
		}
	}
}

/* subscribe */
function subscribe()
{
	var check;
	check = checkEmail($('#mail').val());
	if(!validate() && check=='')
	{
		$.post("/includes/ajax/subscriber_add.php", { mail:$('#mail').val(),news:$('#news').val(),events:$('#events').val(),rand:Math.random() } ,function(response) {
		if(response=='1')
		{
			alert('Спасибо! Адрес '+$('#mail').val()+' добавлен в список рассылки!');
		}
		else
		{
			alert(response);
		}
		});
	}
	else
	{
		if(check!='') {alert(check);}
	}
}

/* check */
function checkEmail(mail)
{
	var mailstr= new String(mail);
	var indexOfDog = mailstr.indexOf("@");
	var indexOfPeriod = mailstr.indexOf(".");
	var indexOfSpace = mailstr.indexOf(" ");
    var regex5=/[^a-zA-Z_0-9\@\.\-]/;
    var regex7=/[а-я]/;
    var regex8=/[А-Я]/;
    var error_message = "";

	if(indexOfDog==-1){
		error_message+="\nEmail не полон, пропущена @";
		error=1;
	}

	if(indexOfDog==0){
		error_message+="\nEmail не полон, перед @ ничего нет";
		error=1;
	}

	if(indexOfSpace!=-1){
		error_message+="\nEmail не должен содержать пробелов";
		error=1;
	}

	if(indexOfPeriod==-1){
		error_message+="\nEmail не полон, пропущена точка";
		error=1;
	}

	if(regex5.test(mail))
	{
		error_message+="\nEmail может содержать только цифры и английские буквы";
		error=1;
	}

	return error_message;
}
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
