jQuery.noConflict();
// т.к. используется php jquery библиотека (jslib.php) и она конфликтует с jQuery - используем решение с http://docs.jquery.com/Using_jQuery_with_Other_Libraries
// т.е. загружаем инициализацию на (document).ready и заменяем стандартную функцию $ на jQuery
//$(document).ready(function () {

//var popWindow; // переменная для окна аудиоплеера

if (document.getElementsByClassName == undefined) {
	document.getElementsByClassName = function(className)
	{
		var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
		var allElements = document.getElementsByTagName("*");
		var results = [];

		var element;
		for (var i = 0; (element = allElements[i]) != null; i++) {
			var elementClass = element.className;
			if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
				results.push(element);
		}

		return results;
	}
}


// определение типа браузера
// if ($is.IE) {....} или if ($is.IE>6) {....} или if ($is.Opera<9) {....}
(function(){ // определение типа браузера
var ua = navigator.userAgent, av = navigator.appVersion, v, i;
$is={};
$is.Opera = !!(window.opera && opera.buildNumber);
$is.WebKit = /WebKit/.test(ua);
$is.OldWebKit = $is.WebKit && !window.getSelection().getRangeAt;
$is.IE = !$is.WebKit && !$is.Opera && (/MSIE/gi).test(ua) && (/Explorer/gi).test(navigator.appName);
$is.IE6 = $is.IE && /MSIE [56]/.test(ua);
$is.IE5 = $is.IE && /MSIE [5]/.test(ua);
$is.Gecko = !$is.WebKit && /Gecko/.test(ua);
$is.Mac = ua.indexOf('Mac') != -1;
for (i in $is) if (!$is[i]) $is[i]=NaN;
if (!$is.IE5) v = (ua.toLowerCase().match(new RegExp(".+(?:rv|it|ra|ie)[\\/: ]([\\d.]+)"))||[])[1];
switch (true) {
    case ($is.WebKit): v=parseInt(v, 10);$is.WebKit=v=v>599?4:v>499?3:v>399?2:1;break;
    case ($is.Opera): $is.Opera =v=v||9;break;
    case ($is.Gecko): $is.Gecko =v=v.substr(0,3)||1.8;break;
    case ($is.IE): $is.IE =v= window.XMLHttpRequest ? 7 : (/MSIE [5]/.test(av)) ? (/MSIE 5.5/.test(av))?5.5:5 : 6;
    };
$is.verb = v;
$is.ok = !!($is.Opera>=9 || $is.IE>=6 || $is.Gecko || $is.WebKit>2);
$is.debug = /&debug$/.test(location.search);
})();


// т.к. в IE8 jQuery('#lava li .selected').width(); работает неправильно, используем этот метод
 function getElementWidth(elem) {
	/* if (ns4) {
		var elem = getObjNN4(document, elem);
		return elem.clip.width;
	} else { */
		if(document.getElementById) {
		//if(document.getElementsByClassName) {
			var elem = document.getElementById(elem);
			//var elem = document.getElementsByClassName(elem);
		} else if (document.all){
			var elem = document.all[elem];
		}
	 	//if (op5) {
	 	if ($is.Opera==5) {
			xPos = elem.style.pixelWidth;
		} else {
			xPos = elem.offsetWidth;
		} 
		return xPos;
	//}
}


jQuery(document).ready(function () {

// если мы на основной странице с двумя фреймами, то не выполнять скрипт, т.к. никаких элементов здесь нет кроме фреймов
 if ((parent.frames.length == 0) && (document.location.href.indexOf('video/index.php') == 0 ))
{return;}
 
// поменяем размеры в зависимости от разрешения
var width = screen.width;
//var height = screen.height;
if (width < 1152)
{ // 1024
document.getElementById('head_table').style.width="990px";
document.getElementById('head_center_center').style.width="165px";
document.getElementById('head_table').style.backgroundImage="none";
document.getElementById('main_table').style.width="990px";
document.getElementById('head_top_center').innerHTML="Молодежный центр<br/>ОБЕРЕГ";
document.getElementById('top_slideshow').style.left="20px";
}
else if (width < 1280)
{ // 1152
document.getElementById('head_table').style.width="1150px";
document.getElementById('head_center_center').style.width="292px";
}



/////////////////////////////////////
//  SlideShow
/////////////////////////////////////
// initialize the slideshow when the DOM is ready
		
		// это вариант загрузки всех картинок разом
		/*
		jQuery('#top_slideshow').cycle({
			fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
		}); //*/
 		
		// вариант добавления картинок в слайдшоу только после их загрузки
var stack = [];
var elements = jQuery("#top_slideshow img");
//var url = jQuery("#top_slideshow a").attr("href");

/* var url1 = "";
var URLParts = window.location.pathname.split("/");
for (i=0; i<URLParts.length-1;i++)
{url1 += URLParts[i]; } 

var url = "location.href='http://"+window.location.hostname+"/"+url1+"/plugins/sgallery/gallery.php'";
 */
for (var i = 0; i < elements.length; i++){
//var link = new link;
//link.href = url;
var img = new Image(366,275);
if(jQuery.browser.msie)
{
img.src = elements.eq(i).attr("src")+"?random=" + (new Date()).getTime();
}
else
{img.src = elements.eq(i).attr("src");}


//img.id = "topimg"+i;
//img.onClick = url;
//document.getElementById("topimg"+i).onclick = url;

// all img nodes (after the second) are removed from the DOM
// once the corresponding image is loaded, it is pushed into the stack
if (i > 1) {
	elements.eq(i).remove();
	  jQuery(img).bind("load",function(){
				stack.push(this);
				}); 
		/* jQuery(img).bind("load",function(){
				alert("!!!!");
				}); */ 		
				
		//if(img.complete || (jQuery.browser.msie))
		/* if(jQuery.browser.msie)
		{
		jQuery(img).trigger("load");
		} */
	/* jQuery(img).bind("click",function(){
				alert("!!!");
				});  */	
    }
}

jQuery('#top_slideshow').cycle({
			fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
			//timeout:2000,
			//containerResize: false,
			//manualTrump:   false,
			before:onBefore
		});
		
// add images to slideshow
function onBefore(curr,next,opts){
		while (stack.length > 0){
		if (opts.addSlide) opts.addSlide(stack.pop());
  };
}; 

/////////////////////////////////////
//  Lava Menu
/////////////////////////////////////

		//transitions
		//for more transition, goto http://gsgd.co.uk/sandbox/jquery/easing/
		var style = 'easeOutElastic';

		// перевели selected с class на id из-за того, что в IE8 проблемы с определением ширины по class
		//Retrieve the selected item position and width
		//var default_left = Math.round(jQuery('#lava li.selected').offset().left - jQuery('#lava').offset().left);
		var default_left = Math.round(jQuery('#lava li#selected').offset().left - jQuery('#lava').offset().left);
		var default_width = getElementWidth('selected');

		//var default_left = '100px';
		//var default_width = '100px';
		//alert('default_width='+default_width+'default_left='+default_left);

		//Set the floating bar position and width
		jQuery('#box').css({left: default_left});
		jQuery('#box #lava_head').css({width: default_width});

		//if mouseover the menu item
		jQuery('#lava li').hover(function () {
			
			//Get the position and width of the menu item
			left = Math.round(jQuery(this).offset().left - jQuery('#lava').offset().left);
			//width = jQuery(this).width(); 
			//width = getElementWidth(jQuery(this));
			if ($is.Opera==5) {	width = this.style.pixelWidth;	} 
			else {	width = this.offsetWidth;	}
			
		jQuery('#debug').html(left);
			//Set the floating bar position, width and transition
			jQuery('#box').stop(false, true).animate({left: left},{duration:1000, easing: style});	
			jQuery('#box #lava_head').stop(false, true).animate({width:width},{duration:1000, easing: style});	
		
		//if user click on the menu
		}).click(function () {
			
			//reset the selected item
			//jQuery('#lava li').removeClass('selected');	
			jQuery('#lava li').removeAttr('id');	
			
			//select the current item
			//jQuery(this).addClass('selected');
			jQuery(this).attr('id', 'selected'); 

	
		});
		
		//If the mouse leave the menu, reset the floating bar to the selected item
		jQuery('#lava').mouseleave(function () {

			//Retrieve the selected item position and width
			//default_left = Math.round(jQuery('#lava li.selected').offset().left - jQuery('#lava').offset().left);
			default_left = Math.round(jQuery('#lava li#selected').offset().left - jQuery('#lava').offset().left);
			//default_width = jQuery('#lava li.selected').width();
			default_width = getElementWidth('selected');
			//alert("leave def w="+default_width);
			
			
			//Set the floating bar position, width and transition
			jQuery('#box').stop(false, true).animate({left: default_left},{duration:1500, easing: style});	
			jQuery('#box #lava_head').stop(false, true).animate({width:default_width},{duration:1500, easing: style});		
			
		});
		
/////////////////////////////////////
//  Left menu (AutoSprites)
/////////////////////////////////////

		jQuery('.left_menu').autosprites({
		orientation: 'vertical',
		offset: '183px'
		});
		
/////////////////////////////////////
//  Slide menu (dimensions)
/////////////////////////////////////
// т.к. Slide menu есть только на некоторых страницах, то если на сранице его нет, будет ошика - уберем ее	
try
{
	/* var menu1 = null;
	var menu2 = null;
	menu1 = parseInt(jQuery('.vid').css('top').substring(0,jQuery('.vid').css('top').indexOf('px')));
	menu2 = jQuery(window).height() - 96;
	
	jQuery('.videopanel ul li ul').hide();
	
    jQuery('.videopanel ul li:has(ul) a').click(function() {
        jQuery(this).parent().find('ul').slideToggle();  
        return false;      
    });
	 
    jQuery('a.plus').click(function(){
       jQuery(this).parent().next().find('ul li ul').slideUp('fast');
       return false; 
    });
    
    jQuery('a.minus').click(function(){
       jQuery(this).parent().next().find('ul li ul').slideDown('slow');
       return false; 
    });	 */
}
catch(err)
  {
  //Handle errors here
  }	
try
{  
	/////////// Content (статьи) ////////////////
	jQuery('.contentpanel ul li ul').hide();
	
    jQuery('.contentpanel ul li:has(ul) a').click(function() {
        jQuery(this).parent().find('ul').slideToggle();  
        return false;      
    });
}
catch(err)
  {
  //Handle errors here
  }		
try
{  	
	/*
	///////// Camps & Competitions plugins ///////////////
	jQuery('.comments1').hide();
	
	jQuery('.comments_button').click(function() {
        //jQuery('.comments1').slideToggle();  
		jQuery(this).parent().find('.comments1').slideToggle();		
        return false;      
    });
	
	jQuery('a.show').click(function(){
       $('.comments1').slideUp('fast');
       return false; 
    });
    
	jQuery('a.hide').click(function(){
       $('.comments1').slideDown('slow');
       return false; 
    });
	//*/
}
catch(err)
  {
  //Handle errors here
  }	

 
//////// for making ajax site - for music player ///////
// suits for frames - to change URL for parent window
//* 
  // making OnClick redirect to XmlHttpRequest
  // OnClick because we want to save anchors for search robots
// if url = video galery - not using frames - don't change anchors
// исключения - не показывать фрэйм с музыкой
if(!(this.location.href.indexOf('video/index.php') + 1) )
{ // exclude hrefs with # as url
jQuery('a').filter(function (index) {
		return jQuery(this).attr("href") !== "#";
		})
		.click(function() {
       //alert('url=' + this.href);
a_click(this.href); 
	   //this.href = '#';		
       //return false;      
    });
}
//*/		


// Audio player window - блокируется браузерами

//function newWindow() 
//{ 
/* if (! popWindow || popWindow.closed) {
popWindow = window.open('frame1.htm', 'Obereg_player', 'width=300,height=100,left=150,top=100'); 
//alert(popWindow);
}  */
/* else {
popWindow.focus(); 
popWindow.location = "#"; 
}  */
//}

// меню разделов


var thumbnail1 = {
imgIncrease : 15, /* увеличение изображения в пикселях для зума */
effectDuration : 300, /* продолжительность эффекта для зума и надписи */
/*
Взять ширину и высоту изображений. Используется для 2-х вещей
1) сделать все элементы списка одного размера 2) вернуть изображения
к первоначальным размерам после зума
*/
/* imgWidth : jQuery('.thumbnailWrapper ul li').find('img').Width(),
imgHeight : jQuery('.thumbnailWrapper ul li').find('img').Height()  - т.к. в IE и Opera проблемы с этим атрибутом, используем хак*/
imgWidth : jQuery('.thumbnailWrapper ul li').find('img').css('width'),
imgHeight : jQuery('.thumbnailWrapper ul li').find('img').css('width')
};
//$('.thumbnailWrapper ul li').find('img').stop().delay(300).animate({
jQuery('.thumbnailWrapper ul li img').stop().each(
	function(i,elem) {
	jQuery(this).stop().delay((i+1)*300).animate({
	/* увеличить ширину изображения для зума*/
	width: parseInt(thumbnail1.imgWidth) + thumbnail1.imgIncrease,
	/* нам необходимо изменить левое и верхнее позиционирование
	для зума, и поэтому мы придаем им отрицательные значения
	 */
	left: thumbnail1.imgIncrease/2*(-1),
	top: thumbnail1.imgIncrease/2*(-1)
	},thumbnail1.effectDuration,
		function() {
		//найти изображение и анимировать его...
		jQuery('.thumbnailWrapper ul li').find('img').animate({
		/* вернуть первоначальный размер */
		width: thumbnail1.imgWidth,
		/* get left and top positions back to normal */
		left: 0,
		top: 0
		}, thumbnail1.effectDuration);
		}); // .animate({
	}
); // .each(


//задаем некоторые переменные
var thumbnail = {
imgIncrease : 15, /* увеличение изображения в пикселях для зума */
effectDuration : 400, /* продолжительность эффекта для зума и надписи */

/*
Взять ширину и высоту изображений. Используется для 2-х вещей
1) сделать все элементы списка одного размера 2) вернуть изображения
к первоначальным размерам после зума
*/
/* imgWidth : jQuery('.thumbnailWrapper ul li').find('img').Width(),
imgHeight : jQuery('.thumbnailWrapper ul li').find('img').Height() - т.к. в IE и Opera проблемы с этим атрибутом, используем хак */

imgWidth : jQuery('.thumbnailWrapper ul li').find('img').css('width'),
imgHeight : jQuery('.thumbnailWrapper ul li').find('img').css('width')

};

//Элементы списка того же размера, что и изображения
jQuery('.thumbnailWrapper ul li').css({ 

'width' : thumbnail.imgWidth,
'height' : thumbnail.imgHeight 

});

//при наведении мышки на элемент...
jQuery('.thumbnailWrapper ul li').hover(function(){

jQuery(this).find('img').stop().animate({

/* увеличить ширину изображения для зума*/
width: parseInt(thumbnail.imgWidth) + thumbnail.imgIncrease,
/* нам необходимо изменить левое и верхнее позиционирование
для зума, и поэтому мы придаем им отрицательные значения
 */
left: thumbnail.imgIncrease/2*(-1),
top: thumbnail.imgIncrease/2*(-1)
},{ 

"duration": thumbnail.effectDuration,
"queue": false

});
//показать надпись с помощью события slideDown
jQuery(this).find('.caption:not(:animated)').slideDown(thumbnail.effectDuration);

//когда мышку уводят...
}, function(){

//найти изображение и анимировать его...
jQuery(this).find('img').animate({

/* вернуть первоначальный размер */
width: thumbnail.imgWidth,
/* get left and top positions back to normal */
left: 0,
top: 0
}, thumbnail.effectDuration);
//спрятать надпись с помощью события slideUp
jQuery(this).find('.caption').slideUp(thumbnail.effectDuration);
});




}); //jQuery(document).ready(function ()
 
function a_click(href)
{
// Prepare
//var History = window.History; // Note: We are using a capital H instead of a lower h
var History = parent.window.History; // Note: We are using a capital H instead of a lower h
/*
if ( !History.enabled ) {
	 // History.js is disabled for this browser.
	 // This is because we can optionally choose to support HTML4 browsers or not.
	return false;
}
*/
/*
// Change our States
History.pushState({state:1}, "State 1", "?state=1"); // logs {state:1}, "State 1", "?state=1"
History.pushState({state:2}, "State 2", "?state=2"); // logs {state:2}, "State 2", "?state=2"
History.replaceState({state:3}, "State 3", "?state=3"); // logs {state:3}, "State 3", "?state=3"
History.pushState(null, null, "?state=4"); // logs {}, '', "?state=4"
History.back(); // logs {state:3}, "State 3", "?state=3"
History.back(); // logs {state:1}, "State 1", "?state=1"
History.back(); // logs {}, "Home Page", "?"
History.go(2); // logs {state:3}, "State 3", "?state=3"
*/
if(href.indexOf('video/index.php') + 1 == 0)
{// if not video page - do history replace, if video page - IE has got error with this because of hash (#) in url
//History.pushState(null, null, "?state=4"); // logs {}, '', "?state=4"
History.replaceState(null, null, href);
}

// if url = video galery - do not use frames
// исключения - не показывать фрэйм с музыкой
if ((href.indexOf('video/index.php') + 1) ||
   (href.indexOf('pekiti') + 1))
{
//parent.location.href = href; - hash is not sent
//parent.location = href; - hash is not sent!
parent.location.replace(href); // ok
}

} // function a_click(href)

 
	/* 
function a_click(href)
{
process_container = 'main_site_div';
the_url = href; */
/*
the_url - url to handle the request
param2 - callback funcrion
param3 - return XML
process_container - id of html element to put the result to
param5 - any parameters to pass to callback function
*/
/* 
makeHttpRequest(the_url, 'main_printResult', null, process_container, null);
} // function a_click(href)

function main_printResult(result_string, process_container, param)
{
	//var info_div = document.getElementById('infodiv');
	//alert(process_container);
	var info_div = document.getElementById(process_container);
	// просто вывести результат в контейнер, заменяя все что там есть
	info_div.innerHTML = result_string;
} // function printResult(result_string, process_container, param)
	 */
