$().ready(function(){
	C.init();
}).hashchange(function (e, newHash) {
	if(typeof C.not_first_time=='undefined'){
		C.not_first_time=true;
	}else{
		C.go(newHash);
	}
});

$(window).bind('load scroll resize',function(evt){
	if(evt.type=='resize' || evt.type=='load'){
		if(C.resize_timer){clearTimeout(C.resize_timer);}
		C.resize_timer=setTimeout('C.doResize()',100);
	}
})

$(window).bind('mousedown mousemove mouseup keydown keyup',function(evt){
	C.clearSelection();
})

var C={
	init: function(){
		// инициализируем библиотечку Shadowbox
		Shadowbox.init({
			players:["img","html","swf"],
			skipSetup: true,
			language: 'ru',
			handleOversize: 'drag'
		}) 

		// инициализируем библиотечку Hash.js (находится внутри jquery.hash.js)
		// добавляем всем ссылкам обработчики клика, которые вместо новых страниц меняют якорь текущей
		$.hash.init('blank.html');
		$('a').each(function(){
			C.bindClick($(this));
		})
		
		// если была открыта какая-то из внутренних страниц сайта, 
		// то загружаем ее содержимое
		// иначе стилизуем содержимое контейнера #contents, 
		// чтобы красиво отобразить картинки и подписи к ним
		// а также запускаем установку Shadowbox
		if(location.hash){
			var url=location.hash.substr(1);
			if(url){
				C.go(url);
			}
		}else{
			C.styleContent();
		}
	},

	go: function(new_hash){
		// меняем адрес страницы
		location.hash='#'+new_hash;
		// получаем содержимое страницы
		$.ajax({
			type: 'GET',
			url: '/'+new_hash,
			dataType: 'json',
			success: function(json){
				if(json.r){
					location.replace(json.r);
					return;
				}
				// обновляем содержимое блоков
				$('body').attr({className:json.b});
				$('#contents').html(json.c).css({visibility: 'visible'});
				document.title=json.t;
				$('#gradusnik').html(json.g);
				$('#menu1').html(json.m);
				$('#header div.langSwitcher a').attr({href:json.l});
				// прокручиваем страницу на самый верх
				window.scrollTo(0,0);
				// стилизуем содержимое контейнера #contents
				C.styleContent();
				// ставим или убираем ссылку на главную страницу
				if(new_hash){
					$('#header>div.logo').empty().append($(document.createElement('a')).attr({href:'/'}))
				}else{
					$('#header>div.logo').empty();
				}
				// переписываем заголовок правильным шрифтом
				Cufon.replace('#pageTitle h1');
				// перехватываем клики по ссылкам в блоках #contents, #gradusnik и #menu1 
				$('#contents a, #gradusnik a, #menu1 a, #header>div.logo>a').each(function(){
					C.bindClick($(this));
				});
				// поскольку содержимое контент-блока меняется динамически, 
				// нам нужно сбросить и установить заново высоту #mainBox
				$('#mainBox').height('auto');
				C.doResize();
				// собираем статистику посещений
				try {
					if($('body').is('body.ru')){
						var pageTracker = _gat._getTracker("UA-15637689-1");
					}else{
						var pageTracker = _gat._getTracker("UA-15637689-2");
					}
					//pageTracker._setDomainName(".paradpobedy.ru");
					pageTracker._trackPageview('/'+new_hash);
				} catch(err) {}
			}
		});
	},
	
	styleContent: function(){
		// обрабатываем картинки
		$('#contents>div.lcol>p, #contents>div.rcol>p').each(function(){
			var image_type;
			if($(this).children().length==1 || $(this).children().length==2){
				var $first_image=$(this).children().eq(0);
				if($first_image.is('a')){
					$first_image=$first_image.children();
				}
				if($first_image.is('img')){// && $first_image.attr('alt')
					if($first_image.is('img.center')){
						image_type='single';
					}else if($first_image[0].offsetWidth==595 || $first_image[0].offsetWidth==226 || $first_image[0].offsetWidth==150){
						image_type='single';
					}else if($first_image[0].offsetWidth==290){
						image_type='pair';
					}
				}
			}
			if(image_type){
				for(var j=0; j<2; j++){
					if($(this).children('img').length || $(this).children('a').length){
						/*if($(this).html().indexOf('&nbsp;')==0){
							var html=$(this).html().substr(6);
							$(this).html(html)
						}
						while($(this).html().indexOf('>&nbsp;')>0){
							var html=$(this).html().substr(0, $(this).html().indexOf('>&nbsp;')+1);
							html+=$(this).html().substr($(this).html().indexOf('>&nbsp;')+7);
							$(this).html(html)
						}*/
						var html=$(this).html();
						html=html.split('&nbsp;<').join('<').split(' <').join('<');
						html=html.split('>&nbsp;').join('>').split('> ').join('>');
						html=html.split('<br>').join('');
						$(this).html(html);
						if($(this).children('img').length){
							var $image=$(this).children('img').eq(0);
						}else{
							var $image=$(this).children('a').children('img').eq(0);
						}
						var $span=$(document.createElement('span')).prependTo(this);
						$span.addClass(image_type);
						$(this).children('img,a').eq(0).appendTo($span);
						if($image.attr('alt')){
							var b=$image.attr('alt');
							var i=null;
							if(b.indexOf('{')>0 && b.indexOf('}')>0){
								i=b.substr(b.indexOf('{')+1);
								i=i.substr(0,i.indexOf('}'));
								b=b.substr(0,b.indexOf('{'));
							}
							var $b=$(document.createElement('b')).html(b).appendTo($span);
							if(i){
								$(document.createElement('i')).html(i).appendTo($b);
							}
						}
					}
				}
				$(this).addClass('images');
				if(image_type=='pair'){
					$(this).append($(document.createElement('br')).addClass('clear'));
				}
			}
		})
		if($.browser.msie && parseFloat($.browser.version)<=6){
			var $rcol_1=$('body.id127 #contents div.rcol').eq(0);
			if($rcol_1.length){
				$rcol_1.find('span.single').eq(0).css({background: 'none'});
			}
		}
		// обрабатываем разделители <hr>
		$('#contents>div').children('hr').each(function(){
			$(this).wrap($(document.createElement('div')).addClass('hr'));
		})

		// привязываем ссылки из #contents к Shadowbox
		$('#contents a').each(function(i){
			if(this.href.search(/\.(jpg|jpeg|png|gif)$/)>0){
				var opts={
					content: this.href,
					player: 'img',
					title: $(this).children().eq(0).attr('alt'),
					handleOversize: 'drag'
				};// console.dir(opts);
				Shadowbox.setup(this,opts);
			}else if(this.href.search(/\.(flv)$/)>0){
				var this_rel=(this.rel && this.rel.indexOf('{')==0)?this.rel:'{}';
				eval('this_rel='+this_rel);
				var wh=[(this_rel.width || 320),(this_rel.height || 240)];
				var title='';
				if(this.title){
					title=this.title;
				}else if($(this).children().is('img')){
					title=$(this).children().eq(0).attr('alt');
					if(title && title.indexOf('{')>=0){
						title=title.substr(0,title.indexOf('{'));
					}
				}
				var opts={
					content: '/u/swf/video_player.swf',
					player: 'swf',
					width: wh[0],
					height: wh[1],
					title: title,
					flashParams: {bgcolor: '#FFFFFF'},
					//flashVersion: 9,
					flashVars: {
						VIDEO_FILE: this.href,
						VIDEO_WIDTH: wh[0],
						VIDEO_HEIGHT: wh[1]
					}
				};// console.dir(opts);
				Shadowbox.setup(this,opts);
			}else if(this.href.search(/\.(mp3)$/)>0){
				var mp3box_id='mp3box_'+i;
				var $mp3_container=$(document.createElement('span')).addClass('mp3box db').attr({id:mp3box_id}).text('hi').insertBefore(this);
				var so = new SWFObject("/u/swf/audio_player.swf", "head", "300", "40", "9", "#ffffff");
				so.addParam("wmode", "transparent");
				so.addVariable("AUDIO_FILE", this.href);
				so.addVariable("AUDIO_TITLE", $(this).text());
				so.write(mp3box_id);
				$(this).remove();
				// var opts={content: '/u/swf/audio_player.swf',player: 'swf',width: 230,height: 40,flashParams: {bgcolor: '#FFFFFF'},flashVars: {AUDIO_FILE: this.href,AUDIO_TITLE: $(this).text()}};Shadowbox.setup(this,opts);
			}
		})
	},

	bindClick: function($a){
		var url=$a.attr('href');
		if(url){
			if(url.indexOf('http://'+location.host)==0){
				url=url.substr(7+location.host.length);
			}
			if(url.indexOf('://')>0){return;}
			if(url.indexOf('mailto:')==0){return;}
			if(url.search(/\.(jpg|jpeg|png|gif|flv)$/)>0){return;}
			$a.bind('click',function(evt){
				evt.preventDefault();
				//C.go(url);
				$.hash.go(url.substr(1));
			})
		}
	},
	
	doResize: function(){
		// для msie делаем ресайзы теней (1 этап - сброс)
		if($.browser.msie && parseFloat($.browser.version)<=6){
			// alert([$('#mainBox').height(),$('#mainBox').css('height'),$('#mainBox')[0].offsetHeight])
			$('#ma, #bgrt, #ma>div.r50, #lshdw, #ma>div.l50, #rshdw').css({height: 'auto'});
		}
		var screen_width=$.evScreenWidth();
		if(screen_width<=1000){
			$('#mainBox').width(1000);
		}else{
			$('#mainBox').width('auto');
		}
		var screen_height=$.evScreenHeight();
		var scroll_height=$.evScrollHeight();
		if(screen_height==scroll_height){
			var height=Math.min($('#ma')[0].offsetHeight+30,screen_height);
			$('#mainBox').height(height);
		}else{
			$('#mainBox').height('auto');
		}
		// для msie делаем ресайзы теней (2 этап - установка)
		if($.browser.msie && parseFloat($.browser.version)<=6){
			// alert([$('#mainBox').height(),$('#mainBox').css('height'),$('#mainBox')[0].offsetHeight])
			$('#ma, #bgrt, #ma>div.r50, #lshdw, #ma>div.l50, #rshdw').each(function(){
				this.style.zoom=1;
				this.style.height=$('#mainBox')[0].offsetHeight+'px';
			})
		}
	},

	clearSelection: function(){
		var sel;
		if(document.selection && document.selection.empty){
			document.selection.empty();
		}else if(window.getSelection){
			sel = window.getSelection();
			if(sel && sel.removeAllRanges)
			sel.removeAllRanges();
		}
	},

	interview: function(id){
		var $a=$('#interview'+id);
		var cache=Shadowbox.inCache($a[0]);
		Shadowbox.open(cache);
	}
}

