(function($) {

  $(document).ready(function(){
	
	$('ul#behind_menu_links li').eq(0).css({'width': '83px', 'margin-right': '10px'});
	$('ul#behind_menu_links li').eq(1).css({'width': '116px', 'margin-right': '10px'});
	$('ul#behind_menu_links li').eq(3).css({'width': '80px'});
	
	/* ДОПОЛНТЕЛЬНЫЕ ССЫЛКИ */
	$('#top_links li').hover(function(){
		$(this).addClass('iehover');
	}, function(){
		$(this).removeClass('iehover');
	});
    
  
  
  
    $('.visTable>tbody>tr>td>strong>span').parent().parent().css({
      textAlign:'left'
    });
	$('#top_menu li').hover (
	      function() { 
			$(this).addClass('iehover');
			$('ul > li',this).show();
			//$(this).find('ul').show();
		  },
           function() { 
			$(this).removeClass('iehover');
			$('ul > li',this).hide();
		  }
		)
    $.datepicker.regional['ru'] = {
      closeText: 'Закрыть',
      prevText: '&#x3c;Пред',
      nextText: 'След&#x3e;',
      currentText: 'Сегодня',
      monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
      'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
      monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
      'Июл','Авг','Сен','Окт','Ноя','Дек'],
      dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
      dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
      dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
      dateFormat: 'yy-mm-dd', firstDay: 1,
      changeMonth: true,
      changeYear: true,
      minDate:'-5Y',
      maxDate:'+1',
      isRTL: false};
    $.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional['ru']));
    $("#datepicker").datepicker();$("#datepicker_2").datepicker();
    $('#l_arrow_scroll, #r_arrow_scroll').live('mouseout',function() {
      $('#gallery_slide div').stop();
    })

    $('#share_dynamic').bind('click',function() {
      var type = $('#type_graph').val();
      var period = $('#graph_form input:checked').attr('id');
      if(period == 'period') {
        period = $('#datepicker_2').val()+':'+$('#datepicker').val();
      }
      
      $('#graph_img').html('<img src="/application/includes/images/ajax-loader.gif" id="loader_gif">');
      setTimeout(function() {
        $('#graph_img img').attr('src','/pages/drawGraph/'+type+'/'+period+'/share/');
        $('#graph_img img').removeAttr('id');
      },1000);
    })
    
    $('#nav_dynamic').bind('click',function() {
      var type = $('#type_graph').val();
      var period = $('#graph_form input:checked').attr('id');
      if(period == 'period') {
        period = $('#datepicker_2').val()+':'+$('#datepicker').val();
      }
      
    $('#graph_img').html('<img src="/application/includes/images/ajax-loader.gif" id="loader_gif">');
      setTimeout(function() {
        $('#graph_img img').attr('src','/pages/drawGraph/'+type+'/'+period+'/nav/');
        $('#graph_img img').removeAttr('id');
        },1000);
    })
    
    $('#show_button').bind('click',function() { 
      var period = $('#graph_form input:checked').attr('id');
      var type = $('#type_graph').val();
      var share_nav = $('.share_nav:checked').attr('id');
      
      if(share_nav == 'share_dynamic') share_nav = 'share';
      else share_nav = 'nav';
      
      if(period == 'period') {
        period = $('#datepicker_2').val()+':'+$('#datepicker').val();
      }
      $('#graph_img').html('<img src="/application/includes/images/ajax-loader.gif" id="loader_gif">');
      setTimeout(function() {
        $('#graph_img img').attr('src','/pages/drawGraph/'+type+'/'+period+'/'+share_nav);
        $('#graph_img img').removeAttr('id');
        },1000);
    });
    
    $('#table_button').bind('click',function() {
      var offset = $(this).offset();
      var period = $('#graph_form input:checked').attr('id');
      var type = $('#type_graph').val();
      var share_nav = $('.share_nav:checked').attr('id');
      //var heightShadow = $('body').innerHeight();
	  var heightShadow = $('body').height();
	  var widthShadow = $('body').width();
	  
      if(share_nav == 'share_dynamic') share_nav = 'share';
      else share_nav = 'nav';
      
      if(period == 'period') {
        period = $('#datepicker_2').val()+':'+$('#datepicker').val();
      }
	  
      $.ajax({
        url: '/pages/drawGraph/'+type+'/'+period+'/'+share_nav+'/false/',
        type:'GET',
        success: function(response) {
		  $('#divShadow').css({
			'height':heightShadow+'px',
			'width': widthShadow+'px'
			}).show();
		 $('#tableGraph_block').html(response).css({
			'margin-top':(offset.top-100)+'px',
			'position':'absolute',
			'z-index':'999'
			});
        $('#tableGraph_block').show(); 
        },
		error: function(error,textStatus,errorThrown) {
			alert(textStatus);
			alert(errorThrown);
		}
      });
    });
    
	$('#calculation').live('click',function() {
		var type = $('#type_graph').val();
		var pid = $('#page_pid').val();
		var offset = $(this).offset();
		var heightShadow = $('body').innerHeight();
		var widthShadow = $('body').width();
		$.ajax({
			url: '/pages/calculation/'+type+'/'+pid+'/',
			type:'GET',
			cache:false,
			success: function(response) {
			  $('#tableGraph_block').css({
				'margin-top':(offset.top-100)+'px',
				'position':'absolute',
				'z-index':'1000'
				});
			  $('#divShadow').css({
				'height':heightShadow+'px',
				'position':'absolute',
				'z-index':'999',
				'width': widthShadow+'px'
				});
			  $('#divShadow').show();
			  $('#tableGraph_block').html(response);
			  $('#tableGraph_block').show();
			}
	   });
	})
	
    $('.close_table').live('click',function() {
      $('#divShadow').hide();
      $('#tableGraph_block').hide();
    })
    
    $('#dynamic_change').bind('change',function() {
        var value = $(this).val();
        $.ajax({
		  beforeSend: function(){
			$('.table_loader_ico img').addClass('act_loader');
		  },
		  type: 'GET',
          url: '/main/ajax_table/'+value+'/',
          cache: false,
          success: function(response){
            $('#dynamic_main').remove();
            $('#dynamic_change').after(response);
          },
		  error: function(a, b, c){
			alert('Произошла ошибка. Если это повториться, пожалуйста, напишите об этом администратору сайта.');
		  },
		  complete: function(){
			$('.table_loader_ico img').removeClass('act_loader');
		  }
        });
    });
	
    $('#l_arrow_scroll').live('mouseover',function() {
      var offset = parseInt($('#gallery_slide div').css('left'));
      if (offset!==0) {
      $('#gallery_slide div').animate({
        left:'0px'
      },13000);
    }
    })

    $('#r_arrow_scroll').live('mouseover',function() {
      var scroll_img_count = $('#gallery_slide img').length;
      var scroll_img_width = $('#gallery_slide img').width();
      var scroll_div_width = scroll_img_count*scroll_img_width-$('#gallery_slide img').width()+60;

      var offset = parseInt($('#gallery_slide div').css('left'));

      if(Math.abs(offset) !== scroll_div_width) {
        $('#gallery_slide div').animate({
          left:'-'+scroll_div_width+'px'
        },15000);
      }
    })
    


    $('#shadow').live('click',function() {
      closeWin('gallery_ajax');
      $('.window_open').hide();
    });
	
	$('.brown_box').prepend('<div class="top_corner">&nbsp;</div>');
	$('.brown_box').prepend('<div class="bottom_corner">&nbsp;</div>');

	// Выоста у нижнего корнера
	var brbox_ih = $('.brown_box').innerHeight()-47;
	$('.brown_box .bottom_corner').css('top', brbox_ih);
	
//	var brbox_pad = $('.brown_box').css('padding-left');
//	$('.brown_box .top_corner').css('left', '-' + brbox_pad);

	


/*    $('.test').bind('click',function() {
      //return alert($(this).attr('alt'));
      $('#text_oprosa img').attr('src','/application/includes/images/01.jpg');  
      $(this).src='/application/includes/images/02.jpg';
      document.forms['opros_form'].oformlenie.value= $(this).attr('alt');
    })*/

    
/*    $('#text_oprosa img').attr('src','/application/includes/images/01.jpg');
    object.src='/application/includes/images/02.jpg';
    document.forms['opros_form'].oformlenie.value= $(object).attr('alt');*/
    
	$('.visTable tr:first').addClass('tr_first');
	
  });
  
	
  
  
  // = = = ajax gallery
  var current_elem = 0;
  $('.gallery_block img').live('click',function(){
    scrollTo(0,0);
    current_elem = $('.gallery_block img').index(this);
	id = $(this).attr('alt');
	//$('#bigImage').attr('src','/application/includes/images/ajax-loader.gif');
	replace_img(id);
	var heightShadow = $('body').innerHeight();
    var widthGallery = $('#gallery_ajax').innerWidth();
    $('#shadow').css('height',heightShadow+'px');
	$('#shadow').show();
	$('#gallery_ajax').css('margin-left','-'+parseInt(widthGallery/2)+'px');	
	$('#gallery_ajax').show();
	$('#choise select').css('visibility','hidden');
    $('#gallery_slide div').css('left','0px');
    
  });
  
  // = = left scroll arrow
  $('#left_arrow').live('click',function(){
    //$('#bigImage').attr('src','/application/includes/images/ajax-loader.gif');
    if(current_elem<=0){
	  current_elem = $('.gallery_block img').length;
	}
	current_elem--;
    id = $('.gallery_block img').eq(current_elem).attr('alt');
	replace_img(id);
  });
  
  // = = right scroll arrow
  $('#right_arrow').live('click',function(){
    count = $('.gallery_block img').length;	
    //$('#bigImage').attr('src','/application/includes/images/ajax-loader.gif');
    if(current_elem >= count-1){
	  current_elem = -1;
	}
	current_elem++;
    id = $('.gallery_block img').eq(current_elem).attr('alt');
	replace_img(id);
  });
  
  

  closeWin = function(id) {
    $('#'+id).hide();
    $('#shadow').hide();
    $('#choise select').css('visibility','visible');
  }

  replace_img = function(id) {
    $('#bigImage').attr('src','/application/includes/img/b/'+id+'.jpg');
    $('#inside_image_text').load('/application/image_note/'+id);
  }
  
  replaceBigImg = function (key/*,sost*/)
  {
/*    if (sost=='back') key--;
    else if (sost=='forward') key++;
    document.getElementById("bigImage").src=images_array[key][0];
    document.getElementById("inside_image_text").innerHTML=images_array[key][1];*/

    $('#bigImage').attr("src","/application/includes/img/b/"+key+".jpg");
    $('#inside_image_text').innerHTML=images_array[key][1];
    
    key--;
    $('#left_arrow').attr("onclick","replaceBigImg("+(key)+")");
    key++;    
    $('#right_arrow').attr("onclick","replaceBigImg("+(key)+")");
  } 
  
  replace_img_m = function() {
    var next_id;
    var id = $('#main_img img').attr('title');
    $('#gallery_slide img').each(function(i) {
      if($(this).attr('title') == id) next_id = (i+1);
    })
    replace_img($('#gallery_slide img').get(next_id).title);
  }

  check = function(id) {
    value = $('#'+id).val();
    if (value != '') 
      return 1;
    else {
      $('#'+id+'_error').html('Проверьте введенные данные').show();
      return 0;
    }
  }

  show_shadow = function()
  {
    document.getElementById('divShadow').style.display = 'block';
    document.getElementById('divShadow').style.width=$('body').innerWidth()+'px';
    document.getElementById('divShadow').style.height=$('body').innerHeight()+15+'px';
    document.getElementById('faq_block').style.display = 'block';
    document.getElementById('faq_block').style.top = '35%';
    document.getElementById('faq_block').style.left = ($('body').innerWidth()-517)/2+'px';    
  }
  
  close_form = function()
  {
    document.getElementById('divShadow').style.display = 'none';
    document.getElementById('faq_block').style.display = 'none';
  }
  rezume = function()
  {
    if (document.getElementById('rezume').style.display == 'block')
    {
      document.getElementById('rezume').style.display = 'none';
    }
    else
    {
      document.getElementById('rezume').style.display = 'block';
    }

  } 
  img_arch = function(object,name,spanid)
  {
//    alert (name);
    $('#'+spanid+' img').attr('src','/application/includes/images/01.jpg');
    object.src='/application/includes/images/02.jpg';
//    document.forms['opros_form'].name.value=$(object).attr('alt');
//    $('#oformlenie').value=$(object).attr('alt');
    $('#'+name).attr("value",$(object).attr('alt'));
  
  }
  
  send_form = function(name) {
    var error = 0;
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    $('form[name="'+name+'"] *[required]').each(function() {
      if ($(this).val()=='' || $(this).val()=='Код' || $(this).val()=='Номер' || $(this).val()=='Введите код с картинки'  || $(this).val()=='Тема которую вы хотите обсудить с консультантом') {
        error ++;
        $(this).addClass('notValid');
      } else if($(this).attr('name') == 'email' && !reg.test($(this).val())) {
        error ++;
        $(this).addClass('notValid');
      }
      else $(this).removeClass('notValid');
    });
    if(error !== 0) {
      if (name=='seminar') $('form[name="'+name+'"]').prepend('<div class="error_seminar">Проверьте введеные данные</div>');
      else
        $('form[name="'+name+'"]').prepend('<div class="error">Проверьте введеные данные</div>');
    } else {
      $('form[name="'+name+'"]').submit();
    }
  }

})(jQuery);

images_array = $('.gallery_block img');