$(function()   {
  var DivContent = $("#pane");  

	if ( (document.location.search != "") 
		|| (document.location.hash.substring(1, 6) == 'poisk') )
		{
	         DivContent.html( '<div id="yandex-results-outer" onclick="return {encoding: ' + "'', language: 'ru'}" + '"></div>' ).after('<script type="text/javascript" src="http://site.yandex.net/load/site.js" charset="utf-8"></script>');
	         $.getScript( "http://site.yandex.net/load/site.js" );
	         //document.location )
	         //'http://' + document.domain + '/poisk.htm?' + document.location.search.substring(1)
	           //     + ' #yandex-results-outer' );
	         //BeginSearch();
	         //document.location.search = '';
	         return true;
	}
	 if (document.location.hash.substring(1) == '') 
	 {
		 ShowOkno( 'text-main', '' );
	 }
	 else if ( (DivContent.attr( 'rel' ) == 'galereya_i_opisaniye' )
	 		 && (document.location.hash.substring(1) == 'galereya_i_opisaniye') )
	 {  
	 	DivContent.hide( "slow" , function () { DivContent.show( "slow" ) } );
	 	return true;
	 }
	 else  {
		ShowOkno( document.location.hash.substring(1), '' );
	 }   
	
	if ( $('body').css( 'rel') != 'complete' )
	 { 	AddClickShowOkno( document.body ); }
	 
	$( 'EMBED' ).each(function() {
	    	$(this).replaceWith( '<object type="application/x-shockwave-flash"' 
      						+ 'data="'+ this.src 
      						+ '" width="100%" height="100%" wmode="transparent" >'
    						+ '<param name="quality" value="high">'
    						//+ '<param name="wmode" value="opaque">'
    						+ '<param name="wmode" value="transparent">'
    						+ '<param name="movie" value="' + this.src + '">'
   							+ '</object>' );
	});
	
	$( 'a[href*=order-calculation]' ).fancybox( {
		'padding': 0,
		//'autoScale': true,
		'centerOnScroll' : true,
		'transitionIn': 'elastic',
		'transitionOut': 'elastic',
		'title': 'Заполните все поля и нажмите кнопку отправить!',
		//'autoDimensions': true,
		'width': 1000,
		'height': 900,
		'type': 'iframe'
	  } );


		
	if ( $("#zag").length == 0 )
    { DivContent.before( '<div id="zag" display="none" > <h1>Ждите, загружаю страницу</h1> </div>');
    }
 
    //$('body').css('font-size', 14);
    
}) // $(document).ready

function createRequestObject() {
  if (typeof XMLHttpRequest === 'undefined') {
    XMLHttpRequest = function() {
      try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
        catch(e) {}
      try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
        catch(e) {}
      try { return new ActiveXObject("Msxml2.XMLHTTP"); }
        catch(e) {}
      try { return new ActiveXObject("Microsoft.XMLHTTP"); }
        catch(e) {}
      throw new Error("This browser does not support XMLHttpRequest.");
    };
  } 
  return new XMLHttpRequest();
  
}
    // Get ajax by adress
var title_doc, menu_hide, DivPopMenu;

function GetAjax( m_adress, file_ext ){ 
     var Res, str_addon, str_body, str_preload;
     var str = document.location.pathname.substring( 1 );
     var i = str.search( '/' ) + 1, j = str.search( 'htm' );
     
      str = '/' + str.substring( 0, i ); // + '#' +  str.substring( i, j -1);

      m_adress = ( m_adress.search('/') > 0 ? m_adress.substring( m_adress.search('/')+1 ): m_adress);
      str_addon = ( m_adress.search('/') > 0 ? m_adress.substring( m_adress.search('/')+1 ): m_adress);
     
      try {
          
            Res = createRequestObject();
          
            Res.open("GET", 'http://' + document.domain + str + m_adress + file_ext, false );
            Res.setRequestHeader('Content-Type', 'text/html; charset=windows-1251');
            Res.send( null );

            if ( Res.readyState != 4 ) { return 'не удалось загрузить данные!'; } // данные не загружены
            
            if ( Res.status != 200 ) { return "Ошибка №" + Res.status + " при загрузке страницы " + m_adress ; } // статус не ОК
            
            
            str = Res.responseText;
            
		    if ( file_ext == ".htm" ) {
		    
		    	 i = Res.responseText.search( "<title>" ) + 7;
		    	 j = Res.responseText.search( "</title>" );
		    	 
		         title_doc = str.substring( i, j);
		         
			     i = str.search( "body { background" );
			     if (i == -1) { 
			        i = str.search( "body { }" );
			     };
			    
			     j = str.search( "</style>" );
			
			     str = ".body-pane" + str.substring( i+4, j+8 ).replace(/\.[apt]\d+/gi, "$&_" + str_addon  );
			
			     str = '<style type="text/css"> \n <!-- /* Стили Артели для Сайткрафт версии 4.31 */ \n' + str ; 
			
			     i = Res.responseText.search( "preload" );
			     j = Res.responseText.search( "//-->" );
			     if (i > -1) { // подключаю предзагрузку картинок
				    		
				
					 str_preload = Res.responseText.substring( i+19, j-4 ); 
					 str_preload = str_preload/* .replace( /\s/gm, ' ' ) */.replace( /"b\d+/gi, "$&_" + str_addon  );
					 
				     str_preload = '<script type="text/javascript">\n'
						    		 //' function '/* preloadimage' + str_addon + */ + '() {'
						    		+ str_preload
						    		//+ '\n  }'
						    		+  ' \n </script>';  
					  //document.write(  str_preload );	
					  //$('body').attr( 'onload', str_preload);				  
					  //$(document).ready( str_preload );
					
			     }
			     else {  str_preload = '';  }
			     
			     i = Res.responseText.search( "<div" );
			     j = Res.responseText.search( "</body>" ) - 16;
			     str_body =  Res.responseText.substring( i, j ).replace( /[apt]\d+(?=\s|\")/g, "$&_" + str_addon  );
			     //alert( str_body )
			     
			     if (str_preload > '') {
			       str +=   str_body.replace( /name="b\d+/gi, "$&_" + str_addon  ).replace( /'b\d+/gi, "$&_" + str_addon  ) /*  + str_preload */ + ' </div>'; 
			       //alert(str)
			       
			     }
			     else { str += (str_body + ' </div>'); }
			     
			     
			   }
			   else { str = Res.responseText; }
	 }
     catch( e ) {
   
              //	alert( e );
              str = e.description;
     } 
return str;      
}

var go_history = 0;

function ShowOkno( id, zag, this_ref ) {
  var DivContent = $("#pane");  
  var Button, Button_name;

  if ( $(this_ref).children().is('img') )
   {	Button =   $(this_ref).children();
   		Button_name = Button.attr( 'name' );
   }
   
  id = ( id.search('/') > 0 ? id.substring( id.search('/')+1 ): id);

  if ( (DivContent.attr( 'rel' ) == id) 
  		|| ( (document.location.hash == '#') && (DivContent.attr( 'rel' ) == 'text-main') ) 
  		|| (id == '') || (id == 'php') 
  		|| ( (DivContent.attr( 'rel' ) == 'galereya_i_opisaniye') && (id == 'galereya_i_opisaniye') ) )
   { return false; } 
       
  if (id != 'text-main')
    { document.location.hash = id; }
  else if ( (document.location.hash != '') && (id == 'text-main') )
     { document.location.hash = '' }
  
  $("#zag").show();
  if (this_ref)
  {
	  Down_button = $( '.down_button' );
	  if (Down_button.length > 0) {
	  
		  Button_ref = $( 'a[href*=' + Down_button.attr( 'rel' ) + ']'); 
		  Button_ref.each( function () { this.onmouseout = function onmouseout(event) { over_off(); } } ); 
	 
		  Button_down = Button_ref.children();  
		  Button_down.attr( 'src', Button_down.attr( 'rel' )  );
		  
		  Down_button.html( '' ).attr( 'rel', '' ).removeClass( 'down_button' );
	
	  }
	  
	  if ( (Button_name != null) && ( id.search('menu') > 0 ) && ( document.wb_pre[Button_name] ) )
	   {
	    
	    	if (document.wb_normal) {
	    	 Button.attr( 'rel', document.wb_normal );
	    	}
	    	this_ref.onmouseout = function onmouseout(event) {  };
	    	$(this_ref).mouseout( ); 
	   }
   } 

     DivContent.hide( "slow" , function () { 
     
     							//title_doc = zag;
     							$("#zag").show();
                                
                                if (id.search('prajs') > 0 ) {
		  
		 							DivContent.load( 'http://' + document.domain + '/' +  id + '.htm');
								 }    
								 else if  ( id.search('galereya') > -1 )
								 {
								    //header('Content-Type: text/html; charset=windows-1251', TRUE);
								   jQuery.ajaxSetup ( {cache: false, content: 'text/html; charset=windows-1251'});
								   try 
								   {
									     DivContent.load( 'http://' + document.domain + '/'								    				+ 'show_galereya.php', { random : Math.random()*99999, template :  id },
								    				function ( responseText, textStatus, XMLHttpRequest ) { 
								    						 //if (textStatus != 'success' ) { return true; } 
     						 								
																	//$("#viewer").removeClass("js-disabled");
																
															  //create new container for images
																$("<div>").attr("id", "container").css({ position:"relative"}).width( ($(".wrapper").length > 4) ? $(".wrapper").length * 56 : $("#viewer").width() ).height( '320px').appendTo("div#viewer").css("left", 0);
															  	
																//add images to container
																$(".wrapper").each(function() {
																	$(this).appendTo("div#container");
																});

															});
									}
									catch(e) { alert(e) } 
								 } 
								 else {                                                      
                                	DivContent.html( GetAjax( id, ".htm" ) );
                                 }
                                
                           divFirst = $('div:first', DivContent);
                           wDiv		= divFirst.width( );
                           divFirst.width( '100%' ).find('[style*="width:' + wDiv + '"]').width( '100%' ); 
 
                            DivContent.addClass( 'body-pane' );
                            
     					DivContent.show( "fast",  function () {
							
							 $("#zag").hide();
                            AddClickShowOkno( DivContent );
                            	
                            // запоминаю для поиска потом нажатой кнопки
                            DivContent.attr( 'rel', id );
                            if ( id.search('menu') > 0 )
                           	 { DivContent.addClass( 'down_button' ); }
                            
                         /*       if (!window.onpopstate) {
							    	window.onpopstate = function(event) {
							    	  
							    	      go_history = 1;
										  ShowOkno( document.location.hash.substring(1), '' );
										  
									  }
								}
							    
if ( go_history == 0 ) {
							         window.history.replaceState( id, (zag > '' ? zag : title_doc ) );
							         
							    } 
*/  
							    go_history = 0;

                            yaCounter1207626.hit( document.location.href, null, null )
                      } );
              });   

                 
                             
return false;
};

function LoadPageToDiv( name_page, str_ext, NameDiv, main_page ) {
  var DivForLoad = $( "#" + NameDiv );
  var str;
  
  if ( DivForLoad.length == 0 ) return; 
   
  name_page = ( name_page.search('/') > 0 ? name_page.substring( name_page.search('/')+1 ): name_page );
  main_page = ( ( (main_page) && (main_page.search('/') > 0) ) ? main_page.substring( main_page.search('/')+1 ): main_page );
  
  if (DivForLoad.attr( 'rel' ) == name_page) {
  	   DivForLoad.slideUp( "slow" , function () { 
     
                                DivForLoad.html( '' );
                                DivForLoad.attr( 'rel', '' );
                                                            
                     });   
   return; 
  }
    str = GetAjax( name_page, str_ext );
                                
  if (!str) {
   if (DivForLoad.attr( 'rel' ) == main_page) { return; }
   str = GetAjax( main_page, ".htm" );
   name_page = main_page;
  }
  
  DivForLoad.slideUp( "slow" , function () { 
     
                                DivForLoad.html( str );
                                DivForLoad.attr( 'rel', name_page );
                                                            
                     });   


     DivForLoad.slideDown( "slow",  function () {

                            AddClickShowOkno( DivForLoad );
                          
                            // yaCounterXXXXXX.hit(url, title, referer)
                      } );
return false;
};


function AddClickShowOkno( parent_this ) {

 $('a', parent_this ).not( 'a:has(img[alt=referal])' ) //referal означает ссылки, которые не надо менять
 .each( function () {
 					 var str = this.href;
 					 var i, j;
 					   j = str.search( '.htm' );
 					   i = str.search( document.domain); 

 					   if (i == -1) {
 					          i = str.search( 'http://' );
 					          if (i == -1) {
 					            i = 1;
 					          }
 					          else { i+= + 4 };
 					   }
 					   
 					   if ( j > 0 ) {
 						    str = str.substring( i, j );
 						    i = str.search( '/' );
 							while (i > 0) {
 								 str = str.substring( i+1, j );
 								 i = str.search( '/' );
 							}
 								
 							if ( str.substring( 0, 4 ) == 'menu' )
 						 	{
 						 		this.onclick = function(){ LoadMenuToDiv( this.rel, '.htm', this );  return false; } ; 
 						 	}
 						 	else if ( str.substring( 0, 7 ) == 'popmenu' )
 						 	{	
 						 	   var DivForLoad =  $("<div>").attr("id", "pane_" + str).addClass( "pop-pane"); 
 						 	   var html_menu = GetAjax( str, '.htm' );
   
                            	$(this).append( DivForLoad );
                            	DivForLoad.html( html_menu ); 
                            	AddClickShowOkno( DivForLoad );
                            	
 						 	    $(this).mouseover( function onmouseover(event) { 
							 						 	  DivPopMenu = $( "#pane_" + this.rel );
							 						 	  clearTimeout( menu_hide);
							 						 	  
							 						 	  if (DivPopMenu.hasClass( 'pop_menu' ))
							 						 	   { return true;}
							 						 	  
							 						 	  $( '.pop_menu' ).removeClass( 'pop_menu' ).hide( );							 						 	  
							 						 	  DivPopMenu.addClass( 'pop_menu' ).slideDown( "fast" );
							 						 	  
						 						 	  	  return true; 
						 						   } );
						 		$(this).mouseleave(	function () { 
		 						 	  							  DivPopMenu = $( "#pane_" + this.rel );
		 						 	  							  clearTimeout( menu_hide);
								 						 	      
								 						 	      menu_hide = setTimeout( function(){ 
									 						 	  		DivPopMenu.removeClass( 'pop_menu' ).hide( )
									 						 	  }, 1000 )
									 			   });			   
						 						   
						 		this.onclick = function(){ return false;};
						 		
						 		DivForLoad.mouseover( function onmouseover(event) { 
						 				if ( DivPopMenu && ( DivPopMenu.attr('id') == $(this).attr('id') ) )
						 				 { clearTimeout( menu_hide); 
						 				   DivPopMenu = null;	}
						 				return true; } );
						 				
						 		DivForLoad.mouseleave( function mouseleave(event) { 
						 		
						 								  clearTimeout( menu_hide);
							 						 	  DivPopMenu = $(this);
							 						 	  menu_hide = setTimeout( function(){ 
														 						 	  DivPopMenu.removeClass( 'pop_menu' ).hide( )
														 						 	  }, 1000 );
							 						 	  
						 						 	  	  return true; 
						 						   } );				  
 						 	}
 							else
 						 	{ if ( this.target != "_blank" )
 						 		{ this.onclick = function(){ ShowOkno( this.rel, this.title, this  ); return false; };
 						 		  this.rel = str; 
 						 		}
 						 		else { this.onclick = function(){ 
 						 								$.fancybox.showActivity();
 						 								$.ajax( {
																type	: "GET",
																cache	: false,
																url		: this.href,
																success: function(data) {
					 						 								$.fancybox(  {
																				'padding': 5,
																				//'autoScale': true,
																				'centerOnScroll' : true,
																				'transitionIn'	 : 'elastic',
																				'transitionOut'	 : 'elastic',
																				'title'			: 'Для закрытия окна шелкните мышкой за его пределами!',
																				 'content' 			: data, 
																				'autoDimensions': true,
																				'overlayShow': true
																			  } );
																			 }
																});
													return false; } ;
 						 		}
 						 	}
 						 
 							this.rel = str;
 					   }
 					  else if ( str.search( '.php' ) > 0)
 					  {  this.onclick = function(){ 
/*
 					  								var DivContent = $("#pane"); str_ref = this.href;
 					  								DivContent.hide( "slow" , function () { 
				 					  								DivContent.post( str_ref );
																	  DivContent.show();
																	  //document.location.hash = 'php';
																	 } );
*/
													/*$.fancybox.showActivity();
 						 								$.ajax( {
																type	: "POST",
																cache	: true,
																url		: this.href,
																success : function(data) {
					 						 					*/			$.fancybox(
{
																				'padding': 5,
																				//'autoScale': true,
																				'centerOnScroll' : true,
																				'transitionIn'	 : 'elastic',
																				'transitionOut'	 : 'elastic',
																				'href'			: this.href,
																				'type'			: 'iframe',
																				'title'			: 'Для закрытия окна шелкните мышкой за его пределами!',
																				// 'content' 			: data, 
																				'autoDimensions': true,
																				'overlayShow': true
																			  } );
															//				 }
															//	});
 					  								return false; };
 					  	 this.rel = str;							
 					  }
 					  else {
 					  
 						    str = str.substring( i+4 );
 						    i = str.search( '/' );
 							while (i > 0) {
 								 str = str.substring( i+1 );
 								 i = str.search( '/' );
 							}
 							
 					      if ( str.substring(0,1) == '#'){
 					      
 					        this.onclick = function(){ LoadPrice( this.rel, this.title );  return false; } ; 
 					        this.rel = str.substring(1); 					       
 					        
 					        return ;
 					     }
 					  } 					  
					  if (!this.title)
					   { this.title = ( $(this).children().is('img')  ? $(this).children().attr( 'title' ) : $(this).text() ); 				
					   }	   
 					});
 		
 		$( 'a[href*=youtube]' ).click(function() {
			  $.fancybox({
				'padding'		: 0,
				'autoScale'		: false,
				'transitionIn'	: 'elastic',
				'transitionOut'	: 'elastic',
				'title'			: this.title,
				'width'			: 1080,
				'height'		: 780,
				'centerOnScroll' : true,
				'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
				'type'			: 'swf',
				'swf'			: {
				   	 'wmode'		: 'window',
				   	 'quality'		: 'high',
					 'allowfullscreen'	: 'true'
				}
			  });
		  return false;
		 });			                                 
    $(parent_this).css( 'rel', 'complete' );

}

function LoadPrice( id, zag ) {

	 var DivContent = $("#pane");
	 
	 $("#zag").html( "Ждите, загружаю страницу" );
	 DivContent.hide( "slow" , function () {
	 			DivContent.load( 'http://' + document.domain + '/' +  id + '.htm',  
    				 			function () { 
        				 			$('div', DivContent).css( 'height', 700 );
        				 			DivContent.show( "slow",  function () {
        				 								$("#zag").html( '<h2>' + zag + '</h2>' );
        				 								document.location.hash = id;
        				 								document.title = zag
		 							});
		 						});
	 			});
	 return false; 
}

function LoadMenuToDiv( name_page, str_ext, this_ref ) {
  var DivForLoad = $( "#pane_" + name_page );
  var str; 
  var Button = $(this_ref).children();
  var Button_name = Button.attr( 'name' );
  
  if ( DivForLoad.length == 0 ) return; 
   
  name_page = ( name_page.search('/') > 0 ? name_page.substring( name_page.search('/')+1 ): name_page );
  
  if (DivForLoad.attr( 'rel' ) == name_page) {
  	   document.wb_normal = Button.attr( 'rel' ) ;
  	   //$(this_ref).mouseout( function () { over_off(); } );
  	   this_ref.onmouseout = function onmouseout(event) { over_off(); };
  	   
  	   DivForLoad.slideUp( "slow" , function () { 
     
                                DivForLoad.html( '' ).attr( 'rel', '' ).removeClass( 'down_menu' );
                                
                                                                                            
                     });   
       
       return false; 
  }
                                
  Down_menu = $( '.down_menu' ).slideUp( "slow" );
  if (Down_menu.length > 0) {
  
	  Button_ref = $( 'a[href*=' + Down_menu.attr( 'rel' ) + ']'); 
	  Button_ref.each( function () { this.onmouseout = function onmouseout(event) { over_off(); } } ); 
 
	  Button_down = Button_ref.children();  
	  Button_down.attr( 'src', Button_down.attr( 'rel' )  );
	  
	  Down_menu.html( '' ).attr( 'rel', '' ).removeClass( 'down_menu' );

  }
  
  if ( document.wb_pre[Button_name] ) {
    
    	if (document.wb_normal) {
    	 Button.attr( 'rel', document.wb_normal );
    	}
    	this_ref.onmouseout = function onmouseout(event) {  };
    	$(this_ref).mouseout( ); 
   }
    
   str = GetAjax( name_page, str_ext );
   
   DivForLoad.slideDown( "slow",  function () {

                                
                            DivForLoad.html( str ); 
                            AddClickShowOkno( DivForLoad );
                            DivForLoad.attr( 'rel', name_page );
                           	DivForLoad.addClass( 'down_menu' );
                                                       // yaCounterXXXXXX.hit(url, title, referer)
                      } );
return false;
};



