var callbacks = {
	gb_success: function(data, $form) {
		$form.hide();
		$('#gbSuccess').show();
	}
};
function __(){
    try {
        console.log(__.caller, arguments);
    } 
    catch (e) {
    }
}

$(function(){
	
	$("a.lightbox").lightBox();
	
	$('a.button[href="#submit"]').click(function(){
		$(this).parents('form').submit();
		return false;
	});
	
	$('table.table tr:odd').addClass('alt');
	
	$('#placesMenu .placesMenuItemC').hover(function(){
		$(this).addClass('placesMenuItemC-opened');
	}, function(){
		$(this).removeClass('placesMenuItemC-opened');
	});
	
	if ($.browser.msie && $.browser.version <= 8) {
		$('#placesMenu .placesSubMenu a').each(function(){
			$(this).append('<i class="nw">&nbsp;</i><i class="ne">&nbsp;</i><i class="se">&nbsp;</i><i class="sw">&nbsp;</i>');
		}).hover(function(){
			$(this).addClass('hover');
			$(this).find('.ne,.nw,.se,.sw').css('display', 'block');
		}, function(){
			$(this).removeClass('hover');
			$(this).find('.ne,.nw,.se,.sw').css('display', 'none');
		})
	}
	
	var $pn_items = $('.placesMenu-prev, .placesMenu-next');
	
	setInterval(function(){
		
		var $items = $('.placesMenu-prev:not(.notActive), .placesMenu-next:not(.notActive)');
		$items.animate({opacity: 0.3}, 300, function(){ $items.animate({opacity: 1}, 300) });
		
	}, 2000);
	
	$pn_items.click(function(){
		
		var $places_menu = $('#placesMenu');
		var next = false;
		var index = parseInt($places_menu.attr('places:current'));
		var count = $places_menu.find('.placesMenuItemC').length;
		if (!index) index = 0;
		
		if ($(this).hasClass('placesMenu-next')) {
			/*$places_menu.find('.placesMenuItemC:first').hide();
			$places_menu.find('.placesMenuItemC:last').show();*/
			index++;
			next = true;
		}
		else {
			/*$places_menu.find('.placesMenuItemC:last').hide();
			$places_menu.find('.placesMenuItemC:first').show();*/
			index--;
		}
		
		if (index + 10 >= count) {
			index = count - 10;
			$('.placesMenu-next').addClass('notActive');
			$('.placesMenu-prev').removeClass('notActive');
		}
		
		if (index <= 0) {
			index = 0;
			$('.placesMenu-prev').addClass('notActive');
			$('.placesMenu-next').removeClass('notActive');
		}
		
		$places_menu.attr('places:current', index);
		
		if (next) {
			$places_menu.find('.placesMenuItemC:eq(' + (index - 1) + ')').hide();
			$places_menu.find('.placesMenuItemC:eq(' + (index + 9) + ')').show();
		}
		else {
			$places_menu.find('.placesMenuItemC:eq(' + (index) + ')').show();
			$places_menu.find('.placesMenuItemC:eq(' + (index + 10) + ')').hide();
		}
		
		return false;
	});
	
	$('.vote-vote').click(function() {
		var $form = $(this).parents('form');
		
		var vts = $form.find('input[type="radio"]').is(':checked');
		
		if( !vts ) {
			alert('Вы должны выбрать один из вариантов голосования!');
			return false;
		}
		
		var form_field = $form.serialize();
		form_field = form_field + '&type=polling';
		$.ajax({
			url : $form.attr('config:uri'),
			type : $form.attr('config:method'),
			dataType : 'json',
			data : form_field,
			success : function( data ) {
				var box = $('<table></table>').hide();
				if( data ) {
					for(var i = 0; i < data['votes'].length; i++) {
						var vote = data['votes'][i];
						var div = $("<tr>"+
							"<td class=\"vote-title\" id=\"title"+i+"\"></td>"+ 
							"<td class=\"vote-line\"><img src=\"/i/b.gif\" id=\"vote"+i+"\"/></td>"+
							"<td class=\"vote-per\" id=\"per"+i+"\">%</td>"+
							"</tr>")
						
						$('#per'+i, div).html( vote.percent + '%' );
						$('#title'+i, div).html( vote.title );
						$('#vote'+ i, div).width( vote.width === 0 ? 1 : vote.width );
						box.append(div);
					}
					box.append('<tr><td class="vote-title" >Всего проголосовавших:</td><td colspan="2">'+data['poll'].hits+'</td></tr>');
					$form.find('.work-form').empty().append(box);
					box.show();
					$('.vote-vote').remove();
				}
			}
		})
		return false;
	});
	
	// ------------------------------------------------------------------------------------------------
	var $sw = $('.comingSoon');
	var $slider = $sw.find('ul');
	var $timer = null;
	
	function slide( $tool, $i ) {
		$slider.stop().animate({marginTop:-146 * $i}, $i == 0 ? 300 : 800, function() {
			$tool.removeClass('current');
			$tool.eq($i).addClass('current');
		});
	}
	$sw.find('.tools a').click(function() {
		var $tools = $sw.find('.tools a'), $i = $tools.index(this), current;
		$tools.removeClass('current');
		$tools.eq($i).addClass('current');
		
		clearInterval($timer);
		slide( $tools, $i );
		
		$slider.data('current_slide', $i);
		
		$timer = setInterval(function() {
			current = $slider.data('current_slide');
			slide( $tools, current);
			if( current == $slider.find('li').length-1 ) 
				current = -1;
			
			$slider.data('current_slide', current+1);	
		}, 6000);
	});
	
	$sw.find('.tools a:eq(0)').click();
	
	// ------------------------------------------------------------------------------------------------
	
	$('.gallery-buttonNext, .gallery-buttonPrev, .gallery-previewItem, .gallery-buttonLast, .gallery-buttonFirst').live('click', function(){
		
		var $gallery = $(this).parents('.gallery');
		var $previews_container = $gallery.find('.previewsC');
		var $previews = $previews_container.find('.previews');
		var visible = $previews_container.attr('gallery:visible');
		var $bigs = $gallery.find('.gallery-bigItems');
		var current = parseInt($gallery.attr('data-current'));
		current = current ? current : 0;
		
		var is_next = $(this).hasClass('gallery-buttonNext');
		
		if ($(this).hasClass('gallery-previewItem')) {
			current = $(this).index();
		}
		else if ($(this).hasClass('gallery-buttonFirst')) {
			current = 0;
			$previews.animate({marginLeft: 0});
		}
		else if ($(this).hasClass('gallery-buttonLast')) {
			current = $previews.find('a').length - 1;
			$previews.animate({marginLeft: -67*(current-visible+1)});
		}
		else {
			if (is_next) 
				current++;
			else 
				current--;
		}
		
		var is_first = false;
		var is_last = false;
		
		if (current <= 0) {
			current = 0;
			is_first = true;
		}
		
		if (current >= $previews.find('a').length - 1) {
			current = $previews.find('a').length - 1;
			is_last = true;
		}
		
		$gallery.attr('data-current', current);
		
		var $current = $previews.find('a:eq('+current+')');
		$previews.find('a').removeClass('gallery-previewItem-active');
		$current.addClass('gallery-previewItem-active');
		/*$gallery
			.find('.galleryCurrent').attr('src', $current.attr('href'))
			.end()
			.find('.galleryCurrentC').attr('href', $current.attr('rel'));*/
		
		$bigs.find('a img').remove();
		$bigs.find('a:eq('+current+')').append('<img src="'+$current.attr('href')+'"/>');
		
		if (is_last || is_first)
			return false;
		
		var offset = $current.position().left;
		
		if (offset >= (3 - 67 + $previews_container.width()))
			$previews.animate({marginLeft: '-=67'});
		else if (offset <= 0)
			$previews.animate({marginLeft: '+=67'});
		
		return false;
	});
	
	$('form.validate').validate();
	
	$('a.ajax').each(function(){
		$(this).attr('id', 'ajax-link-'+Math.round(Math.random()*10000));
	})
	.click(function(){
		
		var $a = $(this);
		$.ajax({url: $a.attr('href')+'block/', dataType: 'html'})
			.success(function(data){
				$a.hide().after('<div class="ajax-content">'+data+'<div class="clear" style="height:20px;"></div></div>')
				$("a.lightbox").lightBox();
			});
		
		return false;
	});
	
	$('form.ajax').submit(function(){
        $form = $(this);
        if ($form.hasClass('validate') && !$form.hasClass('xv-valid'))
                return false;

        var callback_success = $form.attr('form:success');
		var callback_error = $form.attr('form:error');

        $.ajax({
            type: $form.attr('form:method'),
            dataType: 'json',
            url: $form.attr('form:url'),
            data: $form.serialize(),
            beforeSend: function(){
            },
            success: function(data){
                if (data) {
					var callback = callback_success;
					if (!data.success)
						callback = callback_error;
					
					var context = window;
					var func = callback;
					
					if (callback.indexOf('.') != -1) {
						var ns = callback.split('.');
						func = ns.pop();
						
						for (var i = 0; i < ns.length; i++) {
							context = context[ns[i]];
						}
					}
					return context[func].apply(this, [data, $form]);
				}
            }
        });

        return false;
    });
});
