(function($) {

	$(document).ready(function() {

		// -- определяем высоту #shadow
		$('#shadow').css('height', $('body').height()+'px');
		
		if ($.browser.msie && $.browser.version == 6) {
		  height = $('#leftContentBlock').height()
		   $('#rightContentBlock').css('height',height+'px');
		}
		
		// -- устанавливаем ширину ul в #ajaxGalleryBlock
		$('#preview ul').css('width', ($('#scroll li').length*150)+'px');		
		
		$('#shadow').live('click', function() {
			$('#ajaxGalleryBlock').fadeOut();
			$('#pic_editor').fadeOut();
			$('#coctail_show').remove();
			$('#oneParticipant').remove();
			$(this).hide();
		});
		
		// -- скроллер в фотогаллерее
		var sliderCounter = 0;
		$('#rightArrow').live('click',function() {
			var widthPreview = $('#scroll li img').width();
			if((Math.ceil(($('#scroll ul a').length/2)-1)) == sliderCounter) {
				sliderCounter = 0;
			} else {
				sliderCounter++;
			}
			$('#scroll ul').animate({
				marginLeft :'-'+2*(sliderCounter*widthPreview)+'px'
			}, 400);
		});
		
		$('#leftArrow').live('click',function() {
			var widthPreview = $('#scroll li img').width();
			if(sliderCounter !== 0) {
				sliderCounter--;
			} else {
				sliderCounter = Math.ceil(($('#scroll ul a').length/2)-1);
			}
			$('#scroll ul').animate({
				marginLeft:'-'+2*(sliderCounter*widthPreview)+'px'
			}, 400);
		});
		
		// -- клик на фото превью в основном документе
		$('.ajaxGallery a').removeAttr('onClick').live('click', function() {
			var doc    = document.documentElement || document.body;
			var elLeft = Math.round(doc.scrollLeft+(doc.clientWidth-560)/2)+'px';
			var elTop  = Math.round(doc.scrollTop+(doc.clientHeight-505)/2)+'px';
			var id = $(this).attr('href').substring(1);
			$('#shadow').css('height', $('body').height()+'px').show();
			$('#ajaxGalleryBlock').css({'top':elTop,'left':elLeft}).fadeIn();
			$('#ajaxGalleryBlock #mainImg img')
				.attr("src","/application/includes/img/b/"+id+".jpg")
				.attr("onClick","nextImg("+id+");");
			$('#mainNote').load('/all/loadImageNote/'+id);
			return false;
		});
		
		// -- основное меню
		$('#menu_block li').mouseover(function() {
			this.flag = true;
			setTimeout('showMenu("'+$(this).attr('id')+'");', 5);
		});
		$('#menu_block li').mouseout(function() {
			this.flag = false;
			setTimeout('hideMenu("'+$(this).attr('id')+'");', 5);
		});
		
		if($.browser.msie && $.browser.version == '6.0') {
			$('#menu_block li.preactive').next().addClass('next');
		}
		
		// $('#menu_block li.deep_2').mouseover(function(event) {
			// $(this).addClass('hover');
			// $(this).parent().addClass('mouseover');				
		// });
		// $('#menu_block li.deep_2').mouseout(function(event) {
			// $(this).removeClass('hover');
			// $(this).parent().removeClass('mouseover');			
		// });
		
		
		// -- select begin
		var flag  = false;
		var index = 8;
		$('div.select').each(function() {
			var select = $('div.select[id='+$(this).attr('id')+']');
			select.css('z-index', index--);
			select.find('div.input').live('click', function() {
				$('div.select').removeClass('clicked');
				$(this).parent().addClass('clicked');
				$('div.select ul').hide();
				var ul = select.find('ul');
				ul.css('display', ((ul.css('display')=='block')?'none':'block'));
				$(this).blur();
				flag = true;
			});
			select.find('li a').live('click', function() {
				var select_div = $(this).parent().parent().parent();
				select_div.find('div.input').text($(this).text());
				var input = select_div.find('input');
				var input_id = input.attr('id');
				input.attr('value', $(this).text());
				select_div.find('ul').toggle();
				select_div.find('li').removeClass('active');
				$(this).parent().addClass('active').blur();
				select_div.removeClass('clicked');
				flag = true;
				return false;
			});
		});
		
		$('body').live('click', function() {
			if(!flag) {
				$('div.select ul').hide();
				$('div.select').removeClass('clicked');
			}
			flag = false;
		});
		
		$('div.select ul li').live('mouseover', function() {
			$(this).addClass('hover');
		});
		
		$('div.select ul li').live('mouseout', function() {
			$(this).removeClass('hover');
		});
		// -- select end
		$('a.inactive').live('click',function(){return false;})
		
		$('#feedbackForm input,#feedbackForm textarea').focus(function(){
			value = $(this).val();
			title = $(this).attr('title');
			if(value==title) $(this).val(' ');
		})
		$('#feedbackForm input,#feedbackForm textarea').blur(function(){
		    value = $(this).val();
			if(value=='' || value==' ') $(this).val($(this).attr('title'))
		});
		
		//$('.current_contests li:eq(1)').hide();
		
	});
	
	showImg = function(id) {
		var doc    = document.documentElement || document.body;
		var elLeft = Math.round(doc.scrollLeft+(doc.clientWidth-560)/2)+'px'; 
		var elTop  = Math.round(doc.scrollTop+(doc.clientHeight-505)/2)+'px';
		$('#shadow').show();
		$('#ajaxGalleryBlock').css({'top':elTop,'left':elLeft}).fadeIn();
		$('#mainImg').html('<a href="#" onClick="return nextImg('+id+');"><img width="540" height="360" src="/application/includes/img/b/'+id+'.jpg"  /></a>');
	}
	
	replaceImg = function(id, o) {
		$('#mainImg').html('<a href="#" onClick="return nextImg('+id+');"><img width="540" height="360" src="/application/includes/img/b/'+id+'.jpg"  /></a>');
		$('#mainNote').load('/all/loadImageNote/'+id);
		$('#imgLinks').html('<a href="#" onclick=\'return nextImg('+id+')\' class="rightLink">Вперед</a><a href="#" onclick=\'return prevImg('+id+')\' class="leftLink">Назад</a>');
		return false;
	}
	
	nextImg = function(id) {
		for(var i in photo_ids) {
			if(photo_ids[i] == id) {
				next = parseInt(i)+1;
				if(photo_ids[next] == undefined) {
					next = 0;
				}
				$('#mainImg').html('<a href="#" onClick="return nextImg('+photo_ids[next]+');"><img width="540" height="360" src="/application/includes/img/b/'+photo_ids[next]+'.jpg" /></a>');
				$('#mainNote').load('/all/loadImageNote/'+photo_ids[next]);
				$('#imgLinks').html('<a href="#" onclick=\'return nextImg('+photo_ids[next]+')\' class="rightLink">Вперед</a><a href="#" onclick=\'return prevImg('+photo_ids[next]+')\' class="leftLink">Назад</a>');
				break;
			}
		}
		return false;
	}
	prevImg = function(id) {
		for(var i in photo_ids) {
			if(photo_ids[i] == id) {
				next = parseInt(i)-1;
				if(photo_ids[next] == undefined) {
					next = (photo_ids.length-1);
				}
				$('#mainImg').html('<a href="#" onClick="return nextImg('+photo_ids[next]+');"><img src="/application/includes/img/b/'+photo_ids[next]+'.jpg" /></a>');
				$('#mainNote').load('/all/loadImageNote/'+photo_ids[next]);
				$('#imgLinks').html('<a href="#" onclick=\'return nextImg('+photo_ids[next]+')\' class="rightLink">Вперед</a><a href="#" onclick=\'return prevImg('+photo_ids[next]+')\' class="leftLink">Назад</a>');
				break;
			}
		}
		return false;
	}
	

	hideMenu = function(nameid) {
		var sm = document.getElementById(nameid);
		if(!sm.flag) {
			var o  = $('#'+nameid);		
			o.removeClass('hover');
			o.parent().removeClass('mouseover');
			if($.browser.msie && $.browser.version == '6.0') {
				o.find('ul').parent().next().removeClass('next');
				if(!o.hasClass('preactive')) {
					$('#menu_block li.preactive').next().addClass('next');
				}
			}
		}
	}
	
	showMenu = function(nameid) {
		var sm = document.getElementById(nameid);
		if(sm.flag) {
			var o  = $('#'+nameid);		
			o.addClass('hover');
			o.parent().addClass('mouseover')
			if($.browser.msie && $.browser.version == '6.0') {
				o.find('ul').parent().next().addClass('next');
				if(!o.hasClass('preactive')) {
					$('#menu_block li.preactive').next().removeClass('next');
				}
			}
		}
	}

	closeGallery = function() {
		$('#ajaxGalleryBlock').fadeOut();
		$('#shadow').hide();
	}
	in_array = function(needle, haystack, strict) {
		var found = false, key, strict = !!strict;
		for (key in haystack) {
		  if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
			found = true;
			break;
		  }
		}
		return found;
	}
	// обратная связь 
	$('#feedbackForm,#faqForm').live('submit',function(){
	  $(this).find('.isAjaxLoad').remove();
	  $(this).append('<input type="hidden" class="isAjaxLoad" name="isAjaxLoad" value="1" />');
	  $(this).removeClass('wrongCaptcha');
	  var vals = new Array('Представьтесь','Email','Ваш вопрос','Код с картинки');
	  error = '';
	  $(this).find('input,textarea').removeClass('requireInput');
	  inputs = $(this).find('input[required="true"],textarea[required="true"]');
	  
	  for(i=0;i<inputs.length;i++){
	    if(in_array($(inputs[i]).val(),vals)){ 
			error = error + "\n"+$(inputs[i]).attr('title');
			$(inputs[i]).addClass('requireInput');
		}
	  }  
	  if(error!='') {alert("Некоторые поля не заполнены:"+error);return false;}
	  
	  // проверка на ввод каптчи
	  $.ajax({
			url:   $(this).attr('action'),
			type:  'POST',
			data:  $(this).serialize(),
			cache: false,
			success: function(response) { 
				alert(response);
				//if(strcmp(response,'Ваше сообщение было успешно отправлено') === 0) location.reload();//document.getElementById('feedbackForm').reset();
			}
		}); 
	  
	  
	  return false;
	})
	
	$('.recalls_form').live('submit',function(){
	  var vals = Array('Представьтесь','Ваш город','Email','Телефон','Ваш комментарий','Введите код','Заголовок работы','Введите код с картинки');
	  error = '';
	  $(this).find('input,textarea').removeClass('requireInput');
	  inputs = $(this).find('input[required="true"],textarea[required="true"]');
	  
	  for(i=0;i<inputs.length;i++){
	    if(in_array($(inputs[i]).val(),vals)){ 
			error = error + "\n"+$(inputs[i]).attr('title');
			$(inputs[i]).addClass('requireInput');
		}
	  }  
	  if(error=='') return true;
	  alert("Некоторые поля не заполнены:"+error);
	  return false;
	})
	
	// visitors_auth_form
	$('#questioning_members_top_panel .auth_but').live('click',function(){
	  $(this).addClass('auth_but_clicked');
	  $('#questioning_members_top_panel .reg_but').removeClass('reg_but_clicked');
	  $("#visitors_auth_form").show();
	  $("#visitors_reg_form").hide();
	  return false
	})
	
	$('#questioning_members_top_panel .reg_but').live('click',function(){
	  $(this).addClass('reg_but_clicked');
	  $('#questioning_members_top_panel .auth_but').removeClass('auth_but_clicked');
	  $("#visitors_auth_form").hide();
	  $("#visitors_reg_form").show();
	  return false
	})
	

})(jQuery);

function in_array(needle, haystack, strict) {   // Checks if a value exists in an array
	var found = false, key, strict = !!strict;
	for (key in haystack) {
	  if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
		found = true;
		break;
	  }
	}
	return found;
}
function is_array( mixed_var ) {
	return ( mixed_var instanceof Array );
}
function empty( mixed_var ) {
	return ( mixed_var === "" || mixed_var === 0   || mixed_var === "0" || mixed_var === null  || mixed_var === false  ||  ( is_array(mixed_var) && mixed_var.length === 0 ) );
}
function strcmp ( str1, str2 ) {    // Binary safe string comparison
	var size1 = str1.charCodeAt ( 0 );
	var size2 = str2.charCodeAt ( 0 );
	return ( ( size1 == size2 ) ? 0 : ( ( size1 > size2 ) ? 1 : -1 ) );
}
