/**
 * Определение переменных для работы Ajax RIA Framework
 *
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    $Id: Ajax.js,v 1.1 2008/09/11 15:41:59 master Exp $
 */
var Ria_Core_Ajax = {
	'script': 'ajax.php'
};

/**
 * Ria_Rotator_Main
 *
 * @class       Ria_Rotator_Main
 * @copyright   2009 RIA-MUTIMEDIA
 * @license     GNU GPL v2
 * @author      Sergey Zelenko
 *
*/
var AfishaMaterialArr=0;
var AfishaMaterialUpdate=0;
var AfishaMaterialCount=10;
var Ria_Rotator_Main = new Class ({
    
    initialize: function(options){
	rotator_list = new $H(options);
	temp_arc = new $H(options);
	current_item = 0;
	item_total = 0;
	rotateIndex = 0;

	isStop = 0;
	this.preload();
    //this.changeImg.periodical(4000);
	    
    },
    
    stop: function(){
	rotator_list = new $H();
	isStop = 1;
    },

    pause: function(){
	temp_arc = rotator_list;
	rotator_list = new $H();
    },

    play: function (){
	if(!isStop){
	    rotator_list = temp_img_arc;
	}
	$(selected).setProperty('class','tMainBpagerA');
    },

    preload : function (){
	var rotateListImg = new Array();
	thisArea = this;
	rotator_list.each(function(item,index){
	    if (item.photo.length>1){
		image = item.photo.replace('.','med.');
		rotateListImg.include(['http://img.ria.ua/photos/'+image]);
	    }else{
		rotateListImg.include(['http://weekend.com.ua/img/afisha/no_photo_b.gif']);
	    }
	});
	var myImages = new Asset.images(rotateListImg, {
	    onComplete: function(){
//		alert("preload onComplete");
		thisArea.change.periodical(4000);
	    }
	});
    },

    change : function(){
	if (AfishaMaterialUpdate==1) {
	    //alert(AfishaMaterialArr.str);
	    AfishaMaterialUpdate=0;
	    current_item = 0;
	    rotator_list.empty();
	    rotator_list = new $H (AfishaMaterialArr);
	}
        
	rotator_list.each(function(item,index){
	    if(index == current_item){
		if (item.photo.length>1){
		    var image = item.photo;
		    image = image.replace('.','med.');
		    image = 'http://img.ria.ua/photos/' + image;
		}else{
		    image='http://weekend.com.ua/img/afisha/no_photo_b.gif';
		}
		$('AfishaPhoto').set('src',image);
		$('AfishaName').set('html',item.name);
                if(item.annotation){
                    $('AfishaDesc').set('html',item.annotation.substr(0,50)+'...');
                    $('AfishaDesc').set('href','afisha_'+item.event_id);
                }else{
                    $('AfishaDesc').set('html','');
                     $('AfishaDesc').set('href','#');
                }
		$('AfishaName').set('href','afisha_'+item.event_id);
		$('AfishaPhotoLink').set('href','afisha_'+item.event_id);
	    }
	    item_total = index;
	});
	if(current_item != item_total){
	    current_item++;
	}else{
	    current_item = 0;
	    rotateIndex = rotateIndex + 1;
	    if ((rotateIndex*4)>=AfishaMaterialCount){
		rotateIndex=0;
	    }
	    new Ria_Rotator_AfishaMaterial({'rotateIndex':rotateIndex});
	    //alert(AfishaMaterialArr.str);

	}
    }
});
// Calendar: a Javascript class for Mootools that adds accessible and unobtrusive date pickers to your form elements <http://electricprism.com/aeron/calendar>
// Calendar RC4, Copyright (c) 2007 Aeron Glemann <http://electricprism.com/aeron>, MIT Style License.
// Mootools 1.2 compatibility by Davorin Šego
// This Class was modified by ANDREY KOTULSKIY last changes was made by 26.03.2009
// Added notSelected options for calendar with non selected date by dafault,
// added metod readnonselect: that set default date after first click (year set in fullyar format)


var Calendar = new Class({	
	
	Implements: Options,

	options: {
		blocked: [], // blocked dates 
		classes: [], // ['calendar', 'prev', 'next', 'month', 'year', 'today', 'invalid', 'valid', 'inactive', 'active', 'hover', 'hilite']
		days: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'], // days of the week starting at sunday
		direction: 0, // -1 past, 0 past + future, 1 future
		draggable: true,
		months: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
		navigation: 1, // 0 = no nav; 1 = single nav for month; 2 = dual nav for month and year
		offset: 0, // first day of the week: 0 = sunday, 1 = monday, etc..
		onHideStart: Class.empty,
		onHideComplete: Class.empty,
		onShowStart: Class.empty,
		onShowComplete: Class.empty,
		pad: 1, // padding between multiple calendars
		tweak: {x: 0, y: 0, sdvig: 0}, // tweak calendar positioning (sdvig - na ckolyko sdvigaty kalendary chtob on ne otkrivalsya nige okna brouzera)
		positionAfter: 0, // position 0 - Before element, 1- AfterElement
        notSelected: 0
	},

	// initialize: calendar constructor
	// @param obj (obj) a js object containing the form elements and format strings { id: 'format', id: 'format' etc }
	// @param props (obj) optional properties

	initialize: function(obj, options) {
		
		// basic error checking
		if (!obj) { return false; }

		this.setOptions(options);

		// create our classes array
		var keys = ['calendar', 'prev', 'next', 'month', 'year', 'today', 'invalid', 'valid', 'inactive', 'active', 'hover', 'hilite'];

		var values = keys.map(function(key, i) {
			if (this.options.classes[i]) {
				if (this.options.classes[i].length) { key = this.options.classes[i]; }
			}
			return key;
		}, this);

		this.classes = values.associate(keys);

		// create cal element with css styles required for proper cal functioning
		this.calendar = new Element('div', { 
			'styles': { left: '-1000px', opacity: 0, position: 'absolute', top: '-1000px', zIndex: 1000 }
		}).addClass(this.classes.calendar).injectInside(document.body);

		// iex 6 needs a transparent iframe underneath the calendar in order to not allow select elements to render through
		if (window.ie6) {
			this.iframe = new Element('iframe', { 
				'styles': { left: '-1000px', position: 'absolute', top: '-1000px', zIndex: 999 }
			}).injectInside(document.body);
			this.iframe.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
		}

		// initialize fade method
		this.fx = new Fx.Tween(this.calendar, {
			onStart: function() { 
				if (this.calendar.getStyle('opacity') == 0) { // show
					if (window.ie6) { this.iframe.setStyle('display', 'block'); }
					this.calendar.setStyle('display', 'block');
					this.fireEvent('onShowStart', this.element);
				}
				else { // hide
					this.fireEvent('onHideStart', this.element);
				}
			}.bind(this),
			onComplete: function() { 
				if (this.calendar.getStyle('opacity') == 0) { // hidden
					this.calendar.setStyle('display', 'none');
					if (window.ie6) { this.iframe.setStyle('display', 'none'); }
					this.fireEvent('onHideComplete', this.element);
				}
				else { // shown
					this.fireEvent('onShowComplete', this.element);
				}
			}.bind(this)
		});

		// initialize drag method
		if (window.Drag && this.options.draggable) {
			this.drag = new Drag.Move(this.calendar, { 
				onDrag: function() {
					if (window.ie6) { this.iframe.setStyles({ left: this.calendar.style.left, top: this.calendar.style.top }); } 
				}.bind(this) 
			}); 
		}
		
		// create calendars array
		this.calendars = [];

		var id = 0;
		var d = new Date(); // today

		d.setDate(d.getDate() + this.options.direction.toInt()); // correct today for directional offset

		for (var i in obj) {
			var buttonid = 'button'+ id;
			var cal = { 
				button: new Element('button', { 'type': 'button', 'id': buttonid}),
				el: $(i),
				els: [],
				id: id++,
				month: d.getMonth(),
				visible: false,
				year: d.getFullYear()
			};
			

			// fix for bad element (naughty, naughty element!)
			if (!this.element(i, obj[i], cal)) { continue; }
			
			cal.el.addClass(this.classes.calendar);

			// create cal button. 
			//If you want to add Calendar button before input elements use injectBefore 
			//If you want use Callendar button after input elements use injectAfter 
			//alert (cal.el);
			if (this.options.positionAfter) {
			    cal.button.addClass(this.classes.calendar).addEvent('click', function(cal) { this.toggle(cal); }.pass(cal, this)).injectAfter(cal.el);
			} else{
			    cal.button.addClass(this.classes.calendar).addEvent('click', function(cal) { this.toggle(cal); }.pass(cal, this)).injectBefore(cal.el);
			}

			// read in default value
			cal.val = this.read(cal);

			$extend(cal, this.bounds(cal)); // abs bounds of calendar

			$extend(cal, this.values(cal)); // valid days, months, years

			this.rebuild(cal);

			this.calendars.push(cal); // add to cals array		
		}	
	},


	// blocked: returns an array of blocked days for the month / year
	// @param cal (obj)
	// @returns blocked days (array)

	blocked: function(cal) {
		var blocked = [];
		var offset = new Date(cal.year, cal.month, 1).getDay(); // day of the week (offset)
		var last = new Date(cal.year, cal.month + 1, 0).getDate(); // last day of this month
		
		this.options.blocked.each(function(date){
			var values = date.split(' ');
			
			// preparation
			for (var i = 0; i <= 3; i++){ 
				if (!values[i]){ values[i] = (i == 3) ? '' : '*'; } // make sure blocked date contains values for at least d, m and y
				values[i] = values[i].contains(',') ? values[i].split(',') : new Array(values[i]); // split multiple values
				var count = values[i].length - 1;
				for (var j = count; j >= 0; j--){
					if (values[i][j].contains('-')){ // a range
						var val = values[i][j].split('-');
						for (var k = val[0]; k <= val[1]; k++){
							if (!values[i].contains(k)){ values[i].push(k + ''); }
						}
						values[i].splice(j, 1);
					}
				}
			}

			// execution
			if (values[2].contains(cal.year + '') || values[2].contains('*')){
				if (values[1].contains(cal.month + 1 + '') || values[1].contains('*')){
					values[0].each(function(val){ // if blocked value indicates this month / year
						if (val > 0){ blocked.push(val.toInt()); } // add date to blocked array
					});

					if (values[3]){ // optional value for day of week
						for (var i = 0; i < last; i++){
								var day = (i + offset) % 7;
	
								if (values[3].contains(day + '')){ 
									blocked.push(i + 1); // add every date that corresponds to the blocked day of the week to the blocked array
								}
						}
					}
				}
			}
		}, this);

		return blocked;
	},


	// bounds: returns the start / end bounds of the calendar
	// @param cal (obj)
	// @returns obj	

	bounds: function(cal) {
	
		// 1. first we assume the calendar has no bounds (or a thousand years in either direction)
		
		// by default the calendar will accept a millennium in either direction
		var start = new Date(1000, 0, 1); // jan 1, 1000
		var end = new Date(2999, 11, 31); // dec 31, 2999

		// 2. but if the cal is one directional we adjust accordingly
		var date = new Date().getDate() + this.options.direction.toInt();

		if (this.options.direction > 0) {
//            alert (">");
			start = new Date();
			start.setDate(date + this.options.pad * cal.id);
		}
		
		if (this.options.direction < 0) {
//            alert ("<");
			end = new Date();
			end.setDate(date - this.options.pad * (this.calendars.length - cal.id - 1));
		}

		// 3. then we can further filter the limits by using the pre-existing values in the selects
		cal.els.each(function(el) {	
			if (el.get('tag') == 'select') {		
				if (el.format.test('(y|Y)')) { // search for a year select
					var years = [];

					el.getChildren().each(function(option) { // get options
						var values = this.unformat(option.value, el.format);
	
						if (!years.contains(values[0])) { years.push(values[0]); } // add to years array
					}, this);
	
					years.sort(this.sort);
			
					if (years[0] > start.getFullYear()) { 
						d = new Date(years[0], start.getMonth() + 1, 0); // last day of new month
					
						if (start.getDate() > d.getDate()) { start.setDate(d.getDate()); }
	
						start.setYear(years[0]); 
					}
					
					if (years.getLast() < end.getFullYear()) { 
						d = new Date(years.getLast(), end.getMonth() + 1, 0); // last day of new month
					
						if (end.getDate() > d.getDate()) { end.setDate(d.getDate()); }
	
						end.setYear(years.getLast());
					}		
				}
	
				if (el.format.test('(F|m|M|n)')) { // search for a month select
					var months_start = [];
					var months_end = [];

					el.getChildren().each(function(option) { // get options
						var values = this.unformat(option.value, el.format);
	
						if ($type(values[0]) != 'number' || values[0] == years[0]) { // if it's a year / month combo for curr year, or simply a month select
							if (!months_start.contains(values[1])) { months_start.push(values[1]); } // add to months array
						}
	
						if ($type(values[0]) != 'number' || values[0] == years.getLast()) { // if it's a year / month combo for curr year, or simply a month select
							if (!months_end.contains(values[1])) { months_end.push(values[1]); } // add to months array
						}
					}, this);
	
					months_start.sort(this.sort);
					months_end.sort(this.sort);
					
					if (months_start[0] > start.getMonth()) { 
						d = new Date(start.getFullYear(), months_start[0] + 1, 0); // last day of new month
					
						if (start.getDate() > d.getDate()) { start.setDate(d.getDate()); }
	
						start.setMonth(months_start[0]); 
					}
					
					if (months_end.getLast() < end.getMonth()) { 
						d = new Date(start.getFullYear(), months_end.getLast() + 1, 0); // last day of new month
					
						if (end.getDate() > d.getDate()) { end.setDate(d.getDate()); }
	
						end.setMonth(months_end.getLast());
					}		
				}
			}
		}, this);
		
		return { 'start': start, 'end': end };
	},


	// caption: returns the caption element with header and navigation
	// @param cal (obj)
	// @returns caption (element)

	caption: function(cal) {
		// start by assuming navigation is allowed
		var navigation = {
			prev: { 'month': true, 'year': true },
			next: { 'month': true, 'year': true }
		};
		
		// if we're in an out of bounds year
		if (cal.year == cal.start.getFullYear()) { 
			navigation.prev.year = false; 
			if (cal.month == cal.start.getMonth() && this.options.navigation == 1) { 
				navigation.prev.month = false;
			}		
		}		
		if (cal.year == cal.end.getFullYear()) { 
			navigation.next.year = false; 
			if (cal.month == cal.end.getMonth() && this.options.navigation == 1) { 
				navigation.next.month = false;
			}
		}

		// special case of improved navigation but months array with only 1 month we can disable all month navigation
		if ($type(cal.months) == 'array') {
			if (cal.months.length == 1 && this.options.navigation == 2) {
				navigation.prev.month = navigation.next.month = false;
			}
		}

		var caption = new Element('caption');

		var prev = new Element('a').addClass(this.classes.prev).appendText('\x3c'); // <		
		var next = new Element('a').addClass(this.classes.next).appendText('\x3e'); // >

		if (this.options.navigation == 2) {
			var month = new Element('span').addClass(this.classes.month).injectInside(caption);
			
			if (navigation.prev.month) { prev.clone().addEvent('click', function(cal) { this.navigate(cal, 'm', -1); }.pass(cal, this)).injectInside(month); }
			
			month.adopt(new Element('span').appendText(this.options.months[cal.month]));

			if (navigation.next.month) { next.clone().addEvent('click', function(cal) { this.navigate(cal, 'm', 1); }.pass(cal, this)).injectInside(month); }

			var year = new Element('span').addClass(this.classes.year).injectInside(caption);

			if (navigation.prev.year) { prev.clone().addEvent('click', function(cal) { this.navigate(cal, 'y', -1); }.pass(cal, this)).injectInside(year); }
			
			year.adopt(new Element('span').appendText(cal.year));

			if (navigation.next.year) { next.clone().addEvent('click', function(cal) { this.navigate(cal, 'y', 1); }.pass(cal, this)).injectInside(year); }
		}
		else { // 1 or 0
			if (navigation.prev.month && this.options.navigation) { prev.clone().addEvent('click', function(cal) { this.navigate(cal, 'm', -1); }.pass(cal, this)).injectInside(caption); }

			caption.adopt(new Element('span').addClass(this.classes.month).appendText(this.options.months[cal.month]));
			
			caption.adopt(new Element('span').addClass(this.classes.year).appendText(cal.year));
			
			if (navigation.next.month && this.options.navigation) { next.clone().addEvent('click', function(cal) { this.navigate(cal, 'm', 1); }.pass(cal, this)).injectInside(caption); }

		}

		return caption;
	},


	// changed: run when a select value is changed
	// @param cal (obj)

	changed: function(cal) {
        
		cal.val = this.read(cal); // update calendar val from inputs

        if (!cal.val) {cal.val = this.readnonselect(cal); }

		$extend(cal, this.values(cal)); // update bounds - based on curr month

		this.rebuild(cal); // rebuild days select
		 // in case the same date was clicked the cal has no set date we should exit

		if (cal.val.getDate() < cal.days[0]) { cal.val.setDate(cal.days[0]); }
		if (cal.val.getDate() > cal.days.getLast()) { cal.val.setDate(cal.days.getLast()); }
		
		cal.els.each(function(el) {	// then we can set the value to the field
			el.value = this.format(cal.val, el.format); 		
		}, this);
		
		this.check(cal); // checks other cals
        
		this.calendars.each(function(kal) { // update cal graphic if visible
			if (kal.visible) { this.display(kal); }
		}, this);
	},


	// check: checks other calendars to make sure no overlapping values
	// @param cal (obj)

	check: function(cal) {
        

		this.calendars.each(function(kal, i) {
//            alert (i);
            if (!kal.val){kal.val=cal.start;}
			if (kal.val) { // if calendar has value set
                var change = false;
				if (i < cal.id) { // preceding calendar
					var bound = new Date(Date.parse(cal.val));
                    
					bound.setDate(bound.getDate() - (this.options.pad * (cal.id - i)));
					if (bound < kal.val) { change = true;}
				}
				if (i > cal.id) { // following calendar
					var bound = new Date(Date.parse(cal.val));
                    
					bound.setDate(bound.getDate() + (this.options.pad * (i - cal.id)));
					if (bound > kal.val) { change = true; }
				}

				if (change) {
					if (kal.start > bound) { bound = kal.start; }
					if (kal.end < bound) { bound = kal.end; }

					kal.month = bound.getMonth();
					kal.year = bound.getFullYear();		

					$extend(kal, this.values(kal));			

					// TODO - IN THE CASE OF SELECT MOVE TO NEAREST VALID VALUE
					// IN THE CASE OF INPUT DISABLE

					// if new date is not valid better unset cal value
					// otherwise it would mean incrementally checking to find the nearest valid date which could be months / years away
					kal.val = kal.days.contains(bound.getDate()) ? bound : null;

					this.write(kal);

					if (kal.visible) { this.display(kal);} // update cal graphic if visible
				}
                else{
                  var bound = new Date(Date.parse(cal.val));
                }
			}
			else {
				kal.month = cal.month;
				kal.year = cal.year;
			}
		}, this);
	},
	

	// clicked: run when a valid day is clicked in the calendar
	// @param cal (obj)

	clicked: function(td, day, cal) {
		cal.val = (this.value(cal) == day) ? null : new Date(cal.year, cal.month, day); // set new value - if same then disable

		this.write(cal); 

		// ok - in the special case that it's all selects and there's always a date no matter what (at least as far as the form is concerned)
		// we can't let the calendar undo a date selection - it's just not possible!!
//		if (!cal.val) { cal.val = this.read(cal); }

		if (cal.val) {
			this.check(cal); // checks other cals						
			this.toggle(cal); // hide cal
		} 
		else { // remove active class and replace with valid
			td.addClass(this.classes.valid);
			td.removeClass(this.classes.active);
		}
	},
	

	// display: create calendar element
	// @param cal (obj)

	display: function(cal) {

		// 1. header and navigation
		this.calendar.empty(); // init div

		this.calendar.className = this.classes.calendar + ' ' + this.options.months[cal.month].toLowerCase();

		var div = new Element('div').injectInside(this.calendar); // a wrapper div to help correct browser css problems with the caption element

		var table = new Element('table').injectInside(div).adopt(this.caption(cal));
				
		// 2. day names		
		var thead = new Element('thead').injectInside(table);

		var tr = new Element('tr').injectInside(thead);
		
		for (var i = 0; i <= 6; i++) {
			var th = this.options.days[(i + this.options.offset) % 7];
			
			tr.adopt(new Element('th', { 'title': th }).appendText(th.substr(0, 1)));
		}

		// 3. day numbers
		var tbody = new Element('tbody').injectInside(table);
		var tr = new Element('tr').injectInside(tbody);

		var d = new Date(cal.year, cal.month, 1);
		var offset = ((d.getDay() - this.options.offset) + 7) % 7; // day of the week (offset)
		var last = new Date(cal.year, cal.month + 1, 0).getDate(); // last day of this month
		var prev = new Date(cal.year, cal.month, 0).getDate(); // last day of previous month
		var active = this.value(cal); // active date (if set and within curr month)
		var valid = cal.days; // valid days for curr month
		var inactive = []; // active dates set by other calendars
		var hilited = [];
		this.calendars.each(function(kal, i) {
			if (kal != cal && kal.val) {
				if (cal.year == kal.val.getFullYear() && cal.month == kal.val.getMonth()) { inactive.push(kal.val.getDate()); }

				if (cal.val) {
					for (var day = 1; day <= last; day++) {
						d.setDate(day);
						
						if ((i < cal.id && d > kal.val && d < cal.val) || (i > cal.id && d > cal.val && d < kal.val)) { 
							if (!hilited.contains(day)) { hilited.push(day); }
						}
					}
				}
			}
		}, this);
		var d = new Date();
		var today = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); // today obv 
		
		for (var i = 1; i < 43; i++) { // 1 to 42 (6 x 7 or 6 weeks)
			if ((i - 1) % 7 == 0) { tr = new Element('tr').injectInside(tbody); } // each week is it's own table row

			var td = new Element('td').injectInside(tr);
						
			var day = i - offset;
			var date = new Date(cal.year, cal.month, day);
			
			var cls = '';
			
			if (day === active) { cls = this.classes.active; } // active
			else if (inactive.contains(day)) { cls = this.classes.inactive; } // inactive
			else if (valid.contains(day)) { cls = this.classes.valid; } // valid
			else if (day >= 1 && day <= last) { cls = this.classes.invalid; } // invalid

			if (date.getTime() == today) { cls = cls + ' ' + this.classes.today; } // adds class for today

			if (hilited.contains(day)) { cls = cls + ' ' + this.classes.hilite; } // adds class if hilited

			td.addClass(cls);

			if (valid.contains(day)) { // if it's a valid - clickable - day we add interaction
				td.setProperty('title', this.format(date, 'D M jS Y'));
				
				td.addEvents({
					'click': function(td, day, cal) { 
						this.clicked(td, day, cal); 
					}.pass([td, day, cal], this),
					'mouseover': function(td, cls) { 
						td.addClass(cls); 
					}.pass([td, this.classes.hover]),
					'mouseout': function(td, cls) { 
						td.removeClass(cls); 
					}.pass([td, this.classes.hover])
				});
			}

			// pad calendar with last days of prev month and first days of next month
			if (day < 1) { day = prev + day; }
			else if (day > last) { day = day - last; }

			td.appendText(day);
		}
	},


	// element: helper function
	// @param el (string) element id
	// @param f (string) format string
	// @param cal (obj)

	element: function(el, f, cal) {
		if ($type(f) == 'object') { // in the case of multiple inputs per calendar
			for (var i in f) { 
				if (!this.element(i, f[i], cal)) { return false; }		
			}
			
			return true;
		}

		el = $(el);

		if (!el) { return false; }
		
		el.format = f;
		
		if (el.get('tag') == 'select') { // select elements allow the user to manually set the date via select option
			el.addEvent('change', function(cal) { this.changed(cal); }.pass(cal, this));
		}
		else { // input (type text) elements restrict the user to only setting the date via the calendar
			el.readOnly = true;
			el.addEvent('focus', function(cal) { this.toggle(cal); }.pass(cal, this));
		}

		cal.els.push(el);

		return true;
	},


	// format: formats a date object according to passed in instructions
	// @param date (obj)
	// @param f (string) any combination of punctuation / separators and d, j, D, l, S, m, n, F, M, y, Y
	// @returns string

	format: function(date, format) {
		var str = '';
		
		if (date) {
			var j = date.getDate(); // 1 - 31
      var w = date.getDay(); // 0 - 6
			var l = this.options.days[w]; // Sunday - Saturday
			var n = date.getMonth() + 1; // 1 - 12
			var f = this.options.months[n - 1]; // January - December
			var y = date.getFullYear() + ''; // 19xx - 20xx
			
			for (var i = 0, len = format.length; i < len; i++) {
				var cha = format.charAt(i); // format char
				
				switch(cha) {
					// year cases
					case 'y': // xx - xx
						y = y.substr(2);
					case 'Y': // 19xx - 20xx
						str += y;
						break;
	
					// month cases
					case 'm': // 01 - 12
						if (n < 10) { n = '0' + n; }
					case 'n': // 1 - 12
						str += n;
						break;
	
					case 'M': // Jan - Dec
						f = f.substr(0, 3);
					case 'F': // January - December
						str += f;
						break;
	
					// day cases
					case 'd': // 01 - 31
						if (j < 10) { j = '0' + j; }
					case 'j': // 1 - 31
						str += j;
						break;
	
					case 'D': // Sun - Sat
						l = l.substr(0, 3);
					case 'l': // Sunday - Saturday
						str += l;
						break;
	
					case 'N': // 1 - 7
						w += 1;
					case 'w': // 0 - 6
						str += w;
						break;

					case 'S': // st, nd, rd or th (works well with j)
						if (j % 10 == 1 && j != '11') { str += 'st'; }
						else if (j % 10 == 2 && j != '12') { str += 'nd'; }
						else if (j % 10 == 3 && j != '13') { str += 'rd'; }
						else { str += 'th'; }
						break;
	
					default:
						str += cha;
				}
			}
		}

	  return str; //  return format with values replaced
	},


	// navigate: calendar navigation
	// @param cal (obj)
	// @param type (str) m or y for month or year
	// @param n (int) + or - for next or prev

	navigate: function(cal, type, n) {
		switch (type) {
			case 'm': // month
					if ($type(cal.months) == 'array') {
						var i = cal.months.indexOf(cal.month) + n; // index of current month
						
						if (i < 0 || i == cal.months.length) { // out of range
							if (this.options.navigation == 1) { // if type 1 nav we'll need to increment the year
								this.navigate(cal, 'y', n);		
							}
		
							i = (i < 0) ? cal.months.length - 1 : 0;
						}

						cal.month = cal.months[i];
					}
					else { 
						var i = cal.month + n;
		
						if (i < 0 || i == 12) {
							if (this.options.navigation == 1) {
								this.navigate(cal, 'y', n);	
							}
		
							i = (i < 0) ? 11 : 0;
						}
						
						cal.month = i;
					}		
					break;

				case 'y': // year
					if ($type(cal.years) == 'array') {
						var i = cal.years.indexOf(cal.year) + n;

						cal.year = cal.years[i]; 
					}
					else { 
						cal.year += n;
					}						
					break;		
		}

		$extend(cal, this.values(cal));

		if ($type(cal.months) == 'array') { // if the calendar has a months select
			var i = cal.months.indexOf(cal.month); // and make sure the curr months exists for the new year

			if (i < 0) { cal.month = cal.months[0]; } // otherwise we'll reset the month
		}


		this.display(cal);
	},


	// read: compiles cal value based on array of inputs passed in
	// @param cal (obj)
	// @returns date (obj) or (null)

	read: function(cal) {
		var arr = [null, null, null];

		cal.els.each(function(el) {
			// returns an array which may contain empty values
			var values = this.unformat(el.value, el.format);
			
			values.each(function(val, i) { 
				if ($type(val) == 'number') { arr[i] = val; }

			}); 
		}, this);
        
		// we can update the cals month and year values
		if ($type(arr[0]) == 'number') { cal.year = arr[0]; }
		if ($type(arr[1]) == 'number') { cal.month = arr[1];}
//        if (cal.notSelected == 1) { cal.month = cal.month;}

		var val = null;

		if (arr.every(function(i) { return $type(i) == 'number'; })) { // if valid date
			var last = new Date(arr[0], arr[1] + 1, 0).getDate(); // last day of month

			if (arr[2] > last) { arr[2] = last; } // make sure we stay within the month (ex in case default day of select is 31 and month is feb)
			
			val = new Date(arr[0], arr[1], arr[2]);
		}

		return (cal.val == val) ? null : val; // if new date matches old return null (same date clicked twice = disable)
	},

    	// read: compiles cal value based on array of inputs passed in
	// @param cal (obj)
	// @returns date (obj) or (null)

	readnonselect: function(cal) {
		var arr = [null, null, null];

		cal.els.each(function(el) {
			// returns an array which may contain empty values
			var values = this.unformat(el.value, el.format);

			values.each(function(val, i) {
				if ($type(val) == 'number') { arr[i] = val; }

			});
		}, this);

		// we can update the cals month and year values
		if ($type(arr[0]) == 'number') { cal.year = arr[0]; }
		if ($type(arr[1]) == 'number') { cal.month = arr[1];}
        if ($type(arr[0]) != 'number') { cal.year = cal.start.getFullYear();
            arr[0] = cal.start.getFullYear();
        }
		if ($type(arr[1]) != 'number') { cal.month = cal.start.getMonth();
            arr[1] = cal.start.getMonth();
        }
        if ($type(arr[2]) != 'number') { cal.dey = cal.start.getDate();
            arr[2] = cal.start.getDate();
        }

		var val = null;

		if (arr.every(function(i) { return $type(i) == 'number'; })) { // if valid date
			var last = new Date(arr[0], arr[1] + 1, 0).getDate(); // last day of month

			if (arr[2] > last) { arr[2] = last; } // make sure we stay within the month (ex in case default day of select is 31 and month is feb)

			val = new Date(arr[0], arr[1], arr[2]);
		}

		return (cal.val == val) ? null : val; // if new date matches old return null (same date clicked twice = disable)
	},

	
	// rebuild: rebuilds days + months selects
	// @param cal (obj)

	rebuild: function(cal) {
		cal.els.each(function(el) {			
			/*
			if (el.get('tag') == 'select' && el.format.test('^(F|m|M|n)$')) { // special case for months-only select
				if (!cal.options) { cal.options = el.clone(); } // clone a copy of months select
			
				var val = (cal.val) ? cal.val.getMonth() : el.value.toInt();

				el.empty(); // initialize select

				cal.months.each(function(month) {
					// create an option element
					var option = new Element('option', {
						'selected': (val == month),
						'value': this.format(new Date(1, month, 1), el.format);
					}).appendText(day).injectInside(el);
				}, this);
			}
			*/

			if (el.get('tag') == 'select' && el.format.test('^(d|j)$')) { // special case for days-only select
				var d = this.value(cal);

				if (!d) { d = el.value.toInt(); } // if the calendar doesn't have a set value, try to use value from select

				el.empty(); // initialize select
                if (this.options.notSelected == 1){
                var option = new Element('option', {
						'selected': '',
						'value': ''
					}).appendText('День').injectInside(el);}
                
				cal.days.each(function(day) {
					// create an option element
					var option = new Element('option', {
						'selected': (d == day),
						'value': ((el.format == 'd' && day < 10) ? '0' + day : day)
					}).appendText(day).injectInside(el);
				}, this);
			}
		}, this); 
	},


	// sort: helper function for numerical sorting

	sort: function(a, b) {
		return a - b;
	},


	// toggle: show / hide calendar 
	// @param cal (obj)

	toggle: function(cal) {
		document.removeEvent('mousedown', this.fn); // always remove the current mousedown script first
			
		if (cal.visible) { // simply hide curr cal						
			cal.visible = false;
			cal.button.removeClass(this.classes.active); // active
			
			this.fx.start('opacity', 1, 0);
		}
		else { // otherwise show (may have to hide others)
			// hide cal on out-of-bounds click
			this.fn = function(e, cal) { 
				var e = new Event(e);
			
				var el = e.target;

				var stop = false;
				
				while (el != document.body && el.nodeType == 1) {
					if (el == this.calendar) { stop = true; }
					this.calendars.each(function(kal) {
						if (kal.button == el || kal.els.contains(el)) { stop = true; }
					});

					if (stop) { 
						e.stop();
						return false;
					}
					else { el = el.parentNode; }
				}
				
				this.toggle(cal);
			}.create({ 'arguments': cal, 'bind': this, 'event': true });				

			document.addEvent('mousedown', this.fn);

			this.calendars.each(function(kal) {
				if (kal == cal) {
					kal.visible = true;
					kal.button.addClass(this.classes.active); // css c-icon-active
				}
				else {
					kal.visible = false;
					kal.button.removeClass(this.classes.active); // css c-icon-active
				}
			}, this);
			
			var size = window.getScrollSize();
			
			var coord = cal.button.getCoordinates();

			var x = coord.right + this.options.tweak.x;
			var y = coord.top + this.options.tweak.y;
			
			//Меняем положение календаря если он будет 
			//открыт вне окна
			if (window.ie6) {
				
			}else{
			var posit = window.getScroll();
			var calposit = $(cal.el).getCoordinates();
			var vindow = window.getSize();
			var visible = calposit.top - posit.y + 160;
			if (visible > vindow.y ){
				var y = coord.top + this.options.tweak.y - this.options.tweak.sdvig; 	
			}
			}
			//
			// make sure the calendar doesn't open off screen
			if (!this.calendar.coord) { this.calendar.coord = this.calendar.getCoordinates(); }

			if (x + this.calendar.coord.width > size.x) { x -= (x + this.calendar.coord.width - size.x); }
			if (y + this.calendar.coord.height > size.y) { y -= (y + this.calendar.coord.height - size.y); }
			
			this.calendar.setStyles({ left: x + 'px', top: y + 'px' });

			if (window.ie6) { 
				this.iframe.setStyles({ height: this.calendar.coord.height + 'px', left: x + 'px', top: y + 'px', width: this.calendar.coord.width + 'px' }); 
			}

			this.display(cal);
			
			this.fx.start('opacity', 0, 1);
		}
	},


	// unformat: takes a value from an input and parses the d, m and y elements
	// @param val (string)
	// @param f (string) any combination of punctuation / separators and d, j, D, l, S, m, n, F, M, y, Y
	// @returns array
	
	unformat: function(val, f) {
		f = f.escapeRegExp();
		
		var re = {
			d: '([0-9]{2})',
			j: '([0-9]{1,2})',
			D: '(' + this.options.days.map(function(day) { return day.substr(0, 3); }).join('|') + ')',					
			l: '(' + this.options.days.join('|') + ')',
			S: '(st|nd|rd|th)',
			F: '(' + this.options.months.join('|') + ')',
			m: '([0-9]{2})',
			M: '(' + this.options.months.map(function(month) { return month.substr(0, 3); }).join('|') + ')',					
			n: '([0-9]{1,2})',
			Y: '([0-9]{4})',
			y: '([0-9]{2})'
		}

		var arr = []; // array of indexes

		var g = '';

		// convert our format string to regexp
		for (var i = 0; i < f.length; i++) {
			var c = f.charAt(i);
			
			if (re[c]) {
				arr.push(c);

				g += re[c];
			}
			else {
				g += c;
			}
		}

		// match against date
		var matches = val.match('^' + g + '$');
		
		var dates = new Array(3);

		if (matches) {
			matches = matches.slice(1); // remove first match which is the date

			arr.each(function(c, i) {
				i = matches[i];
				
				switch(c) {
					// year cases
					case 'y':
						i = '19' + i; // 2 digit year assumes 19th century (same as JS)
					case 'Y':
						dates[0] = i.toInt();
						break;

					// month cases
					case 'F':
						i = i.substr(0, 3);
					case 'M':
						i = this.options.months.map(function(month) { return month.substr(0, 3); }).indexOf(i) + 1;
					case 'm':
					case 'n':
						dates[1] = i.toInt() - 1;
						break;

					// day cases
					case 'd':
					case 'j':
						dates[2] = i.toInt();
						break;
				}
			}, this);
		}

		return dates;
	},


	// value: returns day value of calendar if set
	// @param cal (obj)
	// @returns day (int) or null

	value: function(cal) {
		var day = null;

		if (cal.val) {
			if (cal.year == cal.val.getFullYear() && cal.month == cal.val.getMonth()) { day = cal.val.getDate(); }
		}

		return day;
	},
	

	// values: returns the years, months (for curr year) and days (for curr month and year) for the calendar
	// @param cal (obj)
	// @returns obj	

	values: function(cal) {
		var years, months, days;

		cal.els.each(function(el) {	
			if (el.get('tag') == 'select') {		
				if (el.format.test('(y|Y)')) { // search for a year select
					years = [];

					el.getChildren().each(function(option) { // get options
						var values = this.unformat(option.value, el.format);
	
						if (!years.contains(values[0])) { years.push(values[0]); } // add to years array
					}, this);
	
					years.sort(this.sort);
				}
	
				if (el.format.test('(F|m|M|n)')) { // search for a month select
					months = []; // 0 - 11 should be

					el.getChildren().each(function(option) { // get options
						var values = this.unformat(option.value, el.format);
	
						if ($type(values[0]) != 'number' || values[0] == cal.year) { // if it's a year / month combo for curr year, or simply a month select
							if (!months.contains(values[1])) { months.push(values[1]); } // add to months array
						}
					}, this);
	
					months.sort(this.sort);
				}
				
				if (el.format.test('(d|j)') && !el.format.test('^(d|j)$')) { // search for a day select, but NOT a days only select
					days = []; // 1 - 31
					
					el.getChildren().each(function(option) { // get options
						var values = this.unformat(option.value, el.format);

						// in the special case of days we dont want the value if its a days only select
						// otherwise that will screw up the options rebuilding
						// we will take the values if they are exact dates though
						if (values[0] == cal.year && values[1] == cal.month) {
							if (!days.contains(values[2])) { days.push(values[2]); } // add to days array
						}
					}, this);
				}
			}
		}, this);
		
		// we start with what would be the first and last days were there no restrictions
		var first = 1;
		var last = new Date(cal.year, cal.month + 1, 0).getDate(); // last day of the month
		
		// if we're in an out of bounds year
		if (cal.year == cal.start.getFullYear()) {
			// in the special case of improved navigation but no months array, we'll need to construct one
			if (months == null && this.options.navigation == 2) {
				months = [];
				
				for (var i = 0; i < 12; i ++) { 
					if (i >= cal.start.getMonth()) { months.push(i); } 
				}
			}
			
			// if we're in an out of bounds month
			if (cal.month == cal.start.getMonth()) { 
				first = cal.start.getDate(); // first day equals day of bound
			}
		}		
		if (cal.year == cal.end.getFullYear()) {
			// in the special case of improved navigation but no months array, we'll need to construct one
			if (months == null && this.options.navigation == 2) {
				months = [];
				
				for (var i = 0; i < 12; i ++) { 
					if (i <= cal.end.getMonth()) { months.push(i); } 
				}
			}

			if (cal.month == cal.end.getMonth()) { 
				last = cal.end.getDate(); // last day equals day of bound
			}
		}

		// let's get our invalid days
		var blocked = this.blocked(cal);

		// finally we can prepare all the valid days in a neat little array
		if ($type(days) == 'array') { // somewhere there was a days select
			days = days.filter(function(day) {
				if (day >= first && day <= last && !blocked.contains(day)) { return day; }
			});
		}
		else { // no days select we'll need to construct a valid days array
			days = [];
			
			for (var i = first; i <= last; i++) { 
				if (!blocked.contains(i)) { days.push(i); }
			}
		}		

		days.sort(this.sort); // sorting our days will give us first and last of month

		return { 'days': days, 'months': months, 'years': years };
	},


	// write: sets calendars value to form elements
	// @param cal (obj)

	write: function(cal) {
		this.rebuild(cal);	 // in the case of options, we'll need to make sure we have the correct number of days available
		
		cal.els.each(function(el) {	// then we can set the value to the field
			el.value = this.format(cal.val, el.format); 		
		}, this);
	}
});

Calendar.implement(new Events, new Options);
/**
 * Ria_Comments_ShowBlock
 *
 * @class       Ria_Comments_ShowBlock
 * @copyright   2009 RIA-MUTIMEDIA
 * @license     GNU GPL v2
 * @author      Yuriy Horbeko
 *
 *
*/
var Ria_Comments_ShowBlock = new Class ({

 initialize: function(){
        this.showCommentBlock();
    },
    
    showCommentBlock:function (){
        
        if ($('comment_block').getStyle('display')=='none'){
            $('comment_block').setStyle('display', 'block');
        }
        else{
            $('comment_block').setStyle('display', 'none');
        }
    }

})



/**
 * Ria_Comments_Add
 *
 * @class       Ria_Comments_AddComment
 * @copyright   2009 RIA-MUTIMEDIA
 * @license     GNU GPL v2
 * @author      Yuriy Horbeko
 *
 *
*/
var Ria_Comments_AddComment = new Class ({

 initialize: function(comment_id){

        this.comment = comment_id;
//        $(button).addEvent('onclick', function(){
        this.showCommentForm( this.comment);
 //       }.bind(this));

    },
    showCommentForm: function(comment){
        if ($('comment_'+comment).getStyle('display')=='none'){
            $('comment_'+comment).setStyle('display', 'block');
        }
        else{
            $('comment_'+comment).setStyle('display', 'none');
        }
    }

})



/*
	Class: FormCheck
		Performs different tests on forms and indicates errors.
		
	Usage:
		Works with these types of fields :
		- input (text, radio, checkbox)
		- textarea
		- select
		
		You just need to add a specific class to each fields you want to check. 
		For example, if you add the class
			(code)
			validate['required','length[4, -1]','differs[email]','digit']
			(end code)
		the value's field must be set (required) with a minimum length of four chars (4, -1), 
		must differs of the input named email (differs[email]), and must be digit. 
		
		You can perform check during the datas entry or on the submit action, shows errors as tips or in a div before or after the field, 
		show errors one by one or all together, show a list of all errors at the top of the form, localize error messages, add new regex check, ...
		
		The layout is design only with css. Now I added a hack to use transparent png with IE6, so you can use png images in formcheck.css (works only for theme, so the file must be named formcheck.css). It can also works with multiple forms on a single html page.
		The class supports now internationalization. To use it, simply specify a new <script> element in your html head, like this : <script type="text/javascript" src="formcheck/lang/fr.js"></script>.

		If you add the class
			(code)
			validate['submit']
			(end code)
		to an element like an anchor (or anything else), this element will act as a submit button.
		
		N.B. : you must load the language script before the formcheck and this method overpass the old way. You can create new languages following existing ones. You can otherwise still specifiy the alerts' strings when you initialize the Class, with options.
		If you don't use a language script, the alert will be displayed in english.
	
	Test type:
		You can perform various test on fields by addind them to the validate class. Be careful to *not use space chars*. Here is the list of them.
			
		required 					- The field becomes required. This is a regex, you can change it with class options.
		alpha 						- The value is restricted to alphabetic chars. This is a regex, you can change it with class options.
		alphanum 					- The value is restricted to alphanumeric characters only. This is a regex, you can change it with class options.
		nodigit 					- The field doesn't accept digit chars. This is a regex, you can change it with class options.
		digit 						- The value is restricted to digit (no floating point number) chars, you can pass two arguments (f.e. digit[21,65]) to limit the number between them. Use -1 as second argument to not set a maximum.
		number 						- The value is restricted to number, including floating point number. This is a regex, you can change it with class options.
		email 						- The value is restricted to valid email. This is a regex, you can change it with class options.
		phone 						- The value is restricted to phone chars. This is a regex, you can change it with class options.
		url: 						- The value is restricted to url. This is a regex, you can change it with class options.
		confirm 					- The value has to be the same as the one passed in argument. f.e. confirm[password].
		differs 					- The value has to be diferent as the one passed in argument. f.e. differs[user].
		length 						- The value length is restricted by argument (f.e. length[6,10]). Use -1 as second argument to not set a maximum.
		
		You can also use a custom function to check a field. For example, if you have a field with class
			(code)
			validate['required','%customCheck']
			(end code)
		the function customCheck(el) will be called to validate the field.
		Here is an example of what customCheck could look : 
			(code)
			function customCheck(el){
				if (!el.value.test(/^[A-Z]/)) {
					el.errors.push("Username should begin with an uppercase letter"); 
					return false;
				} else {
					return true;
				}
			}
			(end code)
		
	Parameters:
		When you initialize the class with addEvent, you can set some options. If you want to modify regex, you must do it in a hash, like for display or alert. You can also add new regex check method by adding the regex and an alert with the same name.
		
		Required:
			
			form_id - The id of the formular. This is required.
			
		Optional:
			
			submitByAjax 			- you can set this to true if you want to submit your form with ajax. You should use provided events to handle the ajax request (see below). By default it is false.
			ajaxResponseDiv 		- id of element to inject ajax response into (can also use onAjaxSuccess). By default it is false.
			ajaxEvalScripts 		- use evalScripts in the Request response. Can be true or false, by default it is false.
			onAjaxRequest 			- Function to fire when the Request event starts.
			onAjaxSuccess 			- Function to fire when the Request receives .  Args: response [the request response] - see Mootools docs for Request.onSuccess.
			onAjaxFailure 			- Function to fire if the Request fails.
			
			tipsClass 				- The class to apply to tipboxes' errors. By default it is 'fc-tbx'.
			errorClass 				- The class to apply to alertbox (not tips). By default it is 'fc-error'.
			fieldErrorClass 		- The class to apply to fields with errors, except for radios. You should also turn on  options.addClassErrorToField. By default it is 'fc-field-error'
			
			trimValue				- If set to true, strip whitespace (or other characters) from the beginning and end of values. By default it is false.
			validateDisabled		- If set to true, disabled input will be validated too, otherwise not.

		Display:
			This is a hash of display settings. in here you can modify.
			
			showErrors 				- 0 : onSubmit, 1 : onSubmit & onBlur, by default it is 1.
			titlesInsteadNames		- 0 : When you do a check using differs or confirm, it takes the field name for the alert. If it's set to 1, it will use the title instead of the name.
			errorsLocation 			- 1 : tips, 2 : before, 3 : after, by default it is 1.
			indicateErrors 			- 0 : none, 1 : one by one, 2 : all, by default it is 1.
			keepFocusOnError 		- 0 : normal behaviour, 1 : the current field keep the focus as it remain errors. By default it is 0.
			checkValueIfEmpty 		- 0 : When you leave a field and you have set the showErrors option to 1, the value is tested only if a value has been set. 1 : The value is tested  in any case.  By default it is 1.
			addClassErrorToField 	- 0 : no class is added to the field, 1 : the options.fieldErrorClass is added to the field with an error (except for radio). By default it is 0.

			fixPngForIe 			- 0 : do nothing, 1 : fix png alpha for IE6 in formcheck.css. By default it is 1.
			replaceTipsEffect 		- 0 : No effect on tips replace when we resize the broswer, 1: tween transition on browser resize;
			closeTipsButton 		- 0 : the close button of the tipbox is hidden, 1 : the close button of the tipbox is visible. By default it is 1.
			flashTips 				- 0 : normal behaviour, 1 : the tipbox "flash" (disappear and reappear) if errors remain when the form is submitted. By default it is 0.
			tipsPosition 			- 'right' : the tips box is placed on the right part of the field, 'left' to place it on the left part. By default it is 'right'.
			tipsOffsetX 			- Horizontal position of the tips box (margin-left), , by default it is 100 (px).
			tipsOffsetY				- Vertical position of the tips box (margin-bottom), , by default it is -10 (px).
			
			listErrorsAtTop 		- List all errors at the top of the form, , by default it is false.
			scrollToFirst 			- Smooth scroll the page to first error and focus on it, by default it is true.
			fadeDuration 			- Transition duration (in ms), by default it is 300.
		
		Alerts:
			This is a hash of alerts settings. in here you can modify strings to localize or wathever else. %0 and %1 represent the argument.
			
			required 				- "This field is required."
			alpha 					- "This field accepts alphabetic characters only."
			alphanum 				- "This field accepts alphanumeric characters only."
			nodigit 				- "No digits are accepted."
			digit 					- "Please enter a valid integer."
			digitmin 				- "The number must be at least %0"
			digitltd 				- "The value must be between %0 and %1"
			number 					- "Please enter a valid number."
			email 					- "Please enter a valid email: <br /><span>E.g. yourname@domain.com</span>"
			phone 					- "Please enter a valid phone."
			url 					- "Please enter a valid url: <br /><span>E.g. http://www.domain.com</span>"
			confirm 				- "This field is different from %0"
			differs 				- "This value must be different of %0"
			length_str 				- "The length is incorrect, it must be between %0 and %1"
			length_fix 				- "The length is incorrect, it must be exactly %0 characters"
			lengthmax 				- "The length is incorrect, it must be at max %0"
			lengthmin 				- "The length is incorrect, it must be at least %0"
			checkbox 				- "Please check the box"
			radios 					- "Please select a radio"
			select 					- "Please choose a value"
		
	Example:
		You can initialize a formcheck (no scroll, custom classes and alert) by adding for example this in your html head this code :
		
		(code)
		<script type="text/javascript">
			window.addEvent('domready', function() {
				var myCheck = new FormCheck('form_id', {
					tipsClass : 'tips_box',
					display : {
						scrollToFirst : false
					},
					alerts : {
						required : 'This field is ablolutely required! Please enter a value'
					}
				})
			});
		</script>
		(end code)
	
	About:
		formcheck.js v.1.4 for mootools v1.2 - 11 / 2008
		
		by Floor SA (http://www.floor.ch) MIT-style license
		
		Created by Luca Pillonel, last modified by Luca Pillonel
		
	Credits:
		This class was inspired by fValidator by Fabio Zendhi Nagao (http://zend.lojcomm.com.br)	
*/

var Floor_FormCheck = new Class({
	
	Implements: [Options, Events],

	options : {
		
		tipsClass: 'fc-tbx',				//tips error class
		errorClass: 'fc-error',				//div error class
		fieldErrorClass: 'fc-field-error',	//error class for elements
		
		trimValue : false,					//trim (remove whitespaces before and after) the value
		validateDisabled : false,			//skip validation on disabled input if set to false.
		
		submitByAjax : false,				//false : standard submit way, true : submit by ajax
		ajaxResponseDiv : false,			//element to inject ajax response into (can also use onAjaxSuccess) [cronix] 
		ajaxEvalScripts : false,			//use evalScripts in the Request response [cronix] 
		onAjaxRequest : $empty,				//Function to fire when the Request event starts 
		onAjaxSuccess : $empty,				//Function to fire when the Request receives .  Args: response [the request response] - see Mootools docs for Request.onSuccess 
		onAjaxFailure : $empty,				//Function to fire if the Request fails 
		
		display : {
			showErrors : 1,
			titlesInsteadNames : 0,
			errorsLocation : 1,
			indicateErrors : 1,
			keepFocusOnError : 0,
			checkValueIfEmpty : 1,
			addClassErrorToField : 0,
			fixPngForIe : 1,
			replaceTipsEffect : 1,
			flashTips : 0,
			closeTipsButton : 1,
			tipsPosition : "right",
			tipsOffsetX : -45,
			tipsOffsetY : 0,
			listErrorsAtTop : false,
			scrollToFirst : true,
			fadeDuration : 300
		},
		
		alerts : {
			required: "This field is required.",
			alpha: "This field accepts alphabetic characters only.",
			alphanum: "This field accepts alphanumeric characters only.",
			nodigit: "No digits are accepted.",
			digit: "Please enter a valid integer.",
			digitltd: "The value must be between %0 and %1",
			number: "Please enter a valid number.",
			email: "Please enter a valid email.",
			phone: "Please enter a valid phone.",
			url: "Please enter a valid url.",
			
			confirm: "This field is different from %0",
			differs: "This value must be different of %0",
			length_str: "The length is incorrect, it must be between %0 and %1",
			length_fix: "The length is incorrect, it must be exactly %0 characters",
			lengthmax: "The length is incorrect, it must be at max %0",
			lengthmin: "The length is incorrect, it must be at least %0",
			checkbox: "Please check the box",
			radios: "Please select a radio",
			select: "Please choose a value"
		},
		
		regexp : {
			required : /[^.*]/,
			alpha : /^[a-z ._-]+$/i,
			alphanum : /^[a-z0-9 ._-]+$/i,
			digit : /^[-+]?[0-9]+$/,
			nodigit : /^[^0-9]+$/,
			number : /^[-+]?\d*\.?\d+$/,
			email : /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i,
			phone : /^[\d\s ().-]+$/,
			url : /^(http|https|ftp)\:\/\/[a-z0-9\-\.]+\.[a-z]{2,3}(:[a-z0-9]*)?\/?([a-z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~])*$/i
		}
	},
	
	/*
	Constructor: initialize
		Constructor
	
		Add event on formular and perform some stuff, you now, like settings, ...
	*/
	initialize : function(form, options) {
		if (this.form = $(form)) {
			this.form.isValid = true;
			this.regex = ['length'];
			this.setOptions(options);
			
			//internalization
			if (typeof(formcheckLanguage) != 'undefined') this.options.alerts = $merge(this.options.alerts, formcheckLanguage);
			
			this.validations = [];
			this.alreadyIndicated = false;
			this.firstError = false;
			
			var regex = new Hash(this.options.regexp);
			regex.each(function(el, key) {
				this.regex.push(key);
			}, this);

			this.form.getElements("*[class*=validate]").each(function(el) {
				el.validation = [];
				var classes = el.getProperty("class").split(' ');
				classes.each(function(classX) {
					if(classX.match(/^validate(\[.+\])$/)) {
						var validators = eval(classX.match(/^validate(\[.+\])$/)[1]);
						for(var i = 0; i < validators.length; i++) {
							el.validation.push(validators[i]);
						}
						this.register(el);
					}
				}, this);
			}, this);
			
			this.form.addEvents({
				"submit": this.onSubmit.bind(this)
			});
			
			if(this.options.display.fixPngForIe) this.fixIeStuffs();
			document.addEvent('mousewheel', function(){
				this.isScrolling = false;
			}.bind(this));
		}
	},
	
	/*
	Function: register
		Private method
		
		Add listener on fields
	*/
	register : function(el) {
		this.validations.push(el);
		el.errors = [];
		if (el.validation[0] == 'submit') {
			el.addEvent('click', function(e){
				this.onSubmit(e);
			}.bind(this));
			return true;
		}

		if (this.isChildType(el) == false) el.addEvent('blur', function(e) {
			if((el.element || this.options.display.showErrors == 1) && (this.options.display.checkValueIfEmpty || el.value)) this.manageError(el, 'blur');
		}.bind(this))
		//We manage errors on radio
		else if (this.isChildType(el) == true) {
			//We get all radio from the same group and add a blur option
			var nlButtonGroup = this.form.getElements('input[name="'+ el.getProperty("name") +'"]');
			nlButtonGroup.each(function(radio){
				radio.addEvent('blur', function(){
					if((el.element || this.options.display.showErrors == 1) && (this.options.display.checkValueIfEmpty || el.value)) this.manageError(el, 'click');
				}.bind(this))
			},this);
		}
	},
	
	/*
	Function: validate
		Private method
		
		Dispatch check to other methods
	*/
	validate : function(el) {
		if (this.options.validateDisabled && el.get('disabled')) return true;
		if (this.options.trimValue && el.value) el.value = el.value.trim();

		//On valide l'element qui n'est pas un radio ni checkbox
		el.errors = [];
		el.isOk = true;
		el.validation.each(function(rule) {
			if(this.isChildType(el)) {
				if (this.validateGroup(el) == false) {
					el.isOk = false;
				}
			} else {
				var ruleArgs = [];
				if(rule.match(/^.+\[/)) {
					var ruleMethod = rule.split('[')[0];
					ruleArgs = eval(rule.match(/^.+(\[.+\])$/)[1].replace(/([0-9A-Z\._]+)/i, "'$1'"));
				} else var ruleMethod = rule;
				if (this.regex.contains(ruleMethod) && el.get('tag') != "select") {
					if (this.validateRegex(el, ruleMethod, ruleArgs) == false) {
						el.isOk = false;
					}
				}
				
				if (ruleMethod == 'confirm') {
					if (this.validateConfirm(el, ruleArgs) == false) {
						el.isOk = false;
					}
				}
				if (ruleMethod == 'differs') {
					if (this.validateDiffers(el, ruleArgs) == false) {
						el.isOk = false;
					}
				}
				if (el.get('tag') == "select" || (el.type == "checkbox" && ruleMethod == 'required')) {
					if (this.simpleValidate(el) == false) {
						el.isOk = false;
					}
				}
				if(rule.match(/%[a-z0-9_]+$/) || (el.isOk && rule.match(/~[a-z0-9_]+$/))) {
					if(eval(rule.slice(1)+'(el)') == false) {
						el.isOk = false;
					}
				}
			}
		}, this);
		
		if (el.isOk) return true;
		else return false;
	},
	
	/*
	Function: simpleValidate
		Private method
		
		Perform simple check for select fields and checkboxes
	*/
	simpleValidate : function(el) {
		if (el.get('tag') == 'select' && el.selectedIndex <= 0) {
			el.errors.push(this.options.alerts.select);
			return false;
		} else if (el.type == "checkbox" && el.checked == false) {
			el.errors.push(this.options.alerts.checkbox);
			return false;
		}
		return true;
	},
	
	/*
	Function: validateRegex
		Private method
		
		Perform regex validations
	*/
	validateRegex : function(el, ruleMethod, ruleArgs) {
		var msg = "";
		if (ruleArgs[1] && ruleMethod == 'length') {
			if (ruleArgs[1] == -1) {
				this.options.regexp.length = new RegExp("^[\\s\\S]{"+ ruleArgs[0] +",}$");
				msg = this.options.alerts.lengthmin.replace("%0",ruleArgs[0]);
			} else if(ruleArgs[0] == ruleArgs[1]) {
				this.options.regexp.length = new RegExp("^[\\s\\S]{"+ ruleArgs[0] +"}$");
				msg = this.options.alerts.length_fix.replace("%0",ruleArgs[0]);
			} else {
				this.options.regexp.length = new RegExp("^[\\s\\S]{"+ ruleArgs[0] +","+ ruleArgs[1] +"}$");
				msg = this.options.alerts.length_str.replace("%0",ruleArgs[0]).replace("%1",ruleArgs[1]);
			}
		} else if (ruleArgs[0] && ruleMethod == 'length') {
			this.options.regexp.length = new RegExp("^.{0,"+ ruleArgs[0] +"}$");
			msg = this.options.alerts.lengthmax.replace("%0",ruleArgs[0]);
		} else {
			msg = this.options.alerts[ruleMethod];
		}
		if (ruleArgs[1] && ruleMethod == 'digit') {
			var regres = true;
			if (!this.options.regexp.digit.test(el.value)) {
				el.errors.push(this.options.alerts[ruleMethod]);
				regres = false;
			}
			if (ruleArgs[1] == -1) {
				if (el.value >= ruleArgs[0]) var valueres = true; else var valueres = false;
				msg = this.options.alerts.digitmin.replace("%0",ruleArgs[0]);
			} else {
				if (el.value >= ruleArgs[0] && el.value <= ruleArgs[1]) var valueres = true; else var valueres = false;
				msg = this.options.alerts.digitltd.replace("%0",ruleArgs[0]).replace("%1",ruleArgs[1]);
			}
			if (regres == false || valueres == false) {
				el.errors.push(msg);
				return false;
			}
		} else if (this.options.regexp[ruleMethod].test(el.value) == false)  {
			el.errors.push(msg);
			return false;
		}
		return true;
	},

	/*
	Function: validateConfirm
		Private method
		
		Perform confirm validations
	*/
	validateConfirm: function(el,ruleArgs) {
		if (el.validation.contains('required') == false) {
			el.validation.push('required');
		}
		var confirm = ruleArgs[0];
		if(el.value != this.form[confirm].value){
			if (this.options.display.titlesInsteadNames)
				var msg = this.options.alerts.confirm.replace("%0",this.form[confirm].getProperty('title'));
			else
				var msg = this.options.alerts.confirm.replace("%0",confirm);
			el.errors.push(msg);
			return false;
		}
		return true;
	},
	
	/*
	Function: validateDiffers
		Private method
		
		Perform differs validations
	*/
	validateDiffers: function(el,ruleArgs) {
		var differs = ruleArgs[0];
		if(el.value == this.form[differs].value){
			if (this.options.display.titlesInsteadNames)
				var msg = this.options.alerts.differs.replace("%0",this.form[differs].getProperty('title'));
			else
				var msg = this.options.alerts.differs.replace("%0",differs);
			el.errors.push(msg);
			return false;
		}
		return true;
	},
	
	/*
	Function: isChildType
		Private method
		
		Determine if the field is a group of radio or not.
	*/
	isChildType: function(el) {
		return ($defined(el.type) && el.type == 'radio') ? true : false;
	},
	
	/*
	Function: validateGroup
		Private method
		
		Perform radios validations
	*/
	validateGroup : function(el) {
		el.errors = [];
		var nlButtonGroup = this.form[el.getProperty("name")];
		el.group = nlButtonGroup;
		var cbCheckeds = false;
		
		for(var i = 0; i < nlButtonGroup.length; i++) {
			if(nlButtonGroup[i].checked) {
				cbCheckeds = true;
			}
		}
		if(cbCheckeds == false) {
			el.errors.push(this.options.alerts.radios);
			return false;
		} else {
			return true;	
		}
	},
	
	/*
	Function: listErrorsAtTop
		Private method
		
		Display errors
	*/
	listErrorsAtTop : function(obj) {
		if(!this.form.element) {
			 this.form.element = new Element('div', {'id' : 'errorlist', 'class' : this.options.errorClass}).injectTop(this.form);
		}
		if ($type(obj) == 'collection') {
			new Element('p').set('html',"<span>" + obj[0].name + " : </span>" + obj[0].errors[0]).injectInside(this.form.element);
		} else {
			if ((obj.validation.contains('required') && obj.errors.length > 0) || (obj.errors.length > 0 && obj.value && obj.validation.contains('required') == false)) {
				obj.errors.each(function(error) {
					new Element('p').set('html',"<span>" + obj.name + " : </span>" + error).injectInside(this.form.element);
				}, this);
			}
		}
	},
	
	/*
	Function: manageError
		Private method
		
		Manage display of errors boxes
	*/
	manageError : function(el, method) {
		var isValid = this.validate(el);
		if ((!isValid && el.validation.contains('required')) || (!el.validation.contains('required') && el.value && !isValid)) {
			if(this.options.display.listErrorsAtTop == true && method == 'submit')
				this.listErrorsAtTop(el, method);
			if (this.options.display.indicateErrors == 2 ||this.alreadyIndicated == false || el.name == this.alreadyIndicated.name)
			{
				if(!this.firstError) this.firstError = el;
				this.alreadyIndicated = el;
				if (this.options.display.keepFocusOnError && el.name == this.firstError.name) (function(){el.focus()}).delay(20);
				this.addError(el);
				return false;
			}
		} else if ((isValid || (!el.validation.contains('required') && !el.value)) && el.element) {
			this.removeError(el);
			return true;
		}
		return true;
	},
	
	/*
	Function: addError
		Private method
		
		Add error message
	*/
	addError : function(obj) {
		if(!obj.element && this.options.display.indicateErrors != 0) {
			if (this.options.display.errorsLocation == 1) {
				var pos = (this.options.display.tipsPosition == 'left') ? obj.getCoordinates().left : obj.getCoordinates().right;
				var options = {
					'opacity' : 0,
					'position' : 'absolute',
					'float' : 'left',
					'left' : pos + this.options.display.tipsOffsetX
				}
				obj.element = new Element('div', {'class' : this.options.tipsClass, 'styles' : options}).injectInside(document.body);
				this.addPositionEvent(obj);
			} else if (this.options.display.errorsLocation == 2){
				obj.element = new Element('div', {'class' : this.options.errorClass, 'styles' : {'opacity' : 0}}).injectBefore(obj);
			} else if (this.options.display.errorsLocation == 3){
				obj.element = new Element('div', {'class' : this.options.errorClass, 'styles' : {'opacity' : 0}});
				if ($type(obj.group) == 'object' || $type(obj.group) == 'collection')
					obj.element.injectAfter(obj.group[obj.group.length-1]);
				else
					obj.element.injectAfter(obj);
			}
		}					
		if (obj.element) {
			obj.element.empty();
			if (this.options.display.errorsLocation == 1) {
				var errors = [];
				obj.errors.each(function(error) {
					errors.push(new Element('p').set('html', error));
				});
				var tips = this.makeTips(errors).injectInside(obj.element);
				if(this.options.display.closeTipsButton) {
					tips.getElements('a.close').addEvent('mouseup', function(){
						this.removeError(obj);
					}.bind(this));
				}
				obj.element.setStyle('top', obj.getCoordinates().top - tips.getCoordinates().height + this.options.display.tipsOffsetY);
			} else {
				obj.errors.each(function(error) {
					new Element('p').set('html',error).injectInside(obj.element);
				});
			}
			
			if (!Browser.Engine.trident5 && obj.element.getStyle('opacity') == 0)
				new Fx.Morph(obj.element, {'duration' : this.options.display.fadeDuration}).start({'opacity':[1]});
			else
				obj.element.setStyle('opacity', 1);
		}
		if (this.options.display.addClassErrorToField && this.isChildType(obj) == false)
		{
			obj.addClass(this.options.fieldErrorClass);
		}
	},
	
	/*
	Function: addPositionEvent
		
		Update tips position after a browser resize
	*/
	addPositionEvent : function(obj) {
		if(this.options.display.replaceTipsEffect) {
			obj.event = function(){
				new Fx.Morph(obj.element, {
					'duration' : this.options.display.fadeDuration
				}).start({ 
					'left':[obj.element.getStyle('left'), obj.getCoordinates().right + this.options.display.tipsOffsetX],
					'top':[obj.element.getStyle('top'), obj.getCoordinates().top - obj.element.getCoordinates().height + this.options.display.tipsOffsetY]
				});
			}.bind(this);
			
		} else {
			obj.event = function(){
				obj.element.setStyles({ 
					'left':obj.getCoordinates().right + this.options.display.tipsOffsetX,
					'top':obj.getCoordinates().top - obj.element.getCoordinates().height + this.options.display.tipsOffsetY
				});
			}.bind(this)
		}
		window.addEvent('resize', obj.event);
	},
	
	/*
	Function: removeError
		Private method
		
		Remove the error display
	*/
	removeError : function(obj) {
		this.firstError = false;
		this.alreadyIndicated = false;
		obj.errors = [];
		obj.isOK = true;
		window.removeEvent('resize', obj.event);
		if (this.options.display.errorsLocation == 2)
			new Fx.Morph(obj.element, {'duration' : this.options.display.fadeDuration}).start({ 'height':[0] });
		if (!Browser.Engine.trident5) {
			new Fx.Morph(obj.element, {
				'duration' : this.options.display.fadeDuration,
				'onComplete' : function() {
					if (obj.element) {
						obj.element.destroy();
						obj.element = false;
					}
				}.bind(this)
			}).start({ 'opacity':[1,0] });
		} else {
			obj.element.destroy();
			obj.element = false;
		}
		
		if (this.options.display.addClassErrorToField && !this.isChildType(obj))
		{
			obj.removeClass(this.options.fieldErrorClass);
		}
	},
	
	/*
	Function: focusOnError
		Private method
		
		Create set the focus to the first field with an error if needed
	*/
	focusOnError : function (obj) {
		if (this.options.display.scrollToFirst && !this.alreadyFocused && !this.isScrolling) {
			if (this.alreadyIndicated.element) {
				switch (this.options.display.errorsLocation){
					case 1 : 
						var dest = obj.element.getCoordinates().top;
						break;
					case 2 :
						var dest = obj.element.getCoordinates().top-30;
						break;
					case 3 :
						var dest = obj.getCoordinates().top-30;
						break;
				}
				this.isScrolling = true;
			} else if (!this.options.display.indicateErrors) {
				var dest = obj.getCoordinates().top-30;
			}
			if (window.getScroll.y != dest) {
				new Fx.Scroll(window, {
					onComplete : function() {
						this.isScrolling = false;
						obj.focus();
					}.bind(this)
				}).start(0,dest);
			} else {
				this.isScrolling = false;
				obj.focus();
			}
			this.alreadyFocused = true;
		}
	},
	
	/*
	Function: fixIeStuffs
		Private method
		
		Fix png for IE6
	*/
	fixIeStuffs : function () {
		if (Browser.Engine.trident4) {
			//We fix png stuffs
			var rpng = new RegExp('url\\(([\.a-zA-Z0-9_/:-]+\.png)\\)');
			var search = new RegExp('(.+)formcheck\.css');
			for (var i = 0; i < document.styleSheets.length; i++){
				if (document.styleSheets[i].href.match(/formcheck\.css$/)) {
					var root = document.styleSheets[i].href.replace(search, '$1');
					var count = document.styleSheets[i].rules.length;
					for (var j = 0; j < count; j++){
						var cssstyle = document.styleSheets[i].rules[j].style;
						var bgimage = root + cssstyle.backgroundImage.replace(rpng, '$1');
						if (bgimage && bgimage.match(/\.png/i)){
							var scale = (cssstyle.backgroundRepeat == 'no-repeat') ? 'crop' : 'scale';
							cssstyle.filter =  'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src=\'' + bgimage + '\', sizingMethod=\''+ scale +'\')';
							cssstyle.backgroundImage = "none";
						}
					}
				}
			}
		}
	},
	
	/*
	Function: makeTips
		Private method
		
		Create tips boxes
	*/
	makeTips : function(txt) {
		var table = new Element('table');
			table.cellPadding ='0';
			table.cellSpacing ='0';
			table.border ='0';
			
			var tbody = new Element('tbody').injectInside(table);
				var tr1 = new Element('tr').injectInside(tbody);
					new Element('td', {'class' : 'tl'}).injectInside(tr1);
					new Element('td', {'class' : 't'}).injectInside(tr1);
					new Element('td', {'class' : 'tr'}).injectInside(tr1);
				var tr2 = new Element('tr').injectInside(tbody);
					new Element('td', {'class' : 'l'}).injectInside(tr2);
					var cont = new Element('td', {'class' : 'c'}).injectInside(tr2);
						var errors = new Element('div', {'class' : 'err'}).injectInside(cont);
						txt.each(function(error) {
							error.injectInside(errors);
						});
						if (this.options.display.closeTipsButton) new Element('a',{'class' : 'close'}).injectInside(cont);
					//	new Element('div', {'style' : "clear:both"}).injectInside(cont);
					new Element('td', {'class' : 'r'}).injectInside(tr2);
				var tr3 = new Element('tr').injectInside(tbody);
					new Element('td', {'class' : 'bl'}).injectInside(tr3);
					new Element('td', {'class' : 'b'}).injectInside(tr3);
					new Element('td', {'class' : 'br'}).injectInside(tr3);			
		return table;
	},
	
	/*
	Function: reinitialize
		Private method		
		
		Reinitialize form before submit check
	*/
	reinitialize: function() {
		this.validations.each(function(el) {
			if (el.element) {
				el.errors = [];
				el.isOK = true;
				if(this.options.display.flashTips == 1) {
					el.element.destroy();
					el.element = false;
				}
			}
		}, this);
		if (this.form.element) this.form.element.empty();
		this.alreadyFocused = false;
		this.firstError = false;
		this.alreadyIndicated = false;
		this.form.isValid = true;
	},
	
	/*
	Function: submitByAjax
		Private method		
		
		Send the form by ajax, and replace the form with response
	*/
	
	submitByAjax: function() {
		var url = this.form.getProperty('action');
		this.fireEvent('ajaxRequest');
		new Request({
			url: url,
			method: this.form.getProperty('method'),
			data : this.form.toQueryString(),
			evalScripts: this.options.ajaxEvalScripts,
			onFailure: function(instance){
				this.fireEvent('ajaxFailure', instance);
			}.bind(this),
			onSuccess: function(result){
				this.fireEvent('ajaxSuccess', result);
				if(this.options.ajaxResponseDiv) $(this.options.ajaxResponseDiv).set('html',result);
			}.bind(this)
		}).send();
	},
	
	/*
	Function: onSubmit
		Private method		
		
		Perform check on submit action
	*/
	onSubmit: function(event) {
		this.reinitialize();
		
		this.validations.each(function(el) {
			if(!this.manageError(el,'submit')) this.form.isValid = false;
		}, this);
		if (this.form.isValid) {
			if (this.options.submitByAjax) {
				new Event(event).stop();
				this.submitByAjax();
			}
		} else {
			new Event(event).stop();
			this.focusOnError(this.firstError)
		}
	}
});
/**
 * Abstract class RIA Framework JSON Request
 *
 * @class      RIA_JsonRequest
 * @copyright  2008 IT RIA
 * @license    GNU GPL v2
 * @version    Release: $Revision: 1.2 $
 * @author     <a href="mailto:Oleg.Cherniy@gmail.com">Oleg Cherniy</a>
 * @requires   Ria_Core_Ajax
 */

var Ria_Core_Ajax_JsonRequest = new Class({

	Implements: Options,
	
	options: {
		target: 'main',
		event: ''
	},

	/**
	 * @raram {Array} options параметры для построения запроса
	 */
	initialize: function(options){
		this.setOptions(options);
		new Request.JSON({url: Ria_Core_Ajax.script,
			onComplete: this.onGetResponse.bind(this)
		}).get(this.options);
	},
	
	/**
	 * Метод, который будет выполнен после получения
	 * ответа на Ajax-запрос.
	 * Вам  нужно его переопредплить.
	 * 
	 * @param {Object} jsonObj Объект с данными из JSON-ответа
	 */
	onGetResponse: function(jsonObj) {}
});

/**
 * Ria_CitySelect_Manager
 *
 * @class       Ria_CitySelect_Manager
 * @copyright   MegaDevel
 * @license     GNU GPL v2
 * @author      MegaDevel
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_CitySelect_CityManager = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 'CitySelect',
		event: 'getCities'
	},

	initialize: function(options){
		this.loading();
		this.setOptions(options);
		this.parent(options);
	},

	loading: function(){
	},

	onGetResponse: function(obj){
	    var select = $('city_cahge_select');
	    select.empty();
	    if(obj.Cities){
		    var Cities = obj.Cities;
		    var option  = new Element('option',{'value':-1, 'html':'--------'});
		    option.inject(select);
		    var option  = new Element('option',{'value':0, 'html':'Другие области'});
		    option.inject(select);
		    Cities.each(function(item){
			    var option  = new Element('option',{'value':item.eng, 'html':item.name});
			    option.inject(select);
		    });
	    }
	}

});
/**
 * Ria_CitySelect_Manager
 *
 * @class       Ria_CitySelect_Manager
 * @copyright   MegaDevel
 * @license     GNU GPL v2
 * @author      MegaDevel
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_CitySelect_RegionManager = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 'CitySelect',
		event: 'getRegions'
	},

	initialize: function(options){
		this.loading();
		this.setOptions(options);
		this.parent(options);
	},

	loading: function(){
	},

	onGetResponse: function(obj){
	    var select = $('city_cahge_select'); 
	    select.empty();
	    if(obj.Regions){
		    var Regions = obj.Regions;
		    var option  = new Element('option',{'value':0, 'html':'----------'});
		    option.inject(select);
		    Regions.each(function(item){
			    var option  = new Element('option',{'value':item.stateID, 'html':item.name});
			    option.inject(select);
		    });
	    }
	}
});
/**
 * Ria_Vote_VoteManager
 *
 * @class       Ria_Vote_VoteManager
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Subscribe_Add = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'subscribe',
		event: 		'main'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);
	},

	onGetResponse: function(jsonObj){
	    $('sbscrvd1').setStyle('display','none');
	    $('sbscrvd2').setStyle('display','none');
	    $('sbscrvd3').setStyle('display','none');
	    $('sbscrvd4').setStyle('display','none');
	    $('sbscrvd5').setStyle('display','none');

	    $(jsonObj.subscribevalid).setStyle('display','block');
	    if (jsonObj.subscribevalid=='sbscrvd1'){
		$('sName').set('value', '');
		$('sEmail').set('value', '');
	    }
	}
});
/**
 * Ria_Rotator_Material
 *
 * @class       Ria_Rotator_Material
 * @copyright   2009 RIA-MUTIMEDIA
 * @license     GNU GPL v2
 * @author      Sergey Zelenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Rotator_AfishaMaterial = new Class ({

    Extends: Ria_Core_Ajax_JsonRequest,

    options: {
        target:     'rotatorAfisha'
    },

    initialize: function(options){
        this.setOptions(options);
        this.parent(options);
	this.returnObj='';
    },

    onGetResponse: function(jsonObj){
	jsonObj.data="{"+jsonObj.data+"}";
	//AfishaMaterialArr.str=jsonObj.str;
	AfishaMaterialArr=JSON.decode(jsonObj.data);
	AfishaMaterialCount=jsonObj.dataCount;
	AfishaMaterialUpdate=1;
    }
});
/**
 * Ria_Login_CheckUserEmail
 *
 * @class       Ria_Login_CheckUserEmail
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Login_CheckUserEmail = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'login',
		event: 		'check_user'
	},

	initialize: function(options){
                this.setOptions(options);
                this.parent(options);
            

  	},

	onGetResponse: function(jsonObj){
            
          var  user= jsonObj.user;
          var commentId = jsonObj.commentId;
       // console.log("user[0]['auth_type']");
        if (user==0){
            if(commentId){
               $('answer_user_'+commentId).set('html',"Пожалуйста, проверьте правильность введенного e-mail адреса. Если он введен правильно, то Вас запомнят на нашем сайте и в следующий раз Вы сможете входить на сайт используя указанный e-mail адрес.");
               $('answer_user_'+commentId).setAttribute('class','important');
               $('answer_user_'+commentId).setAttribute('style','display:block');
               $('input_psw_'+commentId).setAttribute('style', "display:none;");
            } else {
               $('user_msg').set('html',"Пожалуйста, проверьте правильность введенного e-mail адреса. Если он введен правильно, то Вас запомнят на нашем сайте и в следующий раз Вы сможете входить на сайт используя указанный e-mail адрес.");
               $('user_msg').setAttribute('class','important');
               $('user_msg').setAttribute('style','display:block');
               $('input_psw').setAttribute('style', "display:none;");
            }
            
        } else {
            if(user[0]['auth_type']==1){
                if(commentId){
                    $('user_name_'+commentId).set('value',user[0]['fio']);
                    $('user_id_'+commentId).set('value',user[0]['user_id']);
                    $('input_name_'+commentId).setAttribute('style', "display:block;");
                    $('input_email_'+commentId).setAttribute('style', "display:none;");
                    $('answer_user_'+commentId).setAttribute('style','display:none');
                    $('input_psw_'+commentId).setAttribute('style', "display:none;");
                }else{
                    $('user_name').set('value',user[0]['fio']);
                    $('user_id').set('value',user[0]['user_id']);
                    $('input_name').setAttribute('style', "display:block;");
                    $('input_email').setAttribute('style', "display:none;");
                    $('user_msg').setAttribute('style','display:none');
                    $('input_psw').setAttribute('style', "display:none;");
                }
            }
            if(user[0]['auth_type']==3){
                if(commentId){
                   $('answer_user_'+commentId).set('html',"Для указанного E-mail адреса необходим пароль.");
                   $('answer_user_'+commentId).setAttribute('class','important');
                   $('answer_user_'+commentId).setAttribute('style', "display:block;");
                   $('input_psw_'+commentId).setAttribute('style', "display:block;");
                } else {
                     $('user_msg').set('html',"Для указанного E-mail адреса необходим пароль.");
                     $('user_msg').setAttribute('class','important');
                     $('user_msg').setAttribute('style', "display:block;");
                     $('input_psw').setAttribute('style', "display:block;");
                }
            }
        }
    }

});


/**
 * Ria_Login_CheckUserPassword
 *
 * @class       Ria_Login_CheckUserEmail
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Login_CheckUserPassword = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'login',
		event: 		'check_user_pasword'
	},

	initialize: function(options){
                this.setOptions(options);
                this.parent(options);


  	},

	onGetResponse: function(jsonObj){

          var  user= jsonObj.user;
          var commentId = jsonObj.commentId;
        if (user==0){
            if(commentId){
                $('answer_user_'+commentId).set('html',"Введен неправильный пароль.");
                $('answer_user_'+commentId).setAttribute('class','error');
                $('answer_user_'+commentId).setAttribute('style','display:block');
            }else {
                $('user_msg').set('html',"Введен неправильный пароль.");
                $('user_msg').setAttribute('class','error');
                $('user_msg').setAttribute('style','display:block');
            }
        } else {
             if(commentId){
              
                    $('user_name_'+commentId).set('value',user[0]['fio']);
                    $('user_id_'+commentId).set('value',user[0]['user_id']);
                    $('input_name_'+commentId).setAttribute('style', "display:block;");
                    $('input_email_'+commentId).setAttribute('style', "display:none;");
                    $('answer_user_'+commentId).setAttribute('style','display:none');
                    $('input_psw_'+commentId).setAttribute('style', "display:none;");
             }else {
         //   $('user_name').setAttribute('style','disable:true');
                    $('user_name').set('value',user[0]['fio']);
                    $('user_id').set('value',user[0]['user_id']);
                    $('input_name').setAttribute('style', "display:block;");
                    $('input_email').setAttribute('style', "display:none;");
                    $('user_msg').setAttribute('style','display:none');
                    $('input_psw').setAttribute('style', "display:none;");
             }
        }
    }

});


/**
 * Ria_Vote_VoteManager
 *
 * @class       Ria_Vote_VoteManager
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Vote_VoteManager = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'vote_commentPositive'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);

	},

	onGetResponse: function(jsonObj){
		var vote = jsonObj.votes;
                var rating = jsonObj.rating;
                var commentId = jsonObj.comment_id;

                $('commp_' + commentId).setStyle('display', 'none');
                 $('commn_' + commentId).setStyle('display', 'none');
                 if (rating>0){
                   var  sign = "+";
                 }else {
                  var sign = "";
                 }
		$('value_' + commentId).set('html',sign+rating+" / "+"<span class='plusT'>"+vote+"</span>");
          
	}
});
/**
 * Ria_Tree_Characters
 *
 * @class       Ria_Tree_Characters
 * @copyright   MegaDevel
 * @license     GNU GPL v2
 * @author      MegaDevel
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/

var Ria_Tree_Characters = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 'tree',
		event:  'char'
	},

	initialize: function(options){
		this.setOptions(options);
		new Request.JSON({url: Ria_Core_Ajax.script,
			onComplete: this.onGetResponse.bind(this),
			onFailure:this.loadError.bind(this)
		}).get(this.options);
	},
	
	loadError: function(el){
		try {
			$('loading').innerHTML = 'Ошибка доступа к серверу. Перегрузите страницу!';
			$('loading').setStyle('display', 'block');
		} catch (e) {
			alert('Обратитесь ко мне =).')
		}
	},
	
	onGetResponse: function(obj){
		var char_type = obj.type;
		var data = obj.data;
		var board = $('board');
		board.innerHTML = '. . .';
		
		//text field
		var Field = new Element('input',{
									'id':'myField',
									'type':'text'
									});
		if($chk(data)){
			if($chk(data.value_type)){
				if(data.value_type==1){
					Field.set('value', data.value_int);
				}
				if(data.value_type==2){
					Field.set('value', data.value_str);
				}
			}
			//Field.set('value', data.value);
		}
		
		
		
		Field.addEvent('keydown', function(event){
			changeMe(event);
		});
		
		board.innerHTML='<b>'+tree.getSelected().name+':</b>';
		Field.inject(board);
		
		return false;

	}
});


function changeMe(e){
	var Button = new Element('input',{
		'id':'myButton',
		'type':'button',
		'value':'OK'
		});
	
	Button.addEvent('click', function(event){
		new Ria_Tree_EditText({'value':$('myField').value,
								id:tree.getSelected().data.id,
								object_id:object_id,
								object_type:object_type});
	});
	if(!$chk($('myButton'))){
		Button.inject($('board'));
	}
}
/**
 * Ria_Tree_EditCheckBoxs
 *
 * @class       Ria_Tree_EditCheckBoxs
 * @copyright   MegaDevel
 * @license     GNU GPL v2
 * @author      MegaDevel
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/

var Ria_Tree_EditCheckBoxs = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 'tree',
		event: 'checkbox'
	},

	initialize: function(options){
		this.setOptions(options);
		this.setLoad();
		new Request.JSON({url: Ria_Core_Ajax.script,
			onComplete: this.onGetResponse.bind(this),
			onFailure:this.loadError.bind(this)
		}).get(this.options);
	},
	
	loadError: function(el){
		try {
			$('loading').innerHTML = 'Ошибка доступа к серверу. Перегрузите страницу!';
			$('loading').setStyle('display', 'block');
		} catch (e) {
			alert('Обратитесь ко мне =).')
		}
	},
	
	onGetResponse: function(obj){
		
		new Ria_Afisha_Manager({
			target:'tree',
			event:'refresh_char',
			object_id:object_id,
			object_type:object_type
		});
		return true;
	},
	
	setLoad:function(){
		$('character_list').innerHTML = 'Загрузка ...';
	}
});

/**
 * Ria_Tree_EditText
 *
 * @class       Ria_Tree_EditText
 * @copyright   MegaDevel
 * @license     GNU GPL v2
 * @author      MegaDevel
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/

var Ria_Tree_EditText = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 'tree',
		event: 'textarea'
	},

	initialize: function(options){
		this.setOptions(options);
		if(this.options.event!='del_char'){
			this.setLoad();
		}
		new Request.JSON({url: Ria_Core_Ajax.script,
			onComplete: this.onGetResponse.bind(this),
			onFailure:this.loadError.bind(this)
		}).get(this.options);
	},
	
	loadError: function(el){
		try {
			$('loading').innerHTML = 'Ошибка доступа к серверу. Перегрузите страницу!';
			$('loading').setStyle('display', 'block');
		} catch (e) {
			alert('Обратитесь ко мне =).')
		}
	},
	
	
	onGetResponse: function(obj){
		if(this.options.event=='del_char'){
			this.onDel(obj);
		}
		else{
			new Ria_Afisha_Manager({
				target:'tree',
				event:'refresh_char',
				object_id:object_id,
				object_type:object_type
			});
		}
		return false;
	},
	
	onDel: function(obj){
		$('row_'+this.options.id).innerHTML='<span style="color:#F00;">Удалено!</span>';
	},
	
	setLoad:function(){
		$('character_list').innerHTML = 'Загрузка ...';
	}
});

/**
 * Ria_Afisha_Manager
 *
 * @class       Ria_Afisha_Manager
 * @copyright   MegaDevel
 * @license     GNU GPL v2
 * @author      MegaDevel
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Afisha_Manager = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 'afisha'
	},

	initialize: function(options){
		this.loading();
		this.setOptions(options);
		this.parent(options);
	},
	
	onFailure: function(obj){
		console.log('error');	
		console.log(obj);	
	},
	
	onGetResponse: function(obj){
		switch (this.options.event) {
		
			case 'set_person_type':
				this.setPersonType(obj);
			break;
			
			case 'clubs':
				this.getClubs(obj);
			break;
			
			case 'make_persons':
				this.getMakePersons(obj);
				break;
		
			case 'del_persons':
				this.delPersons(obj);
			break;
	
			case 'dates':
				this.getDates(obj);
			break;
				
			case 'add_seans':
				this.addSeans(obj);
			break;
			
			case 'show_add_date':
				this.showAddDate(obj);
			break;
			
			case 'add_date':
				this.addDate(obj);
			break;
			
			case 'add_club':
				this.addClub(obj);
			break;
				
			case 'times':
				this.getTimes(obj);
			break;
	
			case 'del_calendar':
				this.delCalendar(obj);
			break;

			case 'refresh_char':
				this.refreshChar(obj);
			break;
	
			default:
				return false;
			break;
			
		}
		$('loading').setStyle('display', 'none');
		
	},
	
	setPersonType: function(result){
		$(this.options.person_id).setStyle('border-color', '#61AE4E');
	},
	
	delPersons: function(result){
		$('person_'+this.options.person_id).innerHTML = 'deleted';
	},
	
	getMakePersons: function(result){
		$('persons').innerHTML = result.tpl;
	},
	
	getClubs: function(result){
		$('board_'+this.options.city_id).innerHTML = result.tpl;
	},
	
	refreshChar: function(result){
		$('character_list').innerHTML = result.tpl;
	},

	getDates: function(result){
		$('club_board_'+this.options.club_id).innerHTML = result.tpl;
	},

	getTimes: function(result){
		$('dates_board_'+this.options.date+'_'+this.options.club_id).innerHTML = result.tpl;
	},

	delCalendar: function(result){
		showTimes(this.options.unix_date,this.options.club_id);
	},
	
	addSeans: function(result){
		showTimes(this.options.unix_date, this.options.club_id);
	},
	
	addDate: function(result){
		showDates(this.options.club_id);
	},
	
	addClub: function(result){
		showClubs(this.options.city_id);
	},
	
	showAddDate: function(result){
		var city_id = this.options.city_id;
		$('city_board_'+this.options.city_id).innerHTML = result.tpl;
		myCal1 = new Calendar({ date1: 'Y-m-d' }, { direction: 0, tweak: { x: 6, y: 0 }});
		
		var container = $('city_board_'+this.options.city_id); 
	

		generate_select_hours(container, 1);
		
		var dvoetochie = new Element('span', {html: ':'});
		dvoetochie.inject(container);
		
		generate_select_time(container, '00');
		
		var button = new Element('input', {type: 'button',
										   name: 'OK',
										   value: 'OK'
											});
		button.addEvent('click', function(){
				
			new Ria_Afisha_Manager({
				event:'add_club',
				date:$('date1').value,
				hours:$('hours').value,
				event_id:event_id,
				city_id:city_id,
				minutes:minutes_list[$('minutes').value],
				club_id:$('club_selector').value
			});
		});	
		button.inject(container);
		
	},
	
	loading: function(){
		$('loading').setStyle('display', 'block');
	}
});

/**
 * Some additional functions
 * 
 * Some additional functions
 * 
 * Some additional functions
 */

/**
 * Удаление сеанса 
 * @param {Object} calendar_id
 * @param {Object} club_id
 * @param {Object} unix_date
 */
del_calendar = function(calendar_id, club_id, unix_date){
	new Ria_Afisha_Manager({
		event: 'del_calendar',
		club_id:club_id,
		unix_date:unix_date,
		calendar_id:calendar_id
	});
};

/**
 *  Генерация блока добавления 
 * @param {Object} unix_date
 * @param {Object} club_id
 */

add_time = function(unix_date, club_id){
	var container = $('time_section_' + unix_date + '_' + club_id);
	container.innerHTML+='<div>Добавить сеанс на:</div>';
	generate_select_hours(container, 9);
	var dvoetochie = new Element('span', {html: ':'});
	dvoetochie.inject(container);
	generate_select_time(container, 30);
	
	var button = new Element('input', {type: 'button',
									   name: 'OK',
									   value: 'OK'
										});
	button.addEvent('click', function(){
			
		new Ria_Afisha_Manager({
			event:'add_seans',
			unix_date:unix_date,
			hours:$('hours').value,
			event_id:event_id,
			minutes:minutes_list[$('minutes').value],
			club_id:club_id
		});
	});	
	button.inject(container);
									
};


var minutes_list = ['00','05','10','15','20','25','30','35','40','45','50','55'];
/**
 *  Генерация селектора минут
 * @param {Object} elem
 * @param {Object} sel_time
 */
generate_select_time = function(elem, sel_time){
	
	 var select = new Element('select',{
	 	id:'minutes',
		name:'minutes',
         styles:{
            display:'inline'
         }
      }).inject(elem);
		
	 var list = minutes_list;
      list.each(function(el, i){
	  		
         var o = new Element('option', {
            value: i,
            html: el,
         }).inject(select);

         if (o.innerHTML == sel_time) {
		 	o.setProperty('selected', 'selected');
         }
      });
};

/**
 * Генерация селектора часов
 * @param {Object} elem
 * @param {Object} sel_hour
 */
generate_select_hours = function(elem, sel_hour){
	 var select1 = new Element('select',{
	 	id:'hours',
		name:'hours',
         styles:{
            display:'inline'
         }
      }).inject(elem);
		
	 for (var i = 0; i <= 23; i++){
	 	
		//if(i>6){
		     var s = new Element('option', {
	            value: i,
	            html: i,
				id: 'id_'+i
	         }).inject(select1);
			 
			 if (i == sel_hour) {
			 	s.set('selected', 'selected');
	         }
		//}
	}

	return true;
};


/**
 * Генерация блока добавления даты
 * @param {int} club_id
 */
add_date = function(club_id){
	
	$('date_board_'+club_id).innerHTML = '<input id="date1" class="calendar" type="text" name="date1" readonly=""/>';
	myCal1 = new Calendar({ date1: 'Y-m-d' }, { tweak: { x: 6, y: 0 }});

	
	var container = $('date_board_'+club_id); 
	
	generate_select_hours(container, 0);
	var dvoetochie = new Element('span', {html: ':'});
	dvoetochie.inject(container);
	generate_select_time(container, '00');
	
	var button = new Element('input', {type: 'button',
									   name: 'OK',
									   value: 'OK'
										});
	button.addEvent('click', function(){
			
		new Ria_Afisha_Manager({
			event:'add_date',
			date:$('date1').value,
			hours:$('hours').value,
			event_id:event_id,
			minutes:minutes_list[$('minutes').value],
			club_id:club_id
		});
	});	
	button.inject($('date_board_'+club_id));
};

add_club = function(city_id){
	new Ria_Afisha_Manager({
		event:'show_add_date',
		city_id:city_id
	});
}

/**
 * Ria_Vote_VoteForPhoto
 *
 * @class       Ria_Vote_VoteForPhoto
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Vote_VoteForPhoto = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'vote_for_photo'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);

	},

	onGetResponse: function(jsonObj){
		var vote = jsonObj.voted;
                var photoId = jsonObj.photoId;
                var rating = jsonObj.rating;
                var photoRating = "&nbsp;&nbsp;&nbsp; Рейтинг:&nbsp;"+rating;

              
                if (vote==1){
                //  $('voted').setStyle('display', 'block');
                  $('addVoice_' + photoId).setStyle('display', 'none');
                  var voteText= "<span class='golSpan' id='voted' style='display:block'>Cпасибо, Ваш голос учтен!</span>";
                      $('golos').set('html', voteText);
                       $('photo_rating').set('html',photoRating);
                 
                 
                }else{
                    $('voted').setStyle('display', 'none');
                  $('addVoice_' + photoId).setStyle('display', 'block');
                }
                
	}
});
/**
 * Ria_Photo_LeafPhotos
 *
 * @class       Ria_Photo_LeafPhotos
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_LeafPhotos = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'leaf_right'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);
                $('scroll').empty().addClass('ajax-loading');
      	},

	onGetResponse: function(jsonObj){
                var littlePhotos = jsonObj.photos;
                var photo='';
                var photo_class;
               littlePhotoArray = littlePhotos;
                littlePhotos.each(function(value, index){
                  
                    if(value.photo_id==bigPhotoId){
                         photo_class = 'activeSmallPrew';
                    } else{
                        photo_class = 'smallPrew';
                    }
                  photo =photo+ "<div><a href='photos/"+littlePhotos[0]['photoReport_id']+"/photo/"+value.photo_id+"/' class='"+photo_class+"' id='photo_"+value.photo_id+"'> <img src='http://img.ria.ua/photos/"+value.src.replace('.','sw.')+"'"+'/> </a><div><div>'+value.photoNumber+'</div></div></div>';
                  lastPhotoID = value.photo_id;                  
                })
                  firstPhotoID = littlePhotos[0]['photo_id'];
          $('scroll').removeClass('ajax-loading');
          $('scroll').set('html',photo);
          if (littlePhotos[0]['photoNumber']==1){
             $('left-button').setAttribute('class','first-notactive');
             $('left-button-home').setAttribute('class','notactive');
              $('left-button-home').set('html',"<b>В начало</b>");
             $('left-button-5').setAttribute('class','notactive');
             $('left-button-5').set('html', "<b>Предыдущие 5</b>");
          } else {
              $('left-button').setAttribute('class','first');
              $('left-button-home').set('html',"<a  href='begin/photo/"+bigPhotoId+"/' id='toBegin_href'><b>В начало</b></a>");
               $('left-button-home').removeProperty('class');
               $('left-button-5').set('html', "<a href='previous/"+littlePhotos[0]['photo_id']+"/photo/"+bigPhotoId+"/'><b id='PrevFive_href'>Предыдущие 5</b></a>");
               $('left-button-5').removeProperty('class');
          }
          if (littlePhotos[4]['photoNumber']==littlePhotos[4]['countPhotosInReport']){
             $('right-button').setAttribute('class','next-notactive');
             $('right-button-end').setAttribute('class','notactive');
             $('right-button-end').set('html',"<b>В конец</b>");
             $('right-button-5').setAttribute('class','notactive');
             $('right-button-5').set('html',"<b>Следующие 5</b>");
          } else {
              $('right-button').setAttribute('class','next');
              $('right-button-end').set('html',"<a href='end/photo/"+bigPhotoId+"/' ><b id='toEnd_href'>В конец</b></a>");
              $('right-button-end').removeProperty('class');
              $('right-button-5').set('html',"<a href='next/"+littlePhotos[4]['photo_id']+"/photo/"+bigPhotoId+"/' ><b id='NextFive_href'>Следующие 5</b></a>");
              $('right-button-5').removeProperty('class');
          }

    //  $$('.smallPrew').removeEvents('click');
            
            $$('.smallPrew').addEvent('click', function(e) {
                var reg = /\D*/;
                scroll.toElement('BigPhotoToScroll');
              var photoId = this.getAttribute('id').replace(reg, "");
              new Ria_Photo_ShowBigPhoto({'photoId':photoId,'photoReportID':littlePhotos[0]['photoReport_id']});

                return false;
            });
            if($('toBegin_href')){
                $('toBegin_href').addEvent('click', function() {
                        new Ria_Photo_PhotosToBegin({'photoReport':littlePhotos[0]['photoReport_id']});
                    return false;
                 });
            }
            if($('toEnd_href')){
                 $('toEnd_href').addEvent('click', function() {
                    new  Ria_Photo_PhotosToEnd({'photoReport':littlePhotos[0]['photoReport_id']});
                    return false;
                });
            }
              if($('PrevFive_href')){
                 $('PrevFive_href').addEvent('click', function() {
                        new  Ria_Photo_GetPrevFivePhotos({'photoId':littlePhotos[0]['photo_id']});

                        return false;
                    });
              }
             if($('NextFive_href')){
                $('NextFive_href').addEvent('click', function() {
                    new  Ria_Photo_GetNextFivePhotos({'photoId':littlePhotos[4]['photo_id']});
                    return false;
                });
             }

           
   
        }


});


/**
 * Ria_Photo_ShowBigPhoto
 *
 * @class       Ria_Photo_ShowBigPhoto
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_ShowBigPhoto = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'show_photo'
	},

	initialize: function(options){
             if(options.photoId!=0){
			var imgContainer = $('big_photo');
			var load=new Element('div',{id: 'load','styles': {
                                                                            'position'  : 'absolute',
                                                                            'float':'left',
                                                                            'top':'280px',
                                                                            'margin-left' 	:'280px'
                                                                          }
			})/*.set('opacity', 0.1)*/.inject(imgContainer);
			$('img').morph({
						opacity: 0.5
					});
    		var img = new Element('img', {'src': 'img/load.gif','styles':{
                                                                               'background':'none',
                                                                               'border':'none'
                                                                             }
    		});
                $('big_photo').setStyle('height','');
    		img.inject(load);
                this.setOptions(options);
                this.parent(options);
            //    $('scroll').empty().addClass('ajax-loading');
		}

  	},

	onGetResponse: function(jsonObj){
                   
                this.bigPhoto = jsonObj.photo;
                var littlePhotos = jsonObj.photos;
                var tpl = jsonObj.tpl;
                var vote = jsonObj.vote;
                this.comments = jsonObj.comments;
                this.rating =jsonObj.rating;
                var photoRating = "&nbsp;&nbsp;&nbsp; Рейтинг:&nbsp;"+this.rating;
                 var photos='';
                 var table = '';
                  
                 if (this.bigPhoto[0]['PhotosNewDBO']){
                     table = 'PhotosNewDBO';
                 } else{
                     table = 'PhotosTempDBO';
                 }
                    
                    this.addPhotoInfo(this.bigPhoto,table);
                    
                 littlePhotos.each(function(value, index){

                    if(value.photo_id==bigPhotoId){
                         photo_class = 'activeSmallPrew';
                    } else{
                        photo_class = 'smallPrew';
                    }
                  photos =photos+ "<div><a href='photos/"+littlePhotos[0]['photoReport_id']+"/photo/"+value.photo_id+"/' class='"+photo_class+"' id='photo_"+value.photo_id+"'> <img src='http://img.ria.ua/photos/"+value.src.replace('.','sw.')+"'"+'/> </a><div><div>'+value.photoNumber+'</div></div></div>';
                  lastPhotoID = value.photo_id;
                });
                
                  firstPhotoID = littlePhotos[0]['photo_id'];
             //      $('scroll').removeClass('ajax-loading');
                  $('scroll').set('html',photos);

                  
                var photo = 'http://img.ria.ua/photos/'+this.bigPhoto[0][table][0]['file'].replace('.','m.');
                $('img').set('src',photo);
//                $('img').addEvent('load',function(event){
//					var load = $('load');
//					if (load!=null)load.destroy();
//                                        var heightBigPhoto = document.getElementById('big_photo').clientHeight;
//                                            $('big_photo').setStyle('height',heightBigPhoto);
//					$('img').morph({
//						opacity: 1
//					});
//                });

                $('view-many').set('href','multi/photos/'+this.bigPhoto[0]['photoReport_id']+'/photo/'+this.bigPhoto[0][table][0]['photo_id']+'/0/#spinToPhoto');
                $('left-button-home').set('href',"begin/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/");
                $('right-button-end').set('href',"end/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/");
                $('left-button-5').set('href',"previous/"+littlePhotos[0]['photo_id']+"/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/");
                $('right-button-5').set('href',"next/"+littlePhotos[4]['photo_id']+"/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/");
                $('add_comment_block').set('value',this.bigPhoto[0][table][0]['photo_id']);
                if(table=='PhotosNewDBO'){
                    $('photo_rating').set('html',photoRating);
                    $('photo_rating').setStyle('display','block');
                }else{
                   $('photo_rating').set('html','&nbsp;');
                }
                bigPhotoId = this.bigPhoto[0][table][0]['photo_id'];

                if (littlePhotos[0]['photoNumber']==1){
                     $('left-button').setAttribute('class','first-notactive');
                     $('left-button-home').setAttribute('class','notactive');
                      $('left-button-home').set('html',"<b >В начало</b>");
                     $('left-button-5').setAttribute('class','notactive');
                     $('left-button-5').set('html', "<b>Предыдущие 5</b>");

                  } else {
                      $('left-button').setAttribute('class','first');
                      $('left-button-home').set('html',"<a  href='begin/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' id='toBegin_href'><b>В начало</b></a>");
                       $('left-button-home').removeProperty('class');
                       $('left-button-5').set('html', "<a href='previous/"+littlePhotos[0]['photo_id']+"/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/'><b id='PrevFive_href'>Предыдущие 5</b></a>");
                       $('left-button-5').removeProperty('class');
                  }
                  if (littlePhotos[4]['photoNumber']==littlePhotos[4]['countPhotosInReport']){
                     $('right-button').setAttribute('class','next-notactive');
                     $('right-button-end').setAttribute('class','notactive');
                     $('right-button-end').set('html',"<b>В конец</b>");
                     $('right-button-5').setAttribute('class','notactive');
                     $('right-button-5').set('html',"<b>Следующие 5</b>");
                  } else {
                      $('right-button').setAttribute('class','next');
                      $('right-button-end').set('html',"<a href='end/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' ><b id='toEnd_href'>В конец</b></a>");
                      $('right-button-end').removeProperty('class');
                      $('right-button-5').set('html',"<a href='next/"+littlePhotos[4]['photo_id']+"/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' ><b id='NextFive_href'>Следующие 5</b></a>");
                      $('right-button-5').removeProperty('class');
                  }



                 littlePhotos.each(function(value, index){
                            if(value.photo_id==bigPhotoId){
                               $('photo_'+value.photo_id).setAttribute('class','activeSmallPrew');
                            } else {
                               $('photo_'+value.photo_id).setAttribute('class','smallPrew');
                            }
                        });
                if(table=='PhotosNewDBO'){
                 if (vote=='0'){
                    var voteText=  "<a href='vote/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' class='golLink' id='addVoice_"+this.bigPhoto[0][table][0]['photo_id']+"'>Проголосовать за фото (+1)</a>";
                    $('golos').set('html', voteText);
                     $('golos').setStyle('display', 'block');

                } else {

                      var voteText= "<span class='golSpan' id='voted' style='display:block'>Cпасибо, Ваш голос учтен!</span>";
                      $('golos').set('html', voteText);
                      $('golos').setStyle('display', 'block');
                }
                $('photo_rating').setStyle('display','block');

                  $$('.golLink').addEvent('click', function(e) {

                        var reg = /\D*/;
                        var photoId = this.getAttribute('id').replace(reg, "");
                      new Ria_Vote_VoteForPhoto({'photoId':photoId});

                    return false;
                });
                }else{
                     $('golos').set('html', '');
                     $('photo_rating').setStyle('display','none');
                }
                $$('.smallPrew').addEvent('click', function(e) {
                    var reg = /\D*/;
                     scroll.toElement('BigPhotoToScroll');
                  var photoId = this.getAttribute('id').replace(reg, "");
                  new Ria_Photo_ShowBigPhoto({'photoId':photoId,'photoReportID':littlePhotos[0]['photoReport_id']});

                    return false;
                });
                if($('toBegin_href')){
                    $('toBegin_href').addEvent('click', function() {
                        new Ria_Photo_PhotosToBegin({'photoReport':littlePhotos[0]['photoReport_id']});
                        return false;
                    });
                }
                if($('PrevFive_href')){
                    $('PrevFive_href').addEvent('click', function() {
                        new  Ria_Photo_GetPrevFivePhotos({'photoId':littlePhotos[0]['photo_id']});

                        return false;
                    });
                }
                if($('NextFive_href')){
                    $('NextFive_href').addEvent('click', function() {
                        new  Ria_Photo_GetNextFivePhotos({'photoId':littlePhotos[4]['photo_id']});
                        return false;
                    });
                }
                if($('toEnd_href')){
                    $('toEnd_href').addEvent('click', function() {
                        new  Ria_Photo_PhotosToEnd({'photoReport':littlePhotos[0]['photoReport_id']});
                        return false;
                    });
                }
                
            
              var i=0;
              var newPhotosIdArray=[];
               littlePhotos.each(function(value, index){
                   newPhotosIdArray[i]= value.photo_id;
                   i++;
               });
                littlePhotosIdArray =  newPhotosIdArray;
                mainPhoto = this.bigPhoto[0][table][0]['photo_id'];
                  // this.addComments(this.comments,this.bigPhoto,table,tpl);
                  this.addComments(tpl,table,this.bigPhoto,this.comments);

        },
        addPhotoInfo: function (bigPhoto, table){
            
            $('orig_img').set('html',"<a href='http://img.ria.ua/photos/"+bigPhoto[0][table][0]['file'].replace('.','orig.')+"'><b>Загрузить оригинал фото</b></a>");
            $('event_name').set('html',bigPhoto[0]['name']);
            $('event_desc').set('html',bigPhoto[0]['description']);
            $('event_date').set('html',bigPhoto[0]['date']['day']+bigPhoto[0]['date']['month_sklon']+bigPhoto[0]['date']['year']);
            
      //      $('event_city').set('html',bigPhoto[0]['ClubDBO']['CitiesDBO']['name']);
     //       $('event_place').set('html',bigPhoto[0]['ClubDBO']['name']);
     //       $('event_author').set('html',"<a href='photographer_"+bigPhoto[0]['PersonDBO']['person_id']+"'>"+bigPhoto[0]['PersonDBO']['name']+"</a>");
            if (table=='PhotosNewDBO'){
                $('count_view').set('html',bigPhoto[0][table][0]['count_view']);
            }
          //   alert(bigPhoto[0][table][0]['count_view']);
            $('photo_href').set('html',"<input type='text' style='width:100%' value='http://weekend.com.ua/photos/"+bigPhoto[0]['photoReport_id']+"/photo/"+bigPhoto[0][table][0]['photo_id']+"/'>");
           

    },
    addComments:function (tpl,table,bigPhoto,comments){

    $('comments_to_photo').innerHTML =tpl;
  

        if (comments['toCurrentAlbum'].length>0){

             comments['toCurrentAlbum'].each(function(value, index){            
                 if(value['object_id']==bigPhoto[0][table][0]['photo_id']){
                     $('com_'+value['comment_id']).setStyle('display','none');
                 } else {
                      $('com_'+value['comment_id']).setStyle('display','block');
                 }
            });
        }else{
             $('comments_to_album').set('html', '');
        }

        $$('.handUp').addEvent('click', function(e) {
            var reg = /\D*/;
            var commentId = this.getAttribute('id').replace(reg, "");
            new Ria_Vote_VoteManager({'commentId':commentId,'event':'vote_commentPositive'});

            return false;
        });

        $$('.handDown').addEvent('click', function(e) {
            var reg = /\D*/;
            var commentId = this.getAttribute('id').replace(reg, "");
            new Ria_Vote_VoteManager({'commentId':commentId,'event':'vote_commentNegative'});
            return false;
        });

        $$('.textInputEmail').addEvent('blur',function(e){          
           var reg = /\D*/;
           var commentId = this.getAttribute('id').replace(reg, "");
           var userMail = $('answer_mail_'+commentId).get('value');
           if (userMail.test('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$')){
            new Ria_Login_CheckUserEmail({'user_email':userMail,'commentId':commentId});
           } else {
              $('answer_user_'+commentId).set('html','Пожалуйста введите правильный E-mail адрес.<br/>Например: имя@domain.ru' );
              $('answer_user_'+commentId).setAttribute('class','error');
              $('answer_user_'+commentId).setAttribute('style','display:block');
              $('input_psw_'+commentId).setAttribute('style','display:none');
           }
          return false;
        });

        $$('.textInputPsw').addEvent('blur',function(e){
           var reg = /\D*/;
           var commentId = this.getAttribute('id').replace(reg, "");
           var userMail = $('answer_mail_'+commentId).get('value');
           if (userMail.test('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$')){
               var userPasw = $('user_pasw_'+commentId).get('value');
               new Ria_Login_CheckUserPassword({'user_email':userMail,'user_pasw':userPasw,'commentId':commentId});
            } else {
              $('answer_user_'+commentId).set('html','Пожалуйста введите правильный E-mail адрес.<br/>Например: имя@domain.ru' );
              $('answer_user_'+commentId).setAttribute('class','error');
              $('answer_user_'+commentId).setAttribute('style','display:block');
              $('input_psw_'+commentId).setAttribute('style','display:none');
           }
           return false;
         });       

    }

});


/**
 * Ria_Photo_PhotosToBegin
 *
 * @class       Ria_Photo_PhotosToBegin
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_PhotosToBegin = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'to_begin'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);
                $('scroll').empty().addClass('ajax-loading');
      	},

	onGetResponse: function(jsonObj){
                var littlePhotos = jsonObj.photos;
                var photo='';
                var photo_class;
               littlePhotoArray = littlePhotos;
                littlePhotos.each(function(value, index){

                    if(value.photo_id==bigPhotoId){
                         photo_class = 'activeSmallPrew';
                    } else{
                        photo_class = 'smallPrew';
                    }
                  photo =photo+ "<div><a href='photos/"+littlePhotos[0]['photoReport_id']+"/photo/"+value.photo_id+"/' class='"+photo_class+"' id='photo_"+value.photo_id+"'> <img src='http://img.ria.ua/photos/"+value.src.replace('.','sw.')+"'"+'/> </a><div><div>'+value.photoNumber+'</div></div></div>';
                  lastPhotoID = value.photo_id;
                })
                  firstPhotoID = littlePhotos[0]['photo_id'];
          $('scroll').removeClass('ajax-loading');
          $('scroll').set('html',photo);

             $$('.smallPrew').addEvent('click', function(e) {
                var reg = /\D*/;
                scroll.toElement('BigPhotoToScroll');
              var photoId = this.getAttribute('id').replace(reg, "");
              new Ria_Photo_ShowBigPhoto({'photoId':photoId,'photoReportID':littlePhotos[0]['photoReport_id']});

                return false;
            });

          if (littlePhotos[0]['photoNumber']==1){
                     $('left-button').setAttribute('class','first-notactive');
                     $('left-button-home').setAttribute('class','notactive');
                      $('left-button-home').set('html',"<b>В начало</b>");
                     $('left-button-5').setAttribute('class','notactive');
                     $('left-button-5').set('html', "<b>Предыдущие 5</b>");

                  } else {
                      $('left-button').setAttribute('class','first');
                      $('left-button-home').set('html',"<a  href='begin/photo/"+bigPhotoId+"/' id='toBegin_href'><b>В начало</b></a>");
                       $('left-button-home').removeProperty('class');
                       $('left-button-5').set('html', "<a href='previous/"+littlePhotos[0]['photo_id']+"/photo/"+this.bigPhoto[0]['PhotosNewDBO'][0]['photo_id']+"/'><b id='PrevFive_href'>Предыдущие 5</b></a>");
                       $('left-button-5').removeProperty('class');
                  }
                  if (littlePhotos[4]['photoNumber']==littlePhotos[4]['countPhotosInReport']){
                     $('right-button').setAttribute('class','next-notactive');
                     $('right-button-end').setAttribute('class','notactive');
                     $('right-button-end').set('html',"<b>В конец</b>");
                     $('right-button-5').setAttribute('class','notactive');
                     $('right-button-5').set('html',"<b>Следующие 5</b>");
                  } else {
                      $('right-button').setAttribute('class','next');
                      $('right-button-end').set('html',"<a href='end/photo/"+bigPhotoId+"/'><b id='toEnd_href'>В конец</b></a>");
                      $('right-button-end').removeProperty('class');
                      $('right-button-5').set('html',"<a href='next/"+littlePhotos[4]['photo_id']+"/photo/"+bigPhotoId+"/' ><b id='NextFive_href'>Следующие 5</b></a>");
                      $('right-button-5').removeProperty('class');
                  }

                  if($('toEnd_href')){
                      $('toEnd_href').addEvent('click', function() {
                        new  Ria_Photo_PhotosToEnd({'photoReport':littlePhotos[0]['photoReport_id']});
                        return false;
                     });
                  }
                 if($('NextFive_href')){
                    $('NextFive_href').addEvent('click', function() {
                        new  Ria_Photo_GetNextFivePhotos({'photoId':littlePhotos[4]['photo_id']});
                        return false;
                    });
                }
                if($('PrevFive_href')){
                  $('PrevFive_href').addEvent('click', function() {
                    new  Ria_Photo_GetPrevFivePhotos({'photoId':littlePhotos[0]['photo_id']});

                    return false;
                });
                }
                
    
        }


});


/**
 * Ria_Photo_GetPrevFivePhotos
 *
 * @class       Ria_Photo_GetPrevFivePhotos
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_GetPrevFivePhotos = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'prev_five'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);
                $('scroll').empty().addClass('ajax-loading');
      	},

	onGetResponse: function(jsonObj){
                var littlePhotos = jsonObj.photos;
                var photo='';
                var photo_class;
               littlePhotoArray = littlePhotos;
                littlePhotos.each(function(value, index){

                    if(value.photo_id==bigPhotoId){
                         photo_class = 'activeSmallPrew';
                    } else{
                        photo_class = 'smallPrew';
                    }
                  photo =photo+ "<div><a href='photos/"+littlePhotos[0]['photoReport_id']+"/photo/"+value.photo_id+"/' class='"+photo_class+"' id='photo_"+value.photo_id+"'> <img src='http://img.ria.ua/photos/"+value.src.replace('.','sw.')+"'"+'/> </a><div><div>'+value.photoNumber+'</div></div></div>';
                  lastPhotoID = value.photo_id;
                })
                  firstPhotoID = littlePhotos[0]['photo_id'];
          $('scroll').removeClass('ajax-loading');
          $('scroll').set('html',photo);

             $$('.smallPrew').addEvent('click', function(e) {
                var reg = /\D*/;
                scroll.toElement('BigPhotoToScroll');
              var photoId = this.getAttribute('id').replace(reg, "");
              new Ria_Photo_ShowBigPhoto({'photoId':photoId,'photoReportID':littlePhotos[0]['photoReport_id']});

                return false;
            });
            

          if (littlePhotos[0]['photoNumber']==1){
                     $('left-button').setAttribute('class','first-notactive');
                     $('left-button-home').setAttribute('class','notactive');
                      $('left-button-home').set('html',"<b>В начало</b>");
                     $('left-button-5').setAttribute('class','notactive');
                     $('left-button-5').set('html', "<b>Предыдущие 5</b>");

                  } else {
                      $('left-button').setAttribute('class','first');
                      $('left-button-home').set('html',"<a  href='begin/photo/"+bigPhotoId+"/' id='toBegin_href'><b>В начало</b></a>");
                       $('left-button-home').removeProperty('class');
                       $('left-button-5').set('html', "<a href='previous/"+littlePhotos[0]['photo_id']+"/photo/"+bigPhotoId+"/'><b id='PrevFive_href'>Предыдущие 5</b></a>");
                       $('left-button-5').removeProperty('class');
                  }
                  if (littlePhotos[4]['photoNumber']==littlePhotos[4]['countPhotosInReport']){
                     $('right-button').setAttribute('class','next-notactive');
                     $('right-button-end').setAttribute('class','notactive');
                     $('right-button-end').set('html',"<b>В конец</b>");
                     $('right-button-5').setAttribute('class','notactive');
                     $('right-button-5').set('html',"<b>Следующие 5</b>");
                  } else {
                      $('right-button').setAttribute('class','next');
                      $('right-button-end').set('html',"<a href='end/photo/"+bigPhotoId+"/' ><b id='toEnd_href'>В конец</b></a>");
                      $('right-button-end').removeProperty('class');
                      $('right-button-5').set('html',"<a href='next/"+littlePhotos[4]['photo_id']+"/photo/"+bigPhotoId+"/' ><b id='NextFive_href'>Следующие 5</b></a>");
                      $('right-button-5').removeProperty('class');
                  }
                   if($('toBegin_href')){
                       $('toBegin_href').addEvent('click', function() {
                            new Ria_Photo_PhotosToBegin({'photoReport':littlePhotos[0]['photoReport_id']});
                            return false;
                        });
                   }
                   if($('PrevFive_href')){
                      $('PrevFive_href').addEvent('click', function() {
                            new  Ria_Photo_GetPrevFivePhotos({'photoId':littlePhotos[0]['photo_id']});
                            return false;
                        });
                   }
                if($('NextFive_href')){
                    $('NextFive_href').addEvent('click', function() {
                        new  Ria_Photo_GetNextFivePhotos({'photoId':littlePhotos[4]['photo_id']});
                        return false;
                    });
                }
                if($('toEnd_href')){
                    $('toEnd_href').addEvent('click', function() {
                        new  Ria_Photo_PhotosToEnd({'photoReport':littlePhotos[0]['photoReport_id']});
                        return false;
                    });
                }

        }



});


/**
 * Ria_Photo_PhotosToEnd
 *
 * @class       Ria_Photo_PhotosToEnd
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_PhotosToEnd = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'to_end'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);
                $('scroll').empty().addClass('ajax-loading');
      	},

	onGetResponse: function(jsonObj){
                var littlePhotos = jsonObj.photos;
                var photo='';
                var photo_class;
               littlePhotoArray = littlePhotos;
                littlePhotos.each(function(value, index){

                    if(value.photo_id==bigPhotoId){
                         photo_class = 'activeSmallPrew';
                    } else{
                        photo_class = 'smallPrew';
                    }
                  photo =photo+ "<div><a href='photos/"+littlePhotos[0]['photoReport_id']+"/photo/"+value.photo_id+"/' class='"+photo_class+"' id='photo_"+value.photo_id+"'> <img src='http://img.ria.ua/photos/"+value.src.replace('.','sw.')+"'"+'/> </a><div><div>'+value.photoNumber+'</div></div></div>';
                  lastPhotoID = value.photo_id;
                })
                  firstPhotoID = littlePhotos[0]['photo_id'];
           $('scroll').removeClass('ajax-loading');
          $('scroll').set('html',photo);

             $$('.smallPrew').addEvent('click', function(e) {
                var reg = /\D*/;
                scroll.toElement('BigPhotoToScroll');
              var photoId = this.getAttribute('id').replace(reg, "");
              new Ria_Photo_ShowBigPhoto({'photoId':photoId,'photoReportID':littlePhotos[0]['photoReport_id']});

                return false;
            });

          if (littlePhotos[0]['photoNumber']==1){
                     $('left-button').setAttribute('class','first-notactive');
                     $('left-button-home').setAttribute('class','notactive');
                      $('left-button-home').set('html',"<b>В начало</b>");
                     $('left-button-5').setAttribute('class','notactive');
                     $('left-button-5').set('html', "<b>Предыдущие 5</b>");

                  } else {
                      $('left-button').setAttribute('class','first');
                      $('left-button-home').set('html',"<a  href='begin/photo/"+bigPhotoId+"/' id='toBegin_href'><b>В начало</b></a>");
                       $('left-button-home').removeProperty('class');
                       $('left-button-5').set('html', "<a href='previous/"+littlePhotos[0]['photo_id']+"/photo/"+bigPhotoId+"/'><b id='PrevFive_href'>Предыдущие 5</b></a>");
                       $('left-button-5').removeProperty('class');
                  }
                  if (littlePhotos[4]['photoNumber']==littlePhotos[4]['countPhotosInReport']){
                     $('right-button').setAttribute('class','next-notactive');
                     $('right-button-end').setAttribute('class','notactive');
                     $('right-button-end').set('html',"<b>В конец</b>");
                     $('right-button-5').setAttribute('class','notactive');
                     $('right-button-5').set('html',"<b>Следующие 5</b>");
                  } else {
                      $('right-button').setAttribute('class','next');
                      $('right-button-end').set('html',"<a href='end/photo/"+bigPhotoId+"/' ><b id='toEnd_href'>В конец</b></a>");
                      $('right-button-end').removeProperty('class');
                      $('right-button-5').set('html',"<a href='next/"+littlePhotos[4]['photo_id']+"/photo/"+bigPhotoId+"/' ><b id='NextFive_href'>Следующие 5</b></a>");
                      $('right-button-5').removeProperty('class');
                  }
                  if($('toBegin_href')){
                      $('toBegin_href').addEvent('click', function() {
                        new Ria_Photo_PhotosToBegin({'photoReport':littlePhotos[0]['photoReport_id']});
                        return false;
                     });
                  }
                 if($('PrevFive_href')){
                      $('PrevFive_href').addEvent('click', function() {
                        new  Ria_Photo_GetPrevFivePhotos({'photoId':littlePhotos[0]['photo_id']});
                        return false;
                    });
                 }

        }


});





/**
 * Ria_Photo_GetNextFivePhotos
 *
 * @class       Ria_Photo_GetNextFivePhotos
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_GetNextFivePhotos = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'next_five'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);
                $('scroll').empty().addClass('ajax-loading');
      	},

	onGetResponse: function(jsonObj){
             
                var littlePhotos = jsonObj.photos;
                var photo='';
                var photo_class;
               littlePhotoArray = littlePhotos;
                littlePhotos.each(function(value, index){

                    if(value.photo_id==bigPhotoId){
                         photo_class = 'activeSmallPrew';
                    } else{
                        photo_class = 'smallPrew';
                    }
                  photo =photo+ "<div><a href='photos/"+littlePhotos[0]['photoReport_id']+"/photo/"+value.photo_id+"/' class='"+photo_class+"' id='photo_"+value.photo_id+"'> <img src='http://img.ria.ua/photos/"+value.src.replace('.','sw.')+"'"+'/> </a><div><div>'+value.photoNumber+'</div></div></div>';
                  lastPhotoID = value.photo_id;
                })
                  firstPhotoID = littlePhotos[0]['photo_id'];
          $('scroll').removeClass('ajax-loading');
          $('scroll').set('html',photo);
           
             $$('.smallPrew').addEvent('click', function(e) {
                var reg = /\D*/;
                scroll.toElement('BigPhotoToScroll');
              var photoId = this.getAttribute('id').replace(reg, "");
              new Ria_Photo_ShowBigPhoto({'photoId':photoId,'photoReportID':littlePhotos[0]['photoReport_id']});

                return false;
            });


          if (littlePhotos[0]['photoNumber']==1){
                     $('left-button').setAttribute('class','first-notactive');
                     $('left-button-home').setAttribute('class','notactive');
                      $('left-button-home').set('html',"<b>В начало</b>");
                     $('left-button-5').setAttribute('class','notactive');
                     $('left-button-5').set('html', "<b>Предыдущие 5</b>");

                  } else {
                      $('left-button').setAttribute('class','first');
                      $('left-button-home').set('html',"<a  href='begin/photo/"+bigPhotoId+"/' id='toBegin_href'><b>В начало</b></a>");
                       $('left-button-home').removeProperty('class');
                       $('left-button-5').set('html', "<a href='previous/"+littlePhotos[0]['photo_id']+"/photo/"+bigPhotoId+"/'><b id='PrevFive_href'>Предыдущие 5</b></a>");
                       $('left-button-5').removeProperty('class');
                  }
                  if (littlePhotos[4]['photoNumber']==littlePhotos[4]['countPhotosInReport']){
                     $('right-button').setAttribute('class','next-notactive');
                     $('right-button-end').setAttribute('class','notactive');
                     $('right-button-end').set('html',"<b>В конец</b>");
                     $('right-button-5').setAttribute('class','notactive');
                     $('right-button-5').set('html',"<b>Следующие 5</b>");
                  } else {
                      $('right-button').setAttribute('class','next');
                      $('right-button-end').set('html',"<a href='end/photo/"+bigPhotoId+"/' ><b id='toEnd_href'>В конец</b></a>");
                      $('right-button-end').removeProperty('class');
                      $('right-button-5').set('html',"<a href='next/"+littlePhotos[4]['photo_id']+"/photo/"+bigPhotoId+"/' ><b id='NextFive_href'>Следующие 5</b></a>");
                      $('right-button-5').removeProperty('class');
                  }
                   if($('toBegin_href')){
                       $('toBegin_href').addEvent('click', function() {
                        new Ria_Photo_PhotosToBegin({'photoReport':littlePhotos[0]['photoReport_id']});
                        return false;
                     });
                   }
                 if($('PrevFive_href')){
                      $('PrevFive_href').addEvent('click', function() {
                        new  Ria_Photo_GetPrevFivePhotos({'photoId':littlePhotos[0]['photo_id']});
                        return false;
                     });
                 }
                 if($('NextFive_href')){
                    $('NextFive_href').addEvent('click', function() {
                        new  Ria_Photo_GetNextFivePhotos({'photoId':littlePhotos[4]['photo_id']});
                        return false;
                    });
                 }
                 if($('toEnd_href')){
                    $('toEnd_href').addEvent('click', function() {
                        new  Ria_Photo_PhotosToEnd({'photoReport':littlePhotos[0]['photoReport_id']});
                        return false;
                    });
                 }

        }



});


/**
 * Ria_Photo_ShowBigMultiPhoto
 *
 * @class       Ria_Photo_ShowBigMultiPhoto
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_ShowBigMultiPhoto = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'show_multi_photo'
	},

	initialize: function(options){
             if(options.photoId!=0){
			var imgContainer = $('big_photo');
			var load=new Element('div',{id: 'load','styles': {
                                                                            'position'  : 'absolute',
                                                                            'float':'left',
                                                                            'top':'280px',
                                                                            'margin-left' 	:'280px'
                                                                          }
			})/*.set('opacity', 0.1)*/.inject(imgContainer);
			$('img').morph({
						opacity: 0.5
					});
    		var img = new Element('img', {'src': 'img/load.gif','styles':{
                                                                               'background':'none',
                                                                               'border':'none'
                                                                             }
    		});
                $('big_photo').setStyle('height','');
    		img.inject(load);
                this.setOptions(options);
                this.parent(options);

		}
            //     this.setOptions(options);
           //     this.parent(options);

  	},

	onGetResponse: function(jsonObj){
                this.bigPhoto = jsonObj.photo;
                var vote = jsonObj.vote;
                this.comments = jsonObj.comments;
                var tpl = jsonObj.tpl;
                this.rating =jsonObj.rating;
                var photoRating = "&nbsp;&nbsp;&nbsp; Рейтинг:&nbsp;"+this.rating;
                var photos='';
                var table ='';
                 if (this.bigPhoto[0]['PhotosNewDBO']){
                     table = 'PhotosNewDBO';
                 } else{
                     table = 'PhotosTempDBO';
                 }
            
                   this.addPhotoInfo(this.bigPhoto,table);
            

                var new_photoId = "photo/"+this.bigPhoto[0][table][0]['photo_id'];
                var photo = 'http://img.ria.ua/photos/'+this.bigPhoto[0][table][0]['file'].replace('.','m.');
                $('img').set('src',photo);
//                $('img').addEvent('load',function(event){
//					var load = $('load');
//					if (load!=null)load.destroy();
//                                        var heightBigPhoto = document.getElementById('big_photo').clientHeight;
//                                            $('big_photo').setStyle('height',heightBigPhoto);
//					$('img').morph({
//						opacity: 1
//					});
//                });
                 $('add_comment_block').set('value',this.bigPhoto[0][table][0]['photo_id']);
                 if(table=='PhotosNewDBO'){
                    $('photo_rating').set('html',photoRating);
                    $('photo_rating').setStyle('display','block');
                 }else{
                    $('photo_rating').set('html','&nbsp;');
                 }



                    var hrefsPrevNext = $$('.page').getChildren();
                    
                    if (hrefsPrevNext.contains(hrefsPrevNext[0])){
                            hrefsPrevNext[0].each(function(el){
                               if(el.tagName=='A'){
                                      var reg = /photo\/[0-9]*/;
                                      var new_href = el.getProperty('href').replace(reg, new_photoId);
                                      el.set('href',new_href);
                               }
                          });

                      var hrefs = $$('.numbers').getChildren();

                         hrefs[0].each(function(el){
                               if(el.tagName=='A'){
                                      var reg = /photo\/[0-9]*/;
                                      var new_href = el.getProperty('href').replace(reg, new_photoId);
                                      el.set('href',new_href);
                               }
                         });
                    }

      //          bigPhotoId = this.bigPhoto[0][table][0]['photo_id'];
                  
                if($('photo_'+this.bigPhoto[0][table][0]['photo_id'])){
                    $('photo_'+this.bigPhoto[0][table][0]['photo_id']).removeProperty('class');
                    $('photo_'+this.bigPhoto[0][table][0]['photo_id']).setAttribute('class','multiPhotoItem activeMulti');
           
            }

               if ($('photo_'+selectedImgId)){
                   $('photo_'+selectedImgId).removeProperty('class');
                   $('photo_'+selectedImgId).setAttribute('class','multiPhotoItem');
               }
               
               selectedImgId = this.bigPhoto[0][table][0]['photo_id'];
                               
              if(table!='PhotosTempDBO'){
                 if (vote=='0'){
                    var voteText=  "<a href='vote/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' class='golLink' id='addVoice_"+this.bigPhoto[0][table][0]['photo_id']+"'>Проголосовать за фото (+1)</a>";
                  $('golos').set('html', voteText);
                  $('golos').setStyle('display', 'block');
                } else {

                      var voteText= "<span class='golSpan' id='voted' style='display:block'>Cпасибо, Ваш голос учтен!</span>";
                      $('golos').set('html', voteText);
                      $('golos').setStyle('display', 'block');


                }
                  $$('.golLink').addEvent('click', function(e) {

                        var reg = /\D*/;
                        var photoId = this.getAttribute('id').replace(reg, "");
                      new Ria_Vote_VoteForPhoto({'photoId':photoId});

                    return false;
                });
              }else {
                   $('golos').set('html', '');
                   $('photo_rating').setStyle('display','none');
              }
              //   mainPhoto = this.bigPhoto[0][table][0]['photo_id'];
                 this.addComments(this.comments,this.bigPhoto,table,tpl);
    
        },
        addPhotoInfo: function (bigPhoto,table){

            $('orig_img').set('html',"<a href='http://img.ria.ua/photos/"+bigPhoto[0][table][0]['file'].replace('.','orig.')+"'><b>Загрузить оригинал фото</b></a>");
            $('event_name').set('html',bigPhoto[0]['name']);
            $('event_desc').set('html',bigPhoto[0]['description']);
            $('event_date').set('html',bigPhoto[0]['date']['day']+bigPhoto[0]['date']['month_sklon']+bigPhoto[0]['date']['year']);
      //      $('event_city').set('html',bigPhoto[0]['ClubDBO']['CitiesDBO']['name']);
     //       $('event_place').set('html',bigPhoto[0]['ClubDBO']['name']);
     //       $('event_author').set('html',"<a href='photographer_"+bigPhoto[0]['PersonDBO']['person_id']+"'>"+bigPhoto[0]['PersonDBO']['name']+"</a>");
            if (table=='PhotosNewDBO'){
                $('count_view').set('html',bigPhoto[0][table][0]['count_view']);
            }
           $('photo_href').set('html',"<input type='text' style='width:100%' value='http://weekend.com.ua/photos/"+bigPhoto[0]['photoReport_id']+"/photo/"+bigPhoto[0][table][0]['photo_id']+"/'>");


    },
    addComments:function (comments,bigPhoto,table,tpl){

        $('comments_to_photo').innerHTML =tpl;
        if (comments['toCurrentAlbum'].length>0){

             comments['toCurrentAlbum'].each(function(value, index){
                 if(value['object_id']==bigPhoto[0][table][0]['photo_id']){
                     $('com_'+value['comment_id']).setStyle('display','none');
                 } else {
                      $('com_'+value['comment_id']).setStyle('display','block');
                 }
            });
        }else{
             $('comments_to_album').set('html', '');
        }


        $$('.handUp').addEvent('click', function(e) {
            var reg = /\D*/;
            var commentId = this.getAttribute('id').replace(reg, "");
            new Ria_Vote_VoteManager({'commentId':commentId,'event':'vote_commentPositive'});

            return false;
        });

        $$('.handDown').addEvent('click', function(e) {
            var reg = /\D*/;
            var commentId = this.getAttribute('id').replace(reg, "");
            new Ria_Vote_VoteManager({'commentId':commentId,'event':'vote_commentNegative'});
            return false;
        });
        $$('.textInputEmail').addEvent('blur',function(e){
           var reg = /\D*/;
           var commentId = this.getAttribute('id').replace(reg, "");
           var userMail = $('answer_mail_'+commentId).get('value');
           if (userMail.test('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$')){
            new Ria_Login_CheckUserEmail({'user_email':userMail,'commentId':commentId});
           } else {
              $('answer_user_'+commentId).set('html','Пожалуйста введите правильный E-mail адрес.<br/>Например: имя@domain.ru' );
              $('answer_user_'+commentId).setAttribute('class','error');
              $('answer_user_'+commentId).setAttribute('style','display:block');
              $('input_psw_'+commentId).setAttribute('style','display:none');
           }
          return false;
        });

        $$('.textInputPsw').addEvent('blur',function(e){
           var reg = /\D*/;
           var commentId = this.getAttribute('id').replace(reg, "");
           var userMail = $('answer_mail_'+commentId).get('value');
           if (userMail.test('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$')){
               var userPasw = $('user_pasw_'+commentId).get('value');
               new Ria_Login_CheckUserPassword({'user_email':userMail,'user_pasw':userPasw,'commentId':commentId});
            } else {
              $('answer_user_'+commentId).set('html','Пожалуйста введите правильный E-mail адрес.<br/>Например: имя@domain.ru' );
              $('answer_user_'+commentId).setAttribute('class','error');
              $('answer_user_'+commentId).setAttribute('style','display:block');
              $('input_psw_'+commentId).setAttribute('style','display:none');
           }
           return false;
         });
    }

});


/**
 * Ria_Photo_GetNextBigPhoto
 *
 * @class       Ria_Photo_GetNextBigPhoto
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_GetNextBigPhoto = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'get_next_photo'
	},

	initialize: function(options){
             if(options.photoId!=0){
			var imgContainer = $('big_photo');
			var load=new Element('div',{id: 'load','styles': {
                                                                            'position'  : 'absolute',
                                                                            'float':'left',
                                                                            'top':'280px',
                                                                            'margin-left' 	:'280px'
                                                                          }
			})/*.set('opacity', 0.1)*/.inject(imgContainer);
			$('img').morph({
						opacity: 0.5
					});
    		var img = new Element('img', {'src': 'img/load.gif','styles':{
                                                                               'background':'none',
                                                                               'border':'none'
                                                                             }
    		});
                $('big_photo').setStyle('height','');
    		img.inject(load);
                this.setOptions(options);
                this.parent(options);
            //    $('scroll').empty().addClass('ajax-loading');
		}

  	},

	onGetResponse: function(jsonObj){
           
                this.bigPhoto = jsonObj.photo;
                var littlePhotos = jsonObj.photos;
                var vote = jsonObj.vote;
                var tpl =jsonObj.tpl;
                this.comments = jsonObj.comments;
                this.rating =jsonObj.rating;
                var photoRating = "&nbsp;&nbsp;&nbsp; Рейтинг:&nbsp;"+this.rating;
                 var photos='';
                 var table = '';
                  if (this.bigPhoto[0]['PhotosNewDBO']){
                     table = 'PhotosNewDBO';
                 } else{
                     table = 'PhotosTempDBO';
                 }

                    this.addPhotoInfo(this.bigPhoto,table);
   
                 littlePhotos.each(function(value, index){

                    if(value.photo_id==bigPhotoId){
                         photo_class = 'activeSmallPrew';
                    } else{
                        photo_class = 'smallPrew';
                    }
                  photos =photos+ "<div><a href='photos/"+littlePhotos[0]['photoReport_id']+"/photo/"+value.photo_id+"/' class='"+photo_class+"' id='photo_"+value.photo_id+"'> <img src='http://img.ria.ua/photos/"+value.src.replace('.','sw.')+"'"+'/> </a><div><div>'+value.photoNumber+'</div></div></div>';
                  lastPhotoID = value.photo_id;
                })
                  firstPhotoID = littlePhotos[0]['photo_id'];
             //      $('scroll').removeClass('ajax-loading');
                  $('scroll').set('html',photos);
                  
                  
                var photo = 'http://img.ria.ua/photos/'+this.bigPhoto[0][table][0]['file'].replace('.','m.');
                $('img').set('src',photo);
//                $('img').addEvent('load',function(event){
//					var load = $('load');
//					if (load!=null)load.destroy();
//                                         var heightBigPhoto = document.getElementById('big_photo').clientHeight;
//                                            $('big_photo').setStyle('height',heightBigPhoto);
//					$('img').morph({
//						opacity: 1
//					});
//                });
                $('view-many').set('href','multi/photos/'+this.bigPhoto[0]['photoReport_id']+'/photo/'+this.bigPhoto[0][table][0]['photo_id']+'/0/#spinToPhoto');
                $('left-button-home').set('href',"begin/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/");
                $('right-button-end').set('href',"end/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/");
                $('left-button-5').set('href',"previous/"+littlePhotos[0]['photo_id']+"/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/");
                $('right-button-5').set('href',"next/"+littlePhotos[4]['photo_id']+"/photo_"+this.bigPhoto[0][table][0]['photo_id']+"/");
                $('add_comment_block').set('value',this.bigPhoto[0][table][0]['photo_id']);
                  if(table == 'PhotosNewDBO'){
                        $('photo_rating').set('html',photoRating);
                        $('photo_rating').setStyle('display','block');
                  }else{
                      $('photo_rating').set('html','&nbsp;');
                  }

                bigPhotoId = this.bigPhoto[0][table][0]['photo_id'];
               
                if (littlePhotos[0]['photoNumber']==1){
                     $('left-button').setAttribute('class','first-notactive');
                     $('left-button-home').setAttribute('class','notactive');
                      $('left-button-home').set('html',"<b >В начало</b>");
                     $('left-button-5').setAttribute('class','notactive');
                     $('left-button-5').set('html', "<b>Предыдущие 5</b>");

                  } else {
                      $('left-button').setAttribute('class','first');
                      $('left-button-home').set('html',"<a  href='begin/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' id='toBegin_href'><b>В начало</b></a>");
                       $('left-button-home').removeProperty('class');
                       $('left-button-5').set('html', "<a href='previous/"+littlePhotos[0]['photo_id']+"/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/'><b id='PrevFive_href'>Предыдущие 5</b></a>");
                       $('left-button-5').removeProperty('class');
                  }
                  if (littlePhotos[4]['photoNumber']==littlePhotos[4]['countPhotosInReport']){
                     $('right-button').setAttribute('class','next-notactive');
                     $('right-button-end').setAttribute('class','notactive');
                     $('right-button-end').set('html',"<b>В конец</b>");
                     $('right-button-5').setAttribute('class','notactive');
                     $('right-button-5').set('html',"<b>Следующие 5</b>");
                  } else {
                      $('right-button').setAttribute('class','next');
                      $('right-button-end').set('html',"<a href='end/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' ><b id='toEnd_href'>В конец</b></a>");
                      $('right-button-end').removeProperty('class');
                      $('right-button-5').set('html',"<a href='next/"+littlePhotos[4]['photo_id']+"/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' ><b id='NextFive_href'>Следующие 5</b></a>");
                      $('right-button-5').removeProperty('class');
                  }



                 littlePhotos.each(function(value, index){
                            if(value.photo_id==bigPhotoId){
                               $('photo_'+value.photo_id).setAttribute('class','activeSmallPrew');
                            } else {
                               $('photo_'+value.photo_id).setAttribute('class','smallPrew');
                            }
                        })

              if(table == 'PhotosNewDBO'){
                 if (vote=='0'){                   
                    var voteText=  "<a href='vote/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' class='golLink' id='addVoice_"+this.bigPhoto[0][table][0]['photo_id']+"'>Проголосовать за фото (+1)</a>";
                    $('golos').set('html', voteText);
                    $('golos').setStyle('display', 'block');
                   
                } else {

                      var voteText= "<span class='golSpan' id='voted' style='display:block'>Cпасибо, Ваш голос учтен!</span>";
                      $('golos').set('html', voteText);
                      $('golos').setStyle('display', 'block');

                }
                $('photo_rating').setStyle('display','block');
                  $$('.golLink').addEvent('click', function(e) {

                        var reg = /\D*/;
                        var photoId = this.getAttribute('id').replace(reg, "");
                      new Ria_Vote_VoteForPhoto({'photoId':photoId});

                    return false;
                });
              }else{
                  $('golos').set('html', '');
                  $('photo_rating').setStyle('display','none');
              }

                $$('.smallPrew').addEvent('click', function(e) {
                    var reg = /\D*/;
                    scroll.toElement('BigPhotoToScroll');
                  var photoId = this.getAttribute('id').replace(reg, "");
                  new Ria_Photo_ShowBigPhoto({'photoId':photoId,'photoReportID':littlePhotos[0]['photoReport_id']});

                    return false;
                });
                if($('toBegin_href')){
                    $('toBegin_href').addEvent('click', function() {
                        new Ria_Photo_PhotosToBegin({'photoReport':littlePhotos[0]['photoReport_id']});
                        return false;
                    });
                }
                if($('PrevFive_href')){
                    $('PrevFive_href').addEvent('click', function() {
                        new  Ria_Photo_GetPrevFivePhotos({'photoId':littlePhotos[0]['photo_id']});

                        return false;
                    });
                }
                if($('NextFive_href')){
                    $('NextFive_href').addEvent('click', function() {
                        new  Ria_Photo_GetNextFivePhotos({'photoId':littlePhotos[4]['photo_id']});
                        return false;
                    });
                }
                if($('toEnd_href')){
                    $('toEnd_href').addEvent('click', function() {
                        new  Ria_Photo_PhotosToEnd({'photoReport':littlePhotos[0]['photoReport_id']});
                        return false;
                    });
                }

               
             
              var i=0;
              var newPhotosIdArray=[];
               littlePhotos.each(function(value, index){
                   newPhotosIdArray[i]= value.photo_id;
                   i++;
               });
                littlePhotosIdArray =  newPhotosIdArray;
                mainPhoto = this.bigPhoto[0][table][0]['photo_id'];
                this.addComments(this.comments,this.bigPhoto,table,tpl);
      
        },
        addPhotoInfo: function (bigPhoto,table){

            $('orig_img').set('html',"<a href='http://img.ria.ua/photos/"+bigPhoto[0][table][0]['file'].replace('.','orig.')+"'><b>Загрузить оригинал фото</b></a>");
            $('event_name').set('html',bigPhoto[0]['name']);
            $('event_desc').set('html',bigPhoto[0]['description']);
            $('event_date').set('html',bigPhoto[0]['date']['day']+bigPhoto[0]['date']['month_sklon']+bigPhoto[0]['date']['year']);
      //      $('event_city').set('html',bigPhoto[0]['ClubDBO']['CitiesDBO']['name']);
     //       $('event_place').set('html',bigPhoto[0]['ClubDBO']['name']);
     //       $('event_author').set('html',"<a href='photographer_"+bigPhoto[0]['PersonDBO']['person_id']+"'>"+bigPhoto[0]['PersonDBO']['name']+"</a>");
             if (table=='PhotosNewDBO'){
                $('count_view').set('html',bigPhoto[0][table][0]['count_view']);
             }
            $('photo_href').set('html',"<input type='text' style='width:100%' value='http://weekend.com.ua/photos/"+bigPhoto[0]['photoReport_id']+"/photo/"+bigPhoto[0][table][0]['photo_id']+"/'>");


    },
    addComments:function (comments,bigPhoto,table,tpl){

        $('comments_to_photo').innerHTML =tpl;
        if (comments['toCurrentAlbum'].length>0){

             comments['toCurrentAlbum'].each(function(value, index){
                 if(value['object_id']==bigPhoto[0][table][0]['photo_id']){
                     $('com_'+value['comment_id']).setStyle('display','none');
                 } else {
                      $('com_'+value['comment_id']).setStyle('display','block');
                 }
            });
        }else{
             $('comments_to_album').set('html', '');
        }


        $$('.handUp').addEvent('click', function(e) {
            var reg = /\D*/;
            var commentId = this.getAttribute('id').replace(reg, "");
            new Ria_Vote_VoteManager({'commentId':commentId,'event':'vote_commentPositive'});

            return false;
        });

        $$('.handDown').addEvent('click', function(e) {
            var reg = /\D*/;
            var commentId = this.getAttribute('id').replace(reg, "");
            new Ria_Vote_VoteManager({'commentId':commentId,'event':'vote_commentNegative'});
            return false;
        });

        $$('.textInputEmail').addEvent('blur',function(e){
           var reg = /\D*/;
           var commentId = this.getAttribute('id').replace(reg, "");
           var userMail = $('answer_mail_'+commentId).get('value');
           if (userMail.test('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$')){
            new Ria_Login_CheckUserEmail({'user_email':userMail,'commentId':commentId});
           } else {
              $('answer_user_'+commentId).set('html','Пожалуйста введите правильный E-mail адрес.<br/>Например: имя@domain.ru' );
              $('answer_user_'+commentId).setAttribute('class','error');
              $('answer_user_'+commentId).setAttribute('style','display:block');
              $('input_psw_'+commentId).setAttribute('style','display:none');
           }
          return false;
        });

        $$('.textInputPsw').addEvent('blur',function(e){
           var reg = /\D*/;
           var commentId = this.getAttribute('id').replace(reg, "");
           var userMail = $('answer_mail_'+commentId).get('value');
           if (userMail.test('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$')){
               var userPasw = $('user_pasw_'+commentId).get('value');
               new Ria_Login_CheckUserPassword({'user_email':userMail,'user_pasw':userPasw,'commentId':commentId});
            } else {
              $('answer_user_'+commentId).set('html','Пожалуйста введите правильный E-mail адрес.<br/>Например: имя@domain.ru' );
              $('answer_user_'+commentId).setAttribute('class','error');
              $('answer_user_'+commentId).setAttribute('style','display:block');
              $('input_psw_'+commentId).setAttribute('style','display:none');
           }
           return false;
         });
    }

});


/**
 * Ria_Photo_GetPrevBigPhoto
 *
 * @class       Ria_Photo_GetPrevBigPhoto
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_GetPrevBigPhoto = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'get_prev_photo'
	},

	initialize: function(options){
             if(options.photoId!=0){
			var imgContainer = $('big_photo');
			var load=new Element('div',{id: 'load','styles': {
                                                                            'position'  : 'absolute',
                                                                            'float':'left',
                                                                            'top':'280px',
                                                                            'margin-left' 	:'280px'
                                                                          }
			})/*.set('opacity', 0.1)*/.inject(imgContainer);
			$('img').morph({
						opacity: 0.5
					});
    		var img = new Element('img', {'src': 'img/load.gif','styles':{
                                                                               'background':'none',
                                                                               'border':'none'
                                                                             }
    		});
                $('big_photo').setStyle('height','');
    		img.inject(load);
                this.setOptions(options);
                this.parent(options);
            //    $('scroll').empty().addClass('ajax-loading');
		}

  	},

	onGetResponse: function(jsonObj){
           
                this.bigPhoto = jsonObj.photo;
                var littlePhotos = jsonObj.photos;
                var vote = jsonObj.vote;
                var tpl =jsonObj.tpl;
                this.comments = jsonObj.comments;
                this.rating =jsonObj.rating;
                var photoRating = "&nbsp;&nbsp;&nbsp; Рейтинг:&nbsp;"+this.rating;
                 var photos='';
                 var table = '';
                  if (this.bigPhoto[0]['PhotosNewDBO']){
                     table = 'PhotosNewDBO';
                 } else{
                     table = 'PhotosTempDBO';
                 }

                    this.addPhotoInfo(this.bigPhoto,table);
   
                 littlePhotos.each(function(value, index){

                    if(value.photo_id==bigPhotoId){
                         photo_class = 'activeSmallPrew';
                    } else{
                        photo_class = 'smallPrew';
                    }
                  photos =photos+ "<div><a href='photos/"+littlePhotos[0]['photoReport_id']+"/photo/"+value.photo_id+"/' class='"+photo_class+"' id='photo_"+value.photo_id+"'> <img src='http://img.ria.ua/photos/"+value.src.replace('.','sw.')+"'"+'/> </a><div><div>'+value.photoNumber+'</div></div></div>';
                  lastPhotoID = value.photo_id;
                })
                  firstPhotoID = littlePhotos[0]['photo_id'];
             //      $('scroll').removeClass('ajax-loading');
                  $('scroll').set('html',photos);
                  
                  
                var photo = 'http://img.ria.ua/photos/'+this.bigPhoto[0][table][0]['file'].replace('.','m.');
                $('img').set('src',photo);
//                $('img').addEvent('load',function(event){
//					var load = $('load');
//					if (load!=null)load.destroy();
//                                        var heightBigPhoto = document.getElementById('big_photo').clientHeight;
//                                        $('big_photo').setStyle('height',heightBigPhoto);
//					$('img').morph({
//						opacity: 1
//					});
//                });
                $('view-many').set('href','multi/photos/'+this.bigPhoto[0]['photoReport_id']+'/photo/'+this.bigPhoto[0][table][0]['photo_id']+'/0/#spinToPhoto');
                $('left-button-home').set('href',"begin/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/");
                $('right-button-end').set('href',"end/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/");
                $('left-button-5').set('href',"previous/"+littlePhotos[0]['photo_id']+"/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/");
                $('right-button-5').set('href',"next/"+littlePhotos[4]['photo_id']+"/photo_"+this.bigPhoto[0][table][0]['photo_id']+"/");
                $('add_comment_block').set('value',this.bigPhoto[0][table][0]['photo_id']);
                  if(table == 'PhotosNewDBO'){
                        $('photo_rating').set('html',photoRating);
                        $('photo_rating').setStyle('display','block');
                  }else{
                      $('photo_rating').set('html','&nbsp;');
                  }

                bigPhotoId = this.bigPhoto[0][table][0]['photo_id'];
               
                if (littlePhotos[0]['photoNumber']==1){
                     $('left-button').setAttribute('class','first-notactive');
                     $('left-button-home').setAttribute('class','notactive');
                      $('left-button-home').set('html',"<b >В начало</b>");
                     $('left-button-5').setAttribute('class','notactive');
                     $('left-button-5').set('html', "<b>Предыдущие 5</b>");

                  } else {
                      $('left-button').setAttribute('class','first');
                      $('left-button-home').set('html',"<a  href='begin/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' id='toBegin_href'><b>В начало</b></a>");
                       $('left-button-home').removeProperty('class');
                       $('left-button-5').set('html', "<a href='previous/"+littlePhotos[0]['photo_id']+"/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/'><b id='PrevFive_href'>Предыдущие 5</b></a>");
                       $('left-button-5').removeProperty('class');
                  }
                  if (littlePhotos[4]['photoNumber']==littlePhotos[4]['countPhotosInReport']){
                     $('right-button').setAttribute('class','next-notactive');
                     $('right-button-end').setAttribute('class','notactive');
                     $('right-button-end').set('html',"<b>В конец</b>");
                     $('right-button-5').setAttribute('class','notactive');
                     $('right-button-5').set('html',"<b>Следующие 5</b>");
                  } else {
                      $('right-button').setAttribute('class','next');
                      $('right-button-end').set('html',"<a href='end/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' ><b id='toEnd_href'>В конец</b></a>");
                      $('right-button-end').removeProperty('class');
                      $('right-button-5').set('html',"<a href='next/"+littlePhotos[4]['photo_id']+"/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' ><b id='NextFive_href'>Следующие 5</b></a>");
                      $('right-button-5').removeProperty('class');
                  }



                 littlePhotos.each(function(value, index){
                            if(value.photo_id==bigPhotoId){
                               $('photo_'+value.photo_id).setAttribute('class','activeSmallPrew');
                            } else {
                               $('photo_'+value.photo_id).setAttribute('class','smallPrew');
                            }
                        })

              if(table == 'PhotosNewDBO'){
                 if (vote=='0'){                   
                    var voteText=  "<a href='vote/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' class='golLink' id='addVoice_"+this.bigPhoto[0][table][0]['photo_id']+"'>Проголосовать за фото (+1)</a>";
                    $('golos').set('html', voteText);
                    $('golos').setStyle('display', 'block');
                   
                } else {

                      var voteText= "<span class='golSpan' id='voted' style='display:block'>Cпасибо, Ваш голос учтен!</span>";
                      $('golos').set('html', voteText);
                      $('golos').setStyle('display', 'block');

                }
                $('photo_rating').setStyle('display','block');
                  $$('.golLink').addEvent('click', function(e) {

                        var reg = /\D*/;
                        var photoId = this.getAttribute('id').replace(reg, "");
                      new Ria_Vote_VoteForPhoto({'photoId':photoId});

                    return false;
                });
              }else{
                  $('golos').set('html', '');
                  $('photo_rating').setStyle('display','none');
              }

                $$('.smallPrew').addEvent('click', function(e) {
                    var reg = /\D*/;
                    scroll.toElement('BigPhotoToScroll');
                  var photoId = this.getAttribute('id').replace(reg, "");
                  new Ria_Photo_ShowBigPhoto({'photoId':photoId,'photoReportID':littlePhotos[0]['photoReport_id']});

                    return false;
                });
                if($('toBegin_href')){
                    $('toBegin_href').addEvent('click', function() {
                        new Ria_Photo_PhotosToBegin({'photoReport':littlePhotos[0]['photoReport_id']});
                        return false;
                    });
                }
                if($('PrevFive_href')){
                    $('PrevFive_href').addEvent('click', function() {
                        new  Ria_Photo_GetPrevFivePhotos({'photoId':littlePhotos[0]['photo_id']});

                        return false;
                    });
                }
                if($('NextFive_href')){
                    $('NextFive_href').addEvent('click', function() {
                        new  Ria_Photo_GetNextFivePhotos({'photoId':littlePhotos[4]['photo_id']});
                        return false;
                    });
                }
                if($('toEnd_href')){
                    $('toEnd_href').addEvent('click', function() {
                        new  Ria_Photo_PhotosToEnd({'photoReport':littlePhotos[0]['photoReport_id']});
                        return false;
                    });
                }
                
             
              var i=0;
              var newPhotosIdArray=[];
               littlePhotos.each(function(value, index){
                   newPhotosIdArray[i]= value.photo_id;
                   i++;
               });
                littlePhotosIdArray =  newPhotosIdArray;
                mainPhoto = this.bigPhoto[0][table][0]['photo_id'];
                this.addComments(this.comments,this.bigPhoto,table,tpl);
      
        },
        addPhotoInfo: function (bigPhoto,table){

            $('orig_img').set('html',"<a href='http://img.ria.ua/photos/"+bigPhoto[0][table][0]['file'].replace('.','orig.')+"'><b>Загрузить оригинал фото</b></a>");
            $('event_name').set('html',bigPhoto[0]['name']);
            $('event_desc').set('html',bigPhoto[0]['description']);
            $('event_date').set('html',bigPhoto[0]['date']['day']+bigPhoto[0]['date']['month_sklon']+bigPhoto[0]['date']['year']);
      //      $('event_city').set('html',bigPhoto[0]['ClubDBO']['CitiesDBO']['name']);
     //       $('event_place').set('html',bigPhoto[0]['ClubDBO']['name']);
     //       $('event_author').set('html',"<a href='photographer_"+bigPhoto[0]['PersonDBO']['person_id']+"'>"+bigPhoto[0]['PersonDBO']['name']+"</a>");
             if (table=='PhotosNewDBO'){
                 $('count_view').set('html',bigPhoto[0][table][0]['count_view']);
             }
            $('photo_href').set('html',"<input type='text' style='width:100%' value='http://weekend.com.ua/photos/"+bigPhoto[0]['photoReport_id']+"/photo/"+bigPhoto[0][table][0]['photo_id']+"/'>");


    },
    addComments:function (comments,bigPhoto,table,tpl){

        $('comments_to_photo').innerHTML =tpl;
        if (comments['toCurrentAlbum'].length>0){

             comments['toCurrentAlbum'].each(function(value, index){
                 if(value['object_id']==bigPhoto[0][table][0]['photo_id']){
                     $('com_'+value['comment_id']).setStyle('display','none');
                 } else {
                      $('com_'+value['comment_id']).setStyle('display','block');
                 }
            });
        }else{
             $('comments_to_album').set('html', '');
        }


        $$('.handUp').addEvent('click', function(e) {
            var reg = /\D*/;
            var commentId = this.getAttribute('id').replace(reg, "");
            new Ria_Vote_VoteManager({'commentId':commentId,'event':'vote_commentPositive'});

            return false;
        });

        $$('.handDown').addEvent('click', function(e) {
            var reg = /\D*/;
            var commentId = this.getAttribute('id').replace(reg, "");
            new Ria_Vote_VoteManager({'commentId':commentId,'event':'vote_commentNegative'});
            return false;
        });

        var heightBigPhoto = document.getElementById('big_photo').clientHeight;
                $('big_photo').setStyle('height',heightBigPhoto);

        $$('.textInputEmail').addEvent('blur',function(e){
           var reg = /\D*/;
           var commentId = this.getAttribute('id').replace(reg, "");
           var userMail = $('answer_mail_'+commentId).get('value');
           if (userMail.test('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$')){
            new Ria_Login_CheckUserEmail({'user_email':userMail,'commentId':commentId});
           } else {
              $('answer_user_'+commentId).set('html','Пожалуйста введите правильный E-mail адрес.<br/>Например: имя@domain.ru' );
              $('answer_user_'+commentId).setAttribute('class','error');
              $('answer_user_'+commentId).setAttribute('style','display:block');
              $('input_psw_'+commentId).setAttribute('style','display:none');
           }
          return false;
        });

        $$('.textInputPsw').addEvent('blur',function(e){
           var reg = /\D*/;
           var commentId = this.getAttribute('id').replace(reg, "");
           var userMail = $('answer_mail_'+commentId).get('value');
           if (userMail.test('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$')){
               var userPasw = $('user_pasw_'+commentId).get('value');
               new Ria_Login_CheckUserPassword({'user_email':userMail,'user_pasw':userPasw,'commentId':commentId});
            } else {
              $('answer_user_'+commentId).set('html','Пожалуйста введите правильный E-mail адрес.<br/>Например: имя@domain.ru' );
              $('answer_user_'+commentId).setAttribute('class','error');
              $('answer_user_'+commentId).setAttribute('style','display:block');
              $('input_psw_'+commentId).setAttribute('style','display:none');
           }
           return false;
         });
    }

});


/**
 * Ria_Afisha_PublicManager
 *
 * @class       Ria_Afisha_PublicManager
 * @copyright   MegaDevel
 * @license     GNU GPL v2
 * @author      MegaDevel
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Afisha_PublicManager = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 'afisha'
	},

	initialize: function(options){
		this.setOptions(options);
		new Request.JSON({url: Ria_Core_Ajax.script,
			onComplete: this.onGetResponse.bind(this),
			onFailure:this.loadError.bind(this)
		}).get(this.options);
	},
	
	loadError: function(el){
		try {
			$('loading').innerHTML = 'Ошибка доступа к серверу. Перегрузите страницу!';
			$('loading').setStyle('display', 'block');
		} catch (e) {
			alert('Обратитесь ко мне =).')
		}
	},
	
	onGetResponse: function(obj){
		
		switch (this.options.event) {
		
			case 'characters':
				this.getClubs(obj);
			break;
			
			case 'old_seans':
				this.getOldSeans(obj);
			break;
	
			default:
				return false;
			break;
			
		}
	},
	
	getClubs: function(result){
		$('board_'+this.options.city_id).innerHTML = result.tpl;
	},

	getOldSeans: function(result){
		$('seansBlockOld').innerHTML = result.tpl;
	},
	
	loading: function(){
		//$('loading').setStyle('display', 'block');
	}
});

/**
 * Ria_Photo_GetNextBigMultiPhoto
 *
 * @class       Ria_Photo_GetNextBigMultiPhoto
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_GetNextBigMultiPhoto = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'get_next_multi_photo'
	},

	initialize: function(options){
             if(options.photoId!=0){
			var imgContainer = $('big_photo');
			var load=new Element('div',{id: 'load','styles': {
                                                                            'position'  : 'absolute',
                                                                            'float':'left',
                                                                            'top':'280px',
                                                                            'margin-left' 	:'280px'
                                                                          }
			})/*.set('opacity', 0.1)*/.inject(imgContainer);
			$('img').morph({
						opacity: 0.5
					});
    		var img = new Element('img', {'src': 'img/load.gif','styles':{
                                                                               'background':'none',
                                                                               'border':'none'
                                                                             }
    		});
                $('big_photo').setStyle('height','');
    		img.inject(load);
                this.setOptions(options);
                this.parent(options);

		}
            //     this.setOptions(options);
           //     this.parent(options);

  	},

	onGetResponse: function(jsonObj){
   
                this.bigPhoto = jsonObj.photo;
                var vote = jsonObj.vote;
                var tpl = jsonObj.tpl;
                this.comments= jsonObj.comments;
                this.rating =jsonObj.rating;
                var photoRating = "&nbsp;&nbsp;&nbsp; Рейтинг:&nbsp;"+this.rating;
                 var photos='';
                 var table = '';
                 if (this.bigPhoto[0]['PhotosNewDBO']){
                     table = 'PhotosNewDBO';
                 } else{
                     table = 'PhotosTempDBO';
                 }

                   this.addPhotoInfo(this.bigPhoto,table);


                var new_photoId = "photo/"+this.bigPhoto[0][table][0]['photo_id'];
                var photo = 'http://img.ria.ua/photos/'+this.bigPhoto[0][table][0]['file'].replace('.','m.');
                $('img').set('src',photo);
//                $('img').addEvent('load',function(event){
//					var load = $('load');
//					if (load!=null)load.destroy();
//                                        var heightBigPhoto = document.getElementById('big_photo').clientHeight;
//                                        $('big_photo').setStyle('height',heightBigPhoto);
//					$('img').morph({
//						opacity: 1
//					});
//		});
                $('add_comment_block').set('value',this.bigPhoto[0][table][0]['photo_id']);
                if( table == 'PhotosNewDBO'){
                    $('photo_rating').set('html',photoRating);
                    $('photo_rating').setStyle('display','block');
                }else{
                    $('photo_rating').set('html','&nbsp;');
                }

               
               var hrefsPrevNext = $$('.page').getChildren();
                        hrefsPrevNext[0].each(function(el){
                           if(el.tagName=='A'){
                                  var reg = /photo\/[0-9]*/;
                                  var new_href = el.getProperty('href').replace(reg, new_photoId);
                                  el.set('href',new_href);
                           }
                      });
                  var hrefs = $$('.numbers').getChildren();

                 hrefs[0].each(function(el){
                       if(el.tagName=='A'){
                              var reg = /photo\/[0-9]*/;
                              var new_href = el.getProperty('href').replace(reg, new_photoId);
                              el.set('href',new_href);
                       }
                 });

      //          bigPhotoId = this.bigPhoto[0]['PhotosNewDBO'][0]['photo_id'];

                                $('photo_'+this.bigPhoto[0][table][0]['photo_id']).removeProperty('class');
                               $('photo_'+this.bigPhoto[0][table][0]['photo_id']).setAttribute('class','multiPhotoItem activeMulti');
                               if ($('photo_'+selectedImgId)){
                                   $('photo_'+selectedImgId).removeProperty('class');
                                   $('photo_'+selectedImgId).setAttribute('class','multiPhotoItem');
                               }
                               selectedImgId = this.bigPhoto[0][table][0]['photo_id'];

             if( table == 'PhotosNewDBO'){
                 if (vote=='0'){
                    var voteText=  "<a href='vote/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' class='golLink' id='addVoice_"+this.bigPhoto[0][table][0]['photo_id']+"'>Проголосовать за фото (+1)</a>";
                  $('golos').set('html', voteText);
                  $('golos').setStyle('display', 'block');
                } else {

                      var voteText= "<span class='golSpan' id='voted' style='display:block'>Cпасибо, Ваш голос учтен!</span>";
                      $('golos').set('html', voteText);
                      $('golos').setStyle('display', 'block');
                }
                  $$('.golLink').addEvent('click', function(e) {

                        var reg = /\D*/;
                        var photoId = this.getAttribute('id').replace(reg, "");
                      new Ria_Vote_VoteForPhoto({'photoId':photoId});

                    return false;
                });
             }else{
                  $('golos').set('html', '');
                  $('photo_rating').setStyle('display','none');
             }
               // mainPhoto = this.bigPhoto[0][table][0]['photo_id'];
              
                this.addComments(this.comments,this.bigPhoto,table,tpl);


        },
        addPhotoInfo: function (bigPhoto,table){

            $('orig_img').set('html',"<a href='http://img.ria.ua/photos/"+bigPhoto[0][table][0]['file'].replace('.','orig.')+"'><b>Загрузить оригинал фото</b></a>");
            $('event_name').set('html',bigPhoto[0]['name']);
            $('event_desc').set('html',bigPhoto[0]['description']);
            $('event_date').set('html',bigPhoto[0]['date']['day']+bigPhoto[0]['date']['month_sklon']+bigPhoto[0]['date']['year']);
      //      $('event_city').set('html',bigPhoto[0]['ClubDBO']['CitiesDBO']['name']);
     //       $('event_place').set('html',bigPhoto[0]['ClubDBO']['name']);
     //       $('event_author').set('html',"<a href='photographer_"+bigPhoto[0]['PersonDBO']['person_id']+"'>"+bigPhoto[0]['PersonDBO']['name']+"</a>");
           if (table=='PhotosNewDBO'){
                $('count_view').set('html',bigPhoto[0][table][0]['count_view']);
           }
            $('photo_href').set('html',"<input type='text' style='width:100%' value='http://weekend.com.ua/photos/"+bigPhoto[0]['photoReport_id']+"/photo/"+bigPhoto[0][table][0]['photo_id']+"/'>");


    },
    addComments:function (comments,bigPhoto,table,tpl){
         $('comments_to_photo').innerHTML =tpl;


        if (comments['toCurrentAlbum'].length>0){

             comments['toCurrentAlbum'].each(function(value, index){
                 if(value['object_id']==bigPhoto[0][table][0]['photo_id']){
                     $('com_'+value['comment_id']).setStyle('display','none');
                 } else {
                      $('com_'+value['comment_id']).setStyle('display','block');
                 }
            });
        }else{
             $('comments_to_album').set('html', '');
        }



        $$('.handUp').addEvent('click', function(e) {
            var reg = /\D*/;
            var commentId = this.getAttribute('id').replace(reg, "");
            new Ria_Vote_VoteManager({'commentId':commentId,'event':'vote_commentPositive'});

            return false;
        });

        $$('.handDown').addEvent('click', function(e) {
            var reg = /\D*/;
            var commentId = this.getAttribute('id').replace(reg, "");
            new Ria_Vote_VoteManager({'commentId':commentId,'event':'vote_commentNegative'});
            return false;
        });
        $$('.textInputEmail').addEvent('blur',function(e){
           var reg = /\D*/;
           var commentId = this.getAttribute('id').replace(reg, "");
           var userMail = $('answer_mail_'+commentId).get('value');
           if (userMail.test('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$')){
            new Ria_Login_CheckUserEmail({'user_email':userMail,'commentId':commentId});
           } else {
              $('answer_user_'+commentId).set('html','Пожалуйста введите правильный E-mail адрес.<br/>Например: имя@domain.ru' );
              $('answer_user_'+commentId).setAttribute('class','error');
              $('answer_user_'+commentId).setAttribute('style','display:block');
              $('input_psw_'+commentId).setAttribute('style','display:none');
           }
          return false;
        });

        $$('.textInputPsw').addEvent('blur',function(e){
           var reg = /\D*/;
           var commentId = this.getAttribute('id').replace(reg, "");
           var userMail = $('answer_mail_'+commentId).get('value');
           if (userMail.test('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$')){
               var userPasw = $('user_pasw_'+commentId).get('value');
               new Ria_Login_CheckUserPassword({'user_email':userMail,'user_pasw':userPasw,'commentId':commentId});
            } else {
              $('answer_user_'+commentId).set('html','Пожалуйста введите правильный E-mail адрес.<br/>Например: имя@domain.ru' );
              $('answer_user_'+commentId).setAttribute('class','error');
              $('answer_user_'+commentId).setAttribute('style','display:block');
              $('input_psw_'+commentId).setAttribute('style','display:none');
           }
           return false;
         });
    }

});


/**
 * Ria_Photo_GetPrevBigMultiPhoto
 *
 * @class       Ria_Photo_GetPrevBigMultiPhoto
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_GetPrevBigMultiPhoto = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'get_prev_multi_photo'
	},

	initialize: function(options){
             if(options.photoId!=0){
			var imgContainer = $('big_photo');
			var load=new Element('div',{id: 'load','styles': {
                                                                            'position'  : 'absolute',
                                                                            'float':'left',
                                                                            'top':'280px',
                                                                            'margin-left' 	:'280px'
                                                                          }
			})/*.set('opacity', 0.1)*/.inject(imgContainer);
			$('img').morph({
						opacity: 0.5
					});
    		var img = new Element('img', {'src': 'img/load.gif','styles':{
                                                                               'background':'none',
                                                                               'border':'none'
                                                                             }
    		});
                $('big_photo').setStyle('height','');
    		img.inject(load);
                this.setOptions(options);
                this.parent(options);

		}
            //     this.setOptions(options);
           //     this.parent(options);

  	},

	onGetResponse: function(jsonObj){
   
                this.bigPhoto = jsonObj.photo;
                var vote = jsonObj.vote;
                var tpl = jsonObj.tpl;
                this.comments= jsonObj.comments;
                this.rating =jsonObj.rating;
                var photoRating = "&nbsp;&nbsp;&nbsp; Рейтинг:&nbsp;"+this.rating;
                 var photos='';
                 var table = '';
                 if (this.bigPhoto[0]['PhotosNewDBO']){
                     table = 'PhotosNewDBO';
                 } else{
                     table = 'PhotosTempDBO';
                 }

                   this.addPhotoInfo(this.bigPhoto,table);


                var new_photoId = "photo/"+this.bigPhoto[0][table][0]['photo_id'];
                var photo = 'http://img.ria.ua/photos/'+this.bigPhoto[0][table][0]['file'].replace('.','m.');
                $('img').set('src',photo);
//                $('img').addEvent('load',function(event){
//					var load = $('load');
//					if (load!=null)load.destroy();
//                                        var heightBigPhoto = document.getElementById('big_photo').clientHeight;
//                                        $('big_photo').setStyle('height',heightBigPhoto);
//					$('img').morph({
//						opacity: 1
//					});
//		});
                $('add_comment_block').set('value',this.bigPhoto[0][table][0]['photo_id']);
                if( table == 'PhotosNewDBO'){
                    $('photo_rating').set('html',photoRating);
                    $('photo_rating').setStyle('display','block');
                }else{
                    $('photo_rating').set('html','&nbsp;');
                }

               
               var hrefsPrevNext = $$('.page').getChildren();
                        hrefsPrevNext[0].each(function(el){
                           if(el.tagName=='A'){
                                  var reg = /photo\/[0-9]*/;
                                  var new_href = el.getProperty('href').replace(reg, new_photoId);
                                  el.set('href',new_href);
                           }
                      });
                  var hrefs = $$('.numbers').getChildren();

                 hrefs[0].each(function(el){
                       if(el.tagName=='A'){
                              var reg = /photo\/[0-9]*/;
                              var new_href = el.getProperty('href').replace(reg, new_photoId);
                              el.set('href',new_href);
                       }
                 });

      //          bigPhotoId = this.bigPhoto[0]['PhotosNewDBO'][0]['photo_id'];

                                $('photo_'+this.bigPhoto[0][table][0]['photo_id']).removeProperty('class');
                               $('photo_'+this.bigPhoto[0][table][0]['photo_id']).setAttribute('class','multiPhotoItem activeMulti');
                               if ($('photo_'+selectedImgId)){
                                   $('photo_'+selectedImgId).removeProperty('class');
                                   $('photo_'+selectedImgId).setAttribute('class','multiPhotoItem');
                               }
                               selectedImgId = this.bigPhoto[0][table][0]['photo_id'];

             if( table == 'PhotosNewDBO'){
                 if (vote=='0'){
                    var voteText=  "<a href='vote/photo/"+this.bigPhoto[0][table][0]['photo_id']+"/' class='golLink' id='addVoice_"+this.bigPhoto[0][table][0]['photo_id']+"'>Проголосовать за фото (+1)</a>";
                  $('golos').set('html', voteText);
                  $('golos').setStyle('display', 'block');
                } else {

                      var voteText= "<span class='golSpan' id='voted' style='display:block'>Cпасибо, Ваш голос учтен!</span>";
                      $('golos').set('html', voteText);
                      $('golos').setStyle('display', 'block');
                }
                  $$('.golLink').addEvent('click', function(e) {

                        var reg = /\D*/;
                        var photoId = this.getAttribute('id').replace(reg, "");
                      new Ria_Vote_VoteForPhoto({'photoId':photoId});

                    return false;
                });
             }else{
                  $('golos').set('html', '');
                  $('photo_rating').setStyle('display','none');
             }
               // mainPhoto = this.bigPhoto[0][table][0]['photo_id'];
              
                this.addComments(this.comments,this.bigPhoto,table,tpl);


        },
        addPhotoInfo: function (bigPhoto,table){

            $('orig_img').set('html',"<a href='http://img.ria.ua/photos/"+bigPhoto[0][table][0]['file'].replace('.','orig.')+"'><b>Загрузить оригинал фото</b></a>");
            $('event_name').set('html',bigPhoto[0]['name']);
            $('event_desc').set('html',bigPhoto[0]['description']);
            $('event_date').set('html',bigPhoto[0]['date']['day']+bigPhoto[0]['date']['month_sklon']+bigPhoto[0]['date']['year']);
      //      $('event_city').set('html',bigPhoto[0]['ClubDBO']['CitiesDBO']['name']);
     //       $('event_place').set('html',bigPhoto[0]['ClubDBO']['name']);
     //       $('event_author').set('html',"<a href='photographer_"+bigPhoto[0]['PersonDBO']['person_id']+"'>"+bigPhoto[0]['PersonDBO']['name']+"</a>");
             if (table=='PhotosNewDBO'){
                $('count_view').set('html',bigPhoto[0][table][0]['count_view']);
             }
            $('photo_href').set('html',"<input type='text' style='width:100%' value='http://weekend.com.ua/photos/"+bigPhoto[0]['photoReport_id']+"/photo/"+bigPhoto[0][table][0]['photo_id']+"/'>");


    },
    addComments:function (comments,bigPhoto,table,tpl){
         $('comments_to_photo').innerHTML =tpl;


        if (comments['toCurrentAlbum'].length>0){

             comments['toCurrentAlbum'].each(function(value, index){
                 if(value['object_id']==bigPhoto[0][table][0]['photo_id']){
                     $('com_'+value['comment_id']).setStyle('display','none');
                 } else {
                      $('com_'+value['comment_id']).setStyle('display','block');
                 }
            });
        }else{
             $('comments_to_album').set('html', '');
        }



        $$('.handUp').addEvent('click', function(e) {
            var reg = /\D*/;
            var commentId = this.getAttribute('id').replace(reg, "");
            new Ria_Vote_VoteManager({'commentId':commentId,'event':'vote_commentPositive'});

            return false;
        });

        $$('.handDown').addEvent('click', function(e) {
            var reg = /\D*/;
            var commentId = this.getAttribute('id').replace(reg, "");
            new Ria_Vote_VoteManager({'commentId':commentId,'event':'vote_commentNegative'});
            return false;
        });
        $$('.textInputEmail').addEvent('blur',function(e){
           var reg = /\D*/;
           var commentId = this.getAttribute('id').replace(reg, "");
           var userMail = $('answer_mail_'+commentId).get('value');
           if (userMail.test('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$')){
            new Ria_Login_CheckUserEmail({'user_email':userMail,'commentId':commentId});
           } else {
              $('answer_user_'+commentId).set('html','Пожалуйста введите правильный E-mail адрес.<br/>Например: имя@domain.ru' );
              $('answer_user_'+commentId).setAttribute('class','error');
              $('answer_user_'+commentId).setAttribute('style','display:block');
              $('input_psw_'+commentId).setAttribute('style','display:none');
           }
          return false;
        });

        $$('.textInputPsw').addEvent('blur',function(e){
           var reg = /\D*/;
           var commentId = this.getAttribute('id').replace(reg, "");
           var userMail = $('answer_mail_'+commentId).get('value');
           if (userMail.test('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$')){
               var userPasw = $('user_pasw_'+commentId).get('value');
               new Ria_Login_CheckUserPassword({'user_email':userMail,'user_pasw':userPasw,'commentId':commentId});
            } else {
              $('answer_user_'+commentId).set('html','Пожалуйста введите правильный E-mail адрес.<br/>Например: имя@domain.ru' );
              $('answer_user_'+commentId).setAttribute('class','error');
              $('answer_user_'+commentId).setAttribute('style','display:block');
              $('input_psw_'+commentId).setAttribute('style','display:none');
           }
           return false;
         });
    }

});


/**
 * Ria_City_Manager
 *
 * @class       Ria_Club_Manager
 * @copyright   MegaDevel
 * @license     GNU GPL v2
 * @author      MegaDevel
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Club_Manager = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 'Club'
	},

	initialize: function(options){
		this.loading();
		this.setOptions(options);
		this.parent(options);
	},
	
	onGetResponse: function(obj){
		
		var select = $('club');
		select.empty();
		
		if(obj.clubs){
			var clubs = obj.clubs;
			clubs.each(function(item){
				var option  = new Element('option',{'value':item.club_id, 'html':item.name});
				if($defined($('club_selected'))){
					if (item.club_id==$('club_selected').get('value')){
					    option.set('selected','true');
					}	
				}
				option.inject(select);
			});
			select.setStyle('width','auto');
			select.set('disabled', false);
		}
	},
	
	loading: function(){
		var select = $('club');
		select.set('disabled', 'disabled');
		select.empty();
		var option  = new Element('option',{'html':'Loading ...'});
		option.inject(select);
	}
});
/**
 * Ria_Vote_VoteForNews
 *
 * @class       Ria_Vote_VoteForNews
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Vote_VoteForNews = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'news',
		event: 		'voteNews_Positive'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);

	},

	onGetResponse: function(jsonObj){
            var vote = jsonObj.votes;
            var rating = jsonObj.rating;
            var newsId = jsonObj.newsId;

            $('commp_' + newsId).setStyle('display', 'none');
             $('commn_' + newsId).setStyle('display', 'none');
             if (rating>0){
               var  sign = "+";
             }else {
              var sign = "";
             }
            $('value_' + newsId).set('html',sign+rating+" / "+"<span class='plusT'>"+vote+"</span>");

	}
});
/**
 * Ria_Photo_SetAlbumPublicByImg
 *
 * @class       Ria_Photo_SetAlbumPublic
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_SetAlbumPublicByImg = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'uploader',
		event: 		'setAlbumPublicByImg'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);
      	},

	onGetResponse: function(jsonObj){
            var publicReport = jsonObj.publicReport;
            var ReportId = jsonObj.ReportId;
            var is_checked = jsonObj.is_checked;
            if(publicReport==1 && is_checked==0){
                
                $('status_'+ReportId).set('html','ожидает проверки');
                $('setAlbumPublic_'+ReportId).set('html','Снять с просмотра');

            }else if(publicReport==0 && is_checked==0){
                
                $('status_'+ReportId).set('html','невидимка');
                $('setAlbumPublic_'+ReportId).set('html','Опубликовать');
                
            } else if(publicReport==1 && is_checked==1){
                
                $('status_'+ReportId).set('html','активен');
                $('setAlbumPublic_'+ReportId).set('html','Снять с просмотра');
            }
            else if(publicReport==0 && is_checked==1){
               
                $('status_'+ReportId).set('html','невидимка');
                $('setAlbumPublic_'+ReportId).set('html','Опубликовать');

            }
          
        }


});


/**
 * Ria_Login_SendPassword
 *
 * @class       Ria_Login_SendPassword
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Login_SendPassword = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'login',
		event: 		'send_password'
	},

	initialize: function(options){
                 this.setOptions(options);
                this.parent(options);
                $('preloader_img').setStyle('display',"block");

  	},

	onGetResponse: function(jsonObj){
                var result = jsonObj.result;
              if (result==1){
                   $('preloader_img').setStyle('display',"none");
                   $('user_msg').set('html',"На Ваш  E-mail aдрес было выслано письмо со ссылкой. Перейдите пожалуйста по ней для изменения своего текущего пароля.");
                   $('user_msg').setStyle('display', "block");
                   $('user_msg').setAttribute('class', "noticeBlock");
                  
              }else{
                   $('preloader_img').setStyle('display',"none");
                   $('user_msg').set('html',"К сожалению, пользователь с данным E-mail адресом не зарегистрирован.<br/> Проверьте пожалуйста введенный E-mail адрес и попробуйте еще раз.");
                   $('user_msg').setStyle('display',"block");
                   $('user_msg').setAtrribute('class',"errorBlock");
              }
    }

});


/**
 * Ria_Login_CheckUserLogin
 *
 * @class       Ria_Login_CheckUserLogin
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Login_CheckUserLogin = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'login',
		event: 		'check_userLogin'
	},

	initialize: function(options){
                this.setOptions(options);
                this.parent(options);


  	},

	onGetResponse: function(jsonObj){

          var  user= jsonObj.user;
          var password = jsonObj.pasw;
          var reload = jsonObj.reload;

        if (user==0){           
               $('user_msg').set('html',"Пожалуйста, проверьте правильность введенного e-mail адреса. Если Вы не зарегистрированы у нас на сайте то перейдити пожалуйста на страницу регистрации. <a href='registration/'>Регистрация</a>");
               $('user_msg').setAttribute('class','important');
               $('user_msg').setAttribute('style','display:block');
               $('input_psw').setAttribute('style', "display:none;");
           
        } else {
            if(user[0]['auth_type']==1){
                 location.href="mypage/";
              
            }
            if(user[0]['auth_type']==3 ){
                if(password==0 && reload==0 ){
                    $('user_msg').set('html',"Введен неправильный пароль.");
                     $('user_msg').setAttribute('class','important');
                     $('user_msg').setAttribute('style', "display:block;");
                     $('input_psw').setAttribute('style', "display:block;");
                }
                if ( password==1 && reload==1){
                    location.href="mypage/";
                }
                if(password==2 && reload==2){
                     $('user_msg').set('html',"Для указанного E-mail адреса необходим пароль.");
                     $('user_msg').setAttribute('class','important');
                     $('user_msg').setAttribute('style', "display:block;");
                     $('input_psw').setAttribute('style', "display:block;");
                }
            }
        }
    }

});


/**
 * Ria_Photo_addPhotoAlbumNew
 *
 * @class       Ria_Photo_addPhotoAlbumNew
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_addPhotoAlbumNew = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'photo',
		event: 		'addPhotoAlbum_new'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);
      	},

	onGetResponse: function(jsonObj){
                var report = jsonObj.Report_id;
                var ReportName =  jsonObj.ReportName;
                if(report){
                   $('answer_user_script').set('html','Вы выбрали событие: <b>"'+ReportName+'"</b>. Теперь Вы можете добавить к нему свои фотографии.' );
                   $('answer_user_script').setAttribute('class','well');
                   $('answer_user_script').setAttribute('style','display:block');
                   if( $('load_photo')){
                        $('load_photo').setAttribute('style','display:block');
                   }
                   $('info_Rep_form').setStyle('display','none');
                   phRep_id = report;
                }else{
                    $('answer_user_script').set('html','При создании альбома произошла ошибка. Проверьте пожалуйста правильность заполнения необходимых полей и еще раз сохранить альбом.' );
                   $('answer_user_script').setAttribute('class','error');
                   $('answer_user_script').setAttribute('style','display:block');
                }
 
        }


});


/**
 * Ria_Photo_SetAlbumPublic
 *
 * @class       Ria_Photo_SetAlbumPublic
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Photo_SetAlbumPublic = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'uploader',
		event: 		'setAlbumPublic'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);
      	},

	onGetResponse: function(jsonObj){
          
        }


});


/**
 * Ria_News_GetAllEvents
 *
 * @class      Ria_News_GetAllEvents
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_News_GetAllEvents = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'news',
		event: 		'get_all_event'
	},

	initialize: function(options){
                this.loading();
                 this.setOptions(options);
                this.parent(options);
  	},

	onGetResponse: function(jsonObj){
                var events = jsonObj.events;

                var select = $('select_event');
		select.empty();

		if(events){
                    var optionDefault  = new Element('option',{'value':0, 'html':'Выберите событие'});
                      optionDefault.inject(select);
			events.each(function(item){
				var option  = new Element('option',{'value':item.event_id, 'html':item.name});
				if($defined($('club_selected'))){
					if (item.club_id==$('club_selected').get('value')){
					    option.set('selected','true');
					}
				}
				option.inject(select);
			});
			select.setStyle('width','auto');
			select.set('disabled', false);
		}
	},

	loading: function(){
		var select = $('select_event');
		select.set('disabled', 'disabled');
		select.empty();
		var option  = new Element('option',{'html':'Loading ...'});
		option.inject(select);
	}
              
    

});


/**
 * Ria_News_GetEvents
 *
 * @class      Ria_News_GetEvents
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_News_GetEvents = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'news',
		event: 		'get_event'
	},

	initialize: function(options){
                this.loading();
                 this.setOptions(options);
                this.parent(options);
  	},

	onGetResponse: function(jsonObj){
                var other_user_events = jsonObj.other_user_events;
                var user_events = jsonObj.user_events;
                var moderated_club_id = jsonObj.moderated_club_id;
                var lastValueUser = 0;
                var lastValueOther = 0;
               
                var select = $('select_event');
		select.empty();
                var optionDefault  = new Element('option',{'value':0, 'html':'Выберите событие'});
                 optionDefault.inject(select);
		if(user_events.length){
                       var userEventsTitle = new Element('option',{html:'Личные события',disabled:true});
                        userEventsTitle.inject(select);
                        
			user_events.each(function(item){
				var option  = new Element('option',{'value':'us_'+item.EventDBO.event_id, 'html':item.EventDBO.name,'onclick':'$("addUserEventSimple").setStyle("display","none");return false;'});
				option.inject(select);
			});
			 
                         lastValueUser = user_events.length;
		}
                if(other_user_events.length){
                    
                       var otherUserEventsTitle = new Element('option',{html:'События других пользователей',disabled:true});
                        otherUserEventsTitle.inject(select);

			other_user_events.each(function(item){
				var option  = new Element('option',{'value':item.EventDBO.event_id, 'html':item.EventDBO.name,'onclick':'$("addUserEventSimple").setStyle("display","none");return false;'});
				option.inject(select);
			});

                        lastValueOther = other_user_events.length;
                        
		}
                
                if (moderated_club_id){
                    $('moderated_club_id').set('value',moderated_club_id);
                }else{
                    $('moderated_club_id').set('value',0);

                }
                 lastValue = lastValueUser*1 +lastValueOther*1;
                 
                var createUserEvent = new Element('option',{'value':lastValue, 'html':'Создать новое событие','onclick':'$("addUserEventSimple").set("style","")','style':'font-weight: bold;'});
                        createUserEvent.inject(select);
             select.set('disabled', false);
             
             //hiding creating photo report button if it is visible
               if($('create_album_button')){
                    $('create_album_button').setStyle('display','none');
               }
             $('moderated_event_id').set('value',0);

	},

	loading: function(){
		var select = $('select_event');
		//select.set('disabled', 'disabled');
		select.empty();
		var option  = new Element('option',{'html':'Loading ...'});
		option.inject(select);
	}
              
    

});


/**
 * Ria_News_GetClubs
 *
 * @class      Ria_News_GetClubs
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_News_GetClubs = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'news',
		event: 		'get_club'
	},

	initialize: function(options){
                this.loading();
                 this.setOptions(options);
                this.parent(options);
  	},

	onGetResponse: function(jsonObj){
                var clubs = jsonObj.clubs;
                var user_clubs = jsonObj.user_clubs;
                var lastValueUserClub = 0;
                var lastValueOtherUserClub = 0;
                var select = $('select_club');
		select.empty();

		
                    var optionDefault  = new Element('option',{'value':0, 'html':'Выберите заведение:'});
                    optionDefault.inject(select);
                    if (user_clubs.length){
                        var userClubs = new Element('option',{html:'Личные заведения',disabled:true});
                        userClubs.inject(select);
                        user_clubs.each(function(item){
				var option  = new Element('option',{'value':'us_'+item.club_id, 'html':'&nbsp;&nbsp;-'+item.club_name,'onclick':'$("createClub").setStyle("display","none");return false;'});				
				option.inject(select);
			});
                        lastValueUserClub = user_clubs.length;
                    }

                    if(clubs.length){
                      var otherClubs = new Element('option',{html:'Заведения других пользователей',disabled:true});
                        otherClubs.inject(select);
			clubs.each(function(item){
				var option  = new Element('option',{'value':item.club_id, 'html':'&nbsp;&nbsp;-'+item.name,'onclick':'$("createClub").setStyle("display","none");return false;'});				
				option.inject(select);
			});
                        lastValueOtherUserClub = clubs.length;
                    }
                        clubsLength = lastValueUserClub + lastValueOtherUserClub;
                        var createUserClub  = new Element('option',{'value':clubsLength+1, 'html':'Создать новое заведение','onclick':'creatingClub();','style':'font-weight: bold;'});
                        createUserClub.inject(select);
			//select.setStyle('width','auto');
			select.set('disabled', false);
                        
                        // обнуляем список событий
                         var eventSelector = $('select_event');
                        eventSelector.empty();
                    var optionDefaultEvent  = new Element('option',{'value':0, 'html':'Список событий'});
                        optionDefaultEvent.inject(eventSelector);
                        //hiding creating photo report button if it is visible
                          if($('create_album_button')){
                                $('create_album_button').setStyle('display','none');
                          }
                    //     $('moderated_event_id').set('value',0);
                    //     $('moderated_club_id').set('value',0);
		
	},

        

	loading: function(){
		var select = $('select_club');
		//select.set('disabled', 'disabled');
		select.empty();
		var option  = new Element('option',{'html':'Loading ...'});
		option.inject(select);
	}
              
    

});


/**
 * Ria_Afisha_GetClub
 *
 * @class       Ria_Afisha_GetClub
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Afisha_GetClub = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'afisha',
		event: 		'get_club'
	},

	initialize: function(options){
                 this.setOptions(options);
                this.parent(options);
  	},

	onGetResponse: function(jsonObj){
                var club_id= jsonObj.club_id;

               
                $('club_id').set('value',club_id);
              //   alert ( $('club_id').get('value'));
	}


});


/**
 * Ria_Club_CreateNewClub
 *
 * @class       Ria_Club_CreateNewClub
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      MegaDevel
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Club_CreateNewClub = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 'Club',
                event: 	'create_club'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);
	},
	
	onGetResponse: function(jsonObj){
             var created_club_id = jsonObj.created_club_id;
             var clubs = jsonObj.clubs;
             var user_clubs = jsonObj.user_clubs;
             var created_by_admin_club_id = jsonObj.created_by_admin_club_id;
             var lastValueUserClub = 0;
            var lastValueOtherUserClub = 0;
            var select = $('select_club');
            select.empty();


                var optionDefault  = new Element('option',{'value':0, 'html':'Выберите заведение:'});
                optionDefault.inject(select);
                if (user_clubs.length){
                    var userClubs = new Element('option',{html:'Личные заведения',disabled:true});
                    userClubs.inject(select);
                    user_clubs.each(function(item){
                            var option  = new Element('option',{'value':'us_'+item.club_id, 'html':'&nbsp;&nbsp;-'+item.club_name,'onclick':'$("createClub").setStyle("display","none");return false;'});
                            if (item.club_id==created_club_id){
                                        option.set('selected','true');
                            }
                            option.inject(select);
                    });
                    lastValueUserClub = user_clubs.length;
                }

                if(clubs.length){
                  var otherClubs = new Element('option',{html:'Заведения других пользователей',disabled:true});
                    otherClubs.inject(select);
                    clubs.each(function(item){
                            var option  = new Element('option',{'value':item.club_id, 'html':'&nbsp;&nbsp;-'+item.name,'onclick':'$("createClub").setStyle("display","none");return false;'});
                             if (item.club_id==created_club_id){
                                        option.set('selected','true');
                            }
                            option.inject(select);
                    });
                    lastValueOtherUserClub = clubs.length;
                }
                    clubsLength = lastValueUserClub + lastValueOtherUserClub;
                    var createUserClub  = new Element('option',{'value':clubsLength+1, 'html':'Создать новое заведение','onclick':'creatingClub();','style':'font-weight: bold;'});
                    createUserClub.inject(select);
                    select.set('disabled', false);
            if (created_club_id){
                $("createClub").setStyle("display","none");
            }

            // creating values for the event selector of the newly created club
            var eventSelector = $('select_event');
		eventSelector.empty();
            var optionDefaultEvent  = new Element('option',{'value':0, 'html':'Список событий'});
                optionDefaultEvent.inject(eventSelector);
            var createUserEvent = new Element('option',{'value':1, 'html':'Создать новое событие','onclick':'$("addUserEventSimple").set("style","")','style':'font-weight: bold;'});
                createUserEvent.inject(eventSelector);
                lastValue =1;
                $('moderated_event_id').set('value',0);
                if(created_by_admin_club_id){
                     $('moderated_club_id').set('value',created_by_admin_club_id);
                }else{
                    $('moderated_club_id').set('value',0);
                }
	},

	loading: function(){
		var select = $('select_club');
		select.set('disabled', 'disabled');
		select.empty();
		var option  = new Element('option',{'html':'Loading ...'});
		option.inject(select);
	}

	
});
/**
 * Ria_Club_CreateNewEvent
 *
 * @class       Ria_Club_CreateNewEvent
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      MegaDevel
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Club_CreateNewEvent = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 'Club',
                event: 	'create_event'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);
	},
	
	onGetResponse: function(jsonObj){
             var created_event_id = jsonObj.created_event_id;
            var other_user_events = jsonObj.other_user_events;
                var user_events = jsonObj.user_events;
                var created_admin_event_id  = jsonObj.created_admin_event_id;
                var lastValueUser = 0;
                var lastValueOther = 0;

                var select = $('select_event');
		select.empty();
                var optionDefault  = new Element('option',{'value':0, 'html':'Выберите событие'});
                 optionDefault.inject(select);
		if(user_events.length){
                       var userEventsTitle = new Element('option',{html:'Личные события',disabled:true});
                        userEventsTitle.inject(select);

			user_events.each(function(item){
				var option  = new Element('option',{'value':'us_'+item.EventDBO.event_id, 'html':item.EventDBO.name});
				option.inject(select);
                                 if (item.EventDBO.event_id==created_event_id){
					    option.set('selected','true');
                                 }
			});

                         lastValueUser = user_events.length;
		}
                if(other_user_events.length){
                       var otherUserEventsTitle = new Element('option',{html:'События других пользователей',disabled:true});
                        otherUserEventsTitle.inject(select);

			other_user_events.each(function(item){
				var option  = new Element('option',{'value':item.EventDBO.event_id, 'html':item.EventDBO.name});
				option.inject(select);
                                 if (item.EventDBO.event_id==created_event_id){
					    option.set('selected','true');
                                 }
			});

                        lastValueOther = user_events.length;
		}

                 lastValue = lastValueUser +lastValueOther;
                var createUserEvent = new Element('option',{'value':lastValue, 'html':'Создать новое событие','onclick':'$("addUserEventSimple").set("style","");','style':'font-weight: bold;'});
                        createUserEvent.inject(select);
             select.set('disabled', false);
             $('addUserEventSimple').setStyle('display','none');
             if($('create_album_button')){
                $('create_album_button').setStyle('display','block');
             }
              if(created_admin_event_id){
                 $('moderated_event_id').set('value',created_admin_event_id);
              }else{
                 $('moderated_event_id').set('value',0);
              }

	},

	loading: function(){
		var select = $('select_event');
		select.set('disabled', 'disabled');
		select.empty();
		var option  = new Element('option',{'html':'Loading ...'});
		option.inject(select);
	}
	
});
/**
 * Ria_Club_SetModeratedId
 *
 * @class       Ria_Club_SetModeratedId
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      MegaDevel
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Club_SetModeratedId = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 'Club',
                event: 	'get_moderated_id'
	},

	initialize: function(options){
		this.setOptions(options);
		this.parent(options);
	},

	onGetResponse: function(jsonObj){
             var moderated_event_id = jsonObj.moderated_event_id;
             if(moderated_event_id){
                  $('moderated_event_id').set('value',moderated_event_id);
             }else{
                  $('moderated_event_id').set('value',0);
             }
               if($('create_album_button')){
                     $('create_album_button').setStyle('display','block');
               }
	}
});
/**
 * Ria_Tags_getTags
 *
 * @class       Ria_Tags_getTags
 * @copyright   2009 RIA-MUTIMEDIA
 * @license     GNU GPL v2
 * @author      Marvin
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Tags_getTags = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'tags',
		event: 		'gettags'
	},

	initialize: function(options){       
        

        options.str_tag = ($defined(options.str_tag)) ? options.str_tag : 0;

		this.setOptions(options);
		this.parent(options);
	},

	onGetResponse: function(jsonObj){
		var tags = jsonObj.tags;
		var needle = jsonObj.needle;
		
		if(tags != false) {
			var hash = new Hash(tags);		
			
		
			var autocomplete = $('autocomlete');
			if($chk($('completer'))) {
				$('completer').destroy();
			}
			var select = new Element('select',{'size':5,'id':'completer','onclick':'selectTag();'});
			select.setStyle('width', '519px');
			
			hash.each(function(item,index){
				var option  = new Element('option',{'value':index});
				str = item.replace(needle,"<b>" + needle + "</b>" )
				option.set('html',str);
				option.inject(select);
			});
			select.inject(autocomplete);
			
		} else {
			if($chk($('completer'))) {
				$('completer').destroy();
			}       
		}
	}
});
/**
 * Ria_News_GetEventsToReview
 *
 * @class      Ria_News_GetEventsToReview
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_News_GetEventsToReview = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'news',
		event: 		'get_event'
	},

	initialize: function(options){
                this.loading();
                 this.setOptions(options);
                this.parent(options);
  	},

	onGetResponse: function(jsonObj){
                var other_user_events = jsonObj.other_user_events;
                var user_events = jsonObj.user_events;
                var moderated_club_id = jsonObj.moderated_club_id;
                var lastValueUser = 0;
                var lastValueOther = 0;
               
                var select = $('select_event');
		select.empty();
                var optionDefault  = new Element('option',{'value':0, 'html':'Выберите событие'});
                 optionDefault.inject(select);
		
                if(other_user_events.length){                   
			other_user_events.each(function(item){
				var option  = new Element('option',{'value':item.EventDBO.event_id, 'html':item.EventDBO.name,'onclick':'$("addUserEventSimple").setStyle("display","none");return false;'});
				option.inject(select);
			});

                        lastValueOther = other_user_events.length;
                        
		}
                
                if (moderated_club_id){
                    $('moderated_club_id').set('value',moderated_club_id);
                }else{
                    $('moderated_club_id').set('value',0);

                }
                 lastValue = lastValueUser*1 +lastValueOther*1;

             select.set('disabled', false);
             
             //hiding creating photo report button if it is visible
               if($('create_album_button')){
                    $('create_album_button').setStyle('display','none');
               }
             $('moderated_event_id').set('value',0);

	},

	loading: function(){
		var select = $('select_event');
		//select.set('disabled', 'disabled');
		select.empty();
		var option  = new Element('option',{'html':'Loading ...'});
		option.inject(select);
	}
              
    

});


/**
 * Ria_News_GetClubsToReview
 *
 * @class      Ria_News_GetClubsToReview
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_News_GetClubsToReview = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'news',
		event: 		'get_club'
	},

	initialize: function(options){
                this.loading();
                 this.setOptions(options);
                this.parent(options);
  	},

	onGetResponse: function(jsonObj){
                var clubs = jsonObj.clubs;
                var user_clubs = jsonObj.user_clubs;
                var lastValueUserClub = 0;
                var lastValueOtherUserClub = 0;
                var select = $('select_club');
		select.empty();

		
                    var optionDefault  = new Element('option',{'value':0, 'html':'Выберите заведение:'});
                    optionDefault.inject(select);                   

                    if(clubs.length){
			clubs.each(function(item){
				var option  = new Element('option',{'value':item.club_id, 'html':'&nbsp;&nbsp;-'+item.name,'onclick':'$("createClub").setStyle("display","none");return false;'});				
				option.inject(select);
			});
                        lastValueOtherUserClub = clubs.length;
                    }
                        clubsLength = lastValueUserClub + lastValueOtherUserClub;                  
			select.set('disabled', false);
                        
                        // обнуляем список событий
                         var eventSelector = $('select_event');
                        eventSelector.empty();
                    var optionDefaultEvent  = new Element('option',{'value':0, 'html':'Список событий'});
                        optionDefaultEvent.inject(eventSelector);
                        //hiding creating photo report button if it is visible
                          if($('create_album_button')){
                                $('create_album_button').setStyle('display','none');
                          }
		
	},

        

	loading: function(){
		var select = $('select_club');
		//select.set('disabled', 'disabled');
		select.empty();
		var option  = new Element('option',{'html':'Loading ...'});
		option.inject(select);
	}
              
    

});


/**
 * Ria_Login_Enter
 *
 * @class       Ria_Login_Enter
 * @copyright   Yuriy Horbenko
 * @license     GNU GPL v2
 * @author      Yuriy Horbenko
 * @requires    Ria_Core_Ajax_JsonRequest
 *
*/
var Ria_Login_Enter = new Class ({

	Extends: Ria_Core_Ajax_JsonRequest,

	options: {
		target: 	'login',
		event: 		'enter'
	},

	initialize: function(options){
            options.saveMe = ($('saveMe').checked) ? 1 : 0;
                this.setOptions(options);
                this.parent(options);


  	},

	onGetResponse: function(jsonObj){

          var  user= jsonObj.user;
          var password = jsonObj.pasw;
          var reload = jsonObj.reload;

          if (reload==1){
            //  window.location.reload();
           location.href='mypage';
          }
          if (user==0 && password==0){
           $('console_l').set('html',"Пользователь с таким E-mail адресом не зарегистрирован.<a href='registration/'> Хотите зарегистрироваться?</a>");
           $('console_l').setAttribute('class','important');
           $('console_l').setAttribute('style','display:block;margin-top:5px;');
           $('input_password').setAttribute('style', "display:none;");

        }
        if (user==0 && password==1){
             $('console_l').set('html',"Введен неправильный пароль.");
             $('console_l').setAttribute('class','important');
             $('console_l').setAttribute('style','display:block;margin-top:5px;');
             $('input_password').setAttribute('style', "display:block;");
           }
        else {
            
            if(user[0]['auth_type']==3 && password ==2){
                
                     $('console_l').set('html',"Для указанного E-mail адреса необходим пароль.");
                     $('console_l').setAttribute('class','important');
                     $('console_l').setAttribute('style', "display:block;margin-top:5px;");
                     $('input_password').setAttribute('style', "display:block;");
                
            }
        }
       
       
    }

});


