// Проверка на ишака

var IEfixGlobal = {};
var IE = false;
var IEVersion = 6;

if (!jQuery.support.opacity) { 
	IE = true; 
	IEVersion = parseFloat( navigator.appVersion.replace(/^(?:.*?\W+)?MSIE ([0-9]+\.[0-9]+);.*?$/ig, '$1') );
}

// IE bugfix #1 ( скрыть все селекты, перед отображением всплывающих блоков )
var IEfixGlobal_allShowedSelects = $( 'ie_fix' );

function IEfixGlobal_hideSelects() {
	if ( IE ) {
		IEfixGlobal_allShowedSelects.css( 'visibility', 'hidden' )
	}
}; 
function IEfixGlobal_showSelects() {
	if (IE) {
		IEfixGlobal_allShowedSelects.each( function( i, elem ){
			$this = $( elem );
			$this.css( 'visibility', $this.data( 'visibility' ) )
		});
	}
};


/*--------------------------------------------------*/

	$( document ).ready( function(){
		
		// IE PNG FIX -----------------------------
		if ( IE && IEVersion < 7 ) {
			$('img').each( function( i, elem ){
				if ( /\.png$/i.test( elem.src ) ) {
					$elem = $( elem );
					var width = $elem.width()+'px';
					var height = $elem.height()+'px';
					elem.style.background = 'none';
					elem.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+elem.src+'", sizingMethod="crop")';
					elem.src = '../templates/template_1/images/spacer.gif';
					elem.style.width = width;
					elem.style.height = height;
				}
			});
		};
		// END OF IE PNG FIX ----------------------


		if ( IE ) {
			IEfixGlobal_allShowedSelects = $('select').filter( function( i ){
				if ( $( this ).css( 'visibility' ) == 'hidden' ) return false;
				return true;
			}).each( function( i, elem ){
				$this = $( elem );
				$this.data( 'visibility', ( $this.css( 'visibility' ) || 'visible' ) )
			});
		}; 


		/* Преобразование цвета из HEX в RGB */
		function parseColor (color) {
	
			if (color.length != 4 &&
				color.length != 7) {
				return [0,0,0];		
			}; color = color.substr(1);
			
			if (color.length == 3) {
				color = color[0]+color[0]+
						color[1]+color[1]+
						color[2]+color[2];
			}
			
			var R = parseInt(color.substr(0,2),16);
			var G = parseInt(color.substr(2,2),16);
			var B = parseInt(color.substr(4,2),16);
			
			return [R,G,B];
		};


		/** Меню на стартовой */

		var startMenu = $( '#start_menu' );

		if ( startMenu.length ) {
			
			startMenu.children( 'li' ).children( 'a' ).bind({
				'mouseenter': function(e){
					$( this ).parent( 'li' ).addClass( 'active' );
				},
				'mouseleave': function(e){
					$( this ).parent( 'li' ).removeClass( 'active' );
				}	
			});
		}


		/** Слайдшоу на стартовой */

		var startSlideshow = $( '#start-slideshow' );
		
		if ( startSlideshow.length ) { 
			
			/* Настройки */
			var reSwitchSpeed = 1000;
			var reSwitchInterval = 8000;
			var slidesBackgroundColor = '#fff';

			/* Создание маски */
			var mask = $( document.createElement('IMG') );
			mask.one( 'load', function(e){

				var runStartSlideshow = function() {

					var mask = $( this );					

					if ( IE ) { mask.css({'opacity': ''}); }

					if ( (startSlideshow.find( '.slide a' ).length + startSlideshow.find( '.slide img' ).length) > 0 ) {

						startSlideshow.css( 'background-color', mask.css( 'background-color' ) );
						mask.css( 'background-color', 'transparent' );						

						var slideshowOnStart = function() {

							var links = startSlideshow.find( '.slide a' );
							var images = startSlideshow.find( '.slide img' );

							if ( (links.length + images.length) > 1 ) {
			
								if ( links.length ) {
									var img = $( document.createElement( 'img' ) ).attr({
										 'src': links.eq(0).attr( 'href' )
									});
									img.one( 'load', function(){
										if ( images.length ) {
											links.eq(0).parent().css({
												'width': parseInt(this.width)+'px',
												'height': parseInt(this.height)+'px',
												'background-color': slidesBackgroundColor,
												'background-image': 'url('+images.eq(0).attr( 'src' )+')',
												'background-position': 'left top',
												'background-repeat': 'no-repeat'
											});
											images.eq(0).parent().css({ 'visibility': 'hidden' }).remove().insertBefore( '#mask' );
										}
										links.eq(0).parent().css({ 
											'visibility': 'visible' 
										});
										links.eq(0).replaceWith( img.css({ 'opacity': 0 }) );
										img.animate({ 'opacity': 1 }, reSwitchSpeed );
									});
								} else if ( images.length ) {
									images.eq(1).parent().css({
										'width': images.eq(1).width()+'px',
										'height': images.eq(1).height()+'px',
										'background-image': 'url('+images.eq(0).attr( 'src' )+')',
										'background-position': 'left top',
										'background-repeat': 'no-repeat'
									});
									images.eq(0).parent().css({ 'visibility': 'hidden' }).remove().insertBefore( '#mask' );
									images.eq(1).parent().css({ 'visibility': 'visible' });
									images.eq(1).css({ 'opacity': 0 }).animate({ 'opacity': 1 }, reSwitchSpeed);
								}
							}
							setTimeout( slideshowOnStart, reSwitchInterval );
						}; slideshowOnStart();
					}
				};

				if ( IE && IEVersion < 7 ) { 
					runStartSlideshow();
				} else { 
					$( '#mask' ).animate({ 'opacity': 1 }, 200, runStartSlideshow); 
				}
			});

			var maskUrl = $( '#mask' ).css( 'background-image' ).match(/^url\((['"]*)(.+)\1\)$/i);
			if ( maskUrl !== null && typeof maskUrl[2] !== 'undefined' && maskUrl[2] != '' ) {
				mask.attr( 'src', maskUrl[2] );
			} else {
				mask.attr( 'src', '../templates/template_1/images/spacer.gif' );
			}

		}

		/* Всплывающие превьюхи в списках каталога ----------------------------- */
	
		$( '.razd_descr_foto a > img' ).bind({
			'mouseenter': function(e) {
	
				$( '#popup_list_image' ).remove();
				$this = $( this );
	
				$( 'body' ).eq(0).append( 
					$( document.createElement( 'DIV' ) ).attr( 'id', 'popup_list_image' ).append( 
						$( document.createElement( 'IMG' ) ).attr( 'src', $this.attr( 'src' ) ) 
					) 
				);
	
				var popupImage = $( '#popup_list_image' );
				var thisParent = $this.parent('a').parent();
	
				popupImage.css({ 
					'left': ( thisParent.offset().left - ( ( popupImage.outerWidth() - thisParent.outerWidth() ) / 2 ) )+'px',
					'top': ( ( thisParent.offset().top - popupImage.outerHeight() ) + 1 )+'px'
				});
			},
			'mouseleave': function(e) {
				$( '#popup_list_image' ).remove();
			}
		});
	
		/* END OF Всплывающие превьюхи в списках каталога ---------------------- */


		/* Замена SELECT-ов и радиокнопок на графику */
		(function( $ ){
	
		   /**
		 	* Отметить графическую радиокнопку, заданную объектом jQuery
		 	* @return jQuery
		 	*/
			$.fn.checkGraphicRadio = function() {
	
				if ( typeof this.jquery === 'undefined' ) return $( this ).makeGraphicRadios();
	
				var toCheck = this;
				var thisGroup = $( 'div.graph-radio' ).filter( function( i ){
					if ( $( this ).data( 'name' ) == toCheck.data( 'name' ) ) { return true; }
					return false;
				});
				thisGroup.each( function( i, elem ){
					$( elem ).removeClass( 'graph-radio-checked' ).data( 'checked', false );
				});
				toCheck.addClass( 'graph-radio-checked' ).data( 'checked', true );
				var form = toCheck.closest( 'form' );
				if ( form.length ) {
					form.find( "input[name='"+toCheck.data( 'name' )+"'][type='hidden']" ).val( toCheck.data( 'value' ) )
				} else {
					$( "input[name='"+toCheck.data( 'name' )+"'][type='hidden']" ).val( toCheck.data( 'value' ) ).eq(0);
				};
				return this;
			};
	
		   /**
		 	* Заменить стандартные радиокнопки на графические в объекте jQuery
		 	* @return jQuery
		 	*/
			$.fn.makeGraphicRadios = function() {
				
				if ( typeof this.jquery === 'undefined' ) return $( this ).makeGraphicRadios();
				
				/* Замена радиокнопок */
				var allRadios = this.find( 'input[type="radio"]' );
		
				if ( allRadios.length ) {
					
					this.data( 'graphRadios', true );
		
					// Группировка по именам
					var allRadiosByName = {};
					allRadios.each( function( i, radio ) {
						radio = $(radio);
						var name = radio.attr('name');
						if ( typeof allRadiosByName[ name ] == 'undefined' ) {
							allRadiosByName[ name ] = [];
						}; allRadiosByName[ name ][ allRadiosByName[ name ].length ] = radio;
					});
		
					// Создание скрытого Input для каждой группы
					for ( var radioGroup in allRadiosByName ) {
						var isChecked = false;
						var checkedValue = '';
						for ( i=0; i<allRadiosByName[radioGroup].length; i++ ) {
							if ( allRadiosByName[radioGroup][i].is(':checked') ) {
								checkedValue = allRadiosByName[radioGroup][i].val();
								isChecked = true;
								break;
							}
						}; if ( !isChecked ) checkedValue = allRadiosByName[radioGroup][0];
						$( document.createElement('INPUT') ).attr({ 
							'type': 'hidden', 
							'name': radioGroup,
							'value': checkedValue
						}).insertAfter( allRadiosByName[ radioGroup ][ allRadiosByName[radioGroup].length-1 ] );
					}; allRadiosByName = null;
		
					allRadios.each( function( i, radio ) {
	
						$radio = $(radio);
						var isChecked = ($radio.is(':checked'))? true: false
	
						// Поиск лейблов для радиокнопок
						var label = $radio.siblings( 'label' ).filter( function( j ){
							if ( $( this ).attr( 'for' ) == $radio.attr('id') && $radio.attr('id') != null && $radio.attr('id') != '' ) { return true; }
							return false;
						}); 
	
						if ( label.length ) {
							label.bind( 'mousedown', function(){
								if ( !$( '#'+$( this ).attr('for') ).data( 'checked' ) ) {
									$( '#'+$( this ).attr('for') ).checkGraphicRadio();
								}
							});
						};
	
						var newRadio = $( document.createElement('DIV') ).attr({
								'id': $radio.attr('id'),
								'class': 'graph-radio'
							}).data({
								'name': ''+$radio.attr( 'name' ),
								'value': ''+$radio.val(),
								'checked': isChecked
							}).addClass(
								$radio.attr('class')
							).addClass(
								(isChecked)? 'graph-radio-checked': ''
							).css({
								'display': 'block',
								'position': $radio.css('position') | 'relative',
								'float': $radio.css('float') | 'none'
						});
	
						var onclick = $radio.get()[0].getAttribute('onclick');
						// Если к радиокнопке было привязано событие 'click',
						// сохраняем его в data
						if ( onclick != null ) {
							newRadio.add( label ).data( 'onclick', onclick );
						}
						
						// Замена всех радиокнопок
						$radio.replaceWith( newRadio );
	
					});
					
					// Обработка событий click
					$( 'div.graph-radio' ).bind( 'mousedown', function(){
						$( this ).checkGraphicRadio();
					});
				};
				return this;
			};	
	
		   /**
		 	* Заменить стандартные выпадающие списки на графические в объекте jQuery
		 	* @return jQuery
		 	*/
			$.fn.makeGraphicSelects = function() {
		
				if ( typeof this.jquery === 'undefined' ) return $( this ).makeGraphicRadios();
	
				/* Замена SELECT-ов */
				var allSelects = this.find( 'select' );
		
				if ( allSelects.length ) {
					
					this.data( 'graphSelects', true );
	
					IEfixGlobal_allShowedSelects = $( 'ie_fix' );
		
					IEfixGlobal.openedSelect = null;
		
					// Получить выбранный элемент в списке
					var getSelectedIn = function( list ) {
						return list.children('li').filter( function(){
							var _this = $( this );
							if ( _this.data( 'selected' ) === true ) {
								return true;
							}; return false;
						});
					};
		
					// Спрятать все выпадающие списки установив в них класс 'hovered' для выбранных элементов
					var hideAndMakeSelected = function( notThis ) {
						$( 'ul.graph-select-options:visible' ).filter( function( i ){
							if ( typeof(notThis) == 'undefined' || $( this ).get()[0] != notThis.get()[0] ) { return true; }
							return false;
						}).css({'display': 'none'}).each( function( i, obj ){
							obj = $(obj);
							obj.children( 'li' ).removeClass( 'hovered' );
							getSelectedIn( obj ).addClass( 'hovered' );
						});
					}; // То-же самое для IE
					var IE_hideAndMakeSelected = function( notThis ) {
						if ( IEfixGlobal.openedSelect != null ) {
							var list = IEfixGlobal.openedSelect.$list.filter( function( i ){
								if ( typeof(notThis) == 'undefined' || IEfixGlobal.openedSelect.$block.get()[0] != notThis.get()[0] ) { return true; }
								return false;
							});
							if ( list.length ) {
								IEfixGlobal.openedSelect.$list.css({ 'display': 'none' }).detach().appendTo( IEfixGlobal.openedSelect.$block.closest( 'div.graph-select-wrapper' ) );
								IEfixGlobal.openedSelect.$list.children( 'li' ).removeClass( 'hovered' );
								getSelectedIn( IEfixGlobal.openedSelect.$list ).addClass( 'hovered' )
								IEfixGlobal.openedSelect = null;
							};
						}
					};
		
					// Анализ и замена select-ов
					allSelects.each( function( i, select ) {
		
						var $select = $(select);
						var options = $select.children( 'option' );
						var selected = $select.children( 'option:selected' ).eq(0);
		
						// Поиск заранее выбранного элемента в списке
						if ( selected.length ) {
							selected = { 'value': selected.val(), 'text': selected.text() };
						} else {
							if ( options.length ) {
								selected = { 'value': options[0].val(), 'text': options[0].text() };
							} else {
								selected = { 'value': '', 'text': '' };
							}
						};
	
						// Создание нужных тегов
						var graphSelectWrapper = $( document.createElement('DIV') ).attr( 'class', 'graph-select-wrapper' );
						var graphSelect = $( document.createElement('DIV') ).attr( 'class', 'graph-select' );
						var selectDroplist = $( document.createElement('UL') ).attr( 'class', 'graph-select-options' );
		
						// Заполнение элементов в список
						options.each( function( j, opt ){
							var $opt = $( opt );
							var newOpt = $( document.createElement('LI') ).data({ 'value': $opt.val(), 'selected': ($opt.val() == selected.value)? true: false }).text( $opt.text() ).addClass( ($opt.val() == selected.value)? 'hovered': '' );
							if ( typeof $opt.attr('onclick') !== 'undefined' ) {
								newOpt.attr( 'onclick', $opt.attr('onclick') );
							}; selectDroplist.append( newOpt );
						});
		
						// Сборка всего этого в кучу
						var newGraphSelect = graphSelect.attr({
							'id': $select.attr('id')
						}).addClass(
							$select.attr('class')
						).css({
							'width': $select.outerWidth()+'px',
							'position': $select.css('position') | 'relative',
							'float': $select.css('float') | 'none',
							'text-align': 'left'
						}).html( 
							$( document.createElement('SPAN') ).css({
								'display': 'block',
								'float': 'left',
								'width': '1px'
							}).text( selected.text )
						).append( 
							$( document.createElement('DIV') ).attr( 'class', 'arrow' ) 
						).append( 
							$( document.createElement('INPUT') ).attr({
								'type': 'hidden', 
								'name': $select.attr('name'), 
								'value': selected.value
							}) 
						);
						$select.replaceWith( newGraphSelect );
						var span = newGraphSelect.children('span').eq(0);
						var spanWidth = (newGraphSelect.width()-newGraphSelect.children('div.arrow').eq(0).innerWidth()-parseInt(span.css('padding-left')|0)-parseInt(span.css('margin-left')|0))+'px';
						span.css({
							'overflow': 'hidden',
							'width': spanWidth
						});
						newGraphSelect.wrapAll( graphSelectWrapper );
						graphSelect.after( selectDroplist ).after( $( document.createElement('DIV') ).attr( 'class', 'clear_both' ).append( $( document.createElement('SPAN') ) ) );
	
					});
		
					// Подгон ширины выпадающих списков
					this.find( 'ul.graph-select-options' ).each( function( j, elem ){
						elem = $(elem);
						prev = elem.prevAll( 'div.graph-select' ).eq(-1);
						elem.css({
							'width': ((prev.outerWidth() > elem.outerWidth())? prev.innerWidth()+'px': 'auto')
						});
					});
					
					// Установка обработчиков событий на выпадающие списки
					this.find( 'ul.graph-select-options' ).children('li').bind({
						'mouseenter': function( e ){
							var $this = $( this );
							$this.addClass( 'hovered' );
							var ch = $this.parent( 'ul.graph-select-options' ).children( 'li' ).filter( function( i ){
								if ( $( this ).get()[0] != $this.get()[0] ) return true;
								return false;
							}).removeClass( 'hovered' );
						},
						'mousedown': function( e ){
							if ( e.which == 1 ) {
								var $this = $( this );
								var thisUL = $this.parent( 'ul' );
								var thisULPrev;
								if ( IE ) { thisULPrev = IEfixGlobal.openedSelect.$block; } 
								else { thisULPrev = thisUL.prevAll( 'div.graph-select' ).eq(-1); }
								var input = thisULPrev.children( 'input' ).eq(0);
								var hasValue = input.val();
								input.val( $this.data( 'value' ) );
								if ( hasValue != $this.data( 'value' ) ) {
									input.trigger( 'change' );
								};
								thisULPrev.children( 'span' ).eq(0).text( $this.text() );
								getSelectedIn( thisUL ).data( 'selected', false );
								if ( IE ) {
									$this.data( 'selected', true );
									IE_hideAndMakeSelected(); 
								} else { 
									$this.addClass( 'hovered' ).data( 'selected', true );
									thisUL.css({'display': 'none'}); 
								}
							}
						}
					});
		
					// Отображение/скрытие выпадающих списков 
					this.find( 'div.graph-select' ).bind( 'mousedown', function( e ){
		
						if ( e.which == 1 ) {
		
							if ( IE ) { // Если ишак
		
								IE_hideAndMakeSelected( $( this ) );
		
								if ( IEfixGlobal.openedSelect == null ) {
									IEfixGlobal.openedSelect = {
										$block : $( this ),
										$list : $( this ).closest( 'div.graph-select' ).nextAll( 'ul.graph-select-options' ).eq(0) 
									}; 
								}; 
								
								if ( IEfixGlobal.openedSelect.$list.css( 'display' ) == 'none' ) {
									IEfixGlobal.openedSelect.$list.detach().appendTo( $( 'body' ).eq(0) );
									IEfixGlobal.openedSelect.$list.css({ 
										'display': 'block', 
										'left': parseInt( IEfixGlobal.openedSelect.$block.offset().left )+'px',
										'top': ( parseInt( IEfixGlobal.openedSelect.$block.offset().top ) + IEfixGlobal.openedSelect.$block.outerHeight() )+'px' 
									});
								} else {
									IEfixGlobal.openedSelect.$list.css({ 
										'display': 'none', 
										'left': '0px', 
										'top': '0px' 
									}).detach().appendTo( IEfixGlobal.openedSelect.$block.closest( 'div.graph-select-wrapper' ) );
									IEfixGlobal.openedSelect.$list.children( 'li' ).removeClass( 'hovered' );
									getSelectedIn( IEfixGlobal.openedSelect.$list ).addClass( 'hovered' );
									IEfixGlobal.openedSelect = null;
								}
		
							} else { // Если нормальный браузер
		
								var drop = $( this ).closest( 'div.graph-select' ).nextAll( 'ul.graph-select-options' ).eq(0);
		
								if ( drop.length ) {
									if ( drop.css('display') == 'none' ) {
										hideAndMakeSelected( drop );
										drop.css({'display': 'block'});
									} else {
										hideAndMakeSelected();
									}
								}
							}
						}
					});
		
					// Скрыть все выпадающие списки, если был клик где-нибудь в документе
					$( document ).bind( 'mousedown', function( e ){
						if ( !$( e.target ).closest( 'ul.graph-select-options' ).length && !$( e.target ).closest( 'div.graph-select' ).length ) {
							if ( IE ) { // Если ишак
								IE_hideAndMakeSelected();
							} else { // Если нормальный браузер
								hideAndMakeSelected();
							}
						}
					});
		
				};
				return this;
			};
	
		})( jQuery );
	
		// !!! Вызов замены <select> и <input type=radio> во всем документе
		//$( 'body' ).makeGraphicRadios();
		//$( 'body' ).makeGraphicSelects();


	});

/*--------------------------------------------------*/

function high(which2){
theobject=which2
highlighting=setInterval("highlightit(theobject)",80)
}
function low(which2){
clearInterval(highlighting)
which2.filters.alpha.opacity=40
}
function highlightit(cur2){
if (cur2.filters.alpha.opacity<100)
cur2.filters.alpha.opacity+=10
else if (window.highlighting)
clearInterval(highlighting)
}

function baza(clipart) {
if (screen.height < 730){
	windop = window.open("foto.html?"+clipart+"","foto","width=600,scrollbars=1,resizable=1");
	windop.focus();
	  }
else {
windop = window.open("foto.html?"+clipart+"","foto","height=550,width=600");
windop.focus();
}
}
function prew_pic(clipart) {
	windop = window.open("foto.html?"+clipart+"","uvelich","scrollbars=1,resizable=1,menubar=1");
	windop.focus();
}
function Help(name) {
	windop = window.open("help/"+name+".php","help","height=270,width=350,scrollbars=1,resizable=1");
		windop.focus();
}

function novost(fail,papka,h,w) {
if (screen.height < 730){
	windop = window.open(""+papka+"/"+fail+".html","news","width=400,scrollbars=1,resizable=1,menubar=1");
	windop.focus();
	  }
else {
windop = window.open(""+papka+"/"+fail+".html","news","height=300,width=400,scrollbars=1,resizable=1,menubar=1");
windop.focus();
}
}

function menuover(obj)
{
//obj.style.cursor="hand";
obj.className="menuover";
//obj.all.tags('A').item(0).style.color="#522020";
}

function photoover(obj)
{
//alert(obj);
var TABLE = document.getElementById(obj);
TABLE.getAttributeNode('bgcolor').value = "";
//obj.style.cursor="hand";
//obj.className="photoover";
//obj.all.tags('A').item(0).style.color="#522020";
}

function menuout(obj)
{
obj.className="menuout";
//obj.all.tags('A').item(0).style.color="#1E6A54";
}

function menuclick(obj)
{
window.location.href=obj.all.tags('A').item(0).href;
}


function ch_class(id, cl_name)
{
document.getElementById(id).className = cl_name;
}

//скрыть-показать див
function showHideDiv(div_id){
div = document.getElementById(div_id);
div.style.display = (div.style.display == 'none') ? 'block' : 'none';
}
//скрыть див
function hideDiv(div_id){
document.getElementById(div_id).style.display = 'none';
}
//поменять картинку
function showImg(id, srс1, src2){
obj = document.getElementById(id);
obj.src = (obj.src.indexOf(srс1) != -1)? src2: srс1;
}
	
function vkl_zel(id, kv1){
document.getElementById(id).className = kv1;
}	

function vkl_grey(id, grey){
document.getElementById(id).className = grey;
}	

function display(id){
obj = document.getElementById(id);
if(obj)
obj.style.display = "block";
}

function hide(id){
obj = document.getElementById(id);
if(obj)
obj.style.display = "none";
}

function cs(id, theClass){
obj = document.getElementById(id);
if(obj)
obj.className = theClass;
}

//установка куки
function setCookie(name, value){
	document.cookie = name+"="+escape(value)+";path=/";
}

function view_foto(pid,rid,view){
	windop = window.open("../foto.php?pid="+pid+"&rid="+rid+"&view="+view,"uvelich","width=700,height=600,status=1,resizable=1,scrollbars=1");
	windop.focus();
}

