var re=/http:\/\/[a-z\.-]+/;

if (location.hash=='') location.href='/#'+location.href.replace(re,'');

var loading=false;
var clicked=false;
var wait;
var bookopen=false;
var flash=false;
var _active=0;
var lim=0;
var pageTracker;

$(document).ready(function(){	
	
	// fixPNG
	$('img[@src$=.png], #over, #lpage, #rpage').ifixpng();
	
	$('body').append('<div id="loader"/>');
	init('all');
	
	var u=location.hash.substr(1);	
	if (u=='' && location.href.replace(re,'')=="/") { location.href='/#/news'; }
//	else location.href='/#'+location.href.replace(re,'');
	if (u.substr(0,5)=='/book') { $("#book").html(''); }	
	
	
	// разбивка на колонки	
	if ($('#text').html()!=null){		
		$(function(){			
			$('#wrapper').css({ overflow: 'hidden', height: 128, width: 534 });
			$('#text').columnize({width: 247, height: 130, buildOnce:true});
			scTextInit();
		});
	}
	
	// flashBook	
	  if (swfobject.hasFlashPlayerVersion("10.0.0") && !($.browser.msie && $.browser.version<7) ) {		  
		  flash=true;
		  $('#book, #over, #triangle').remove();
		  $('#all').prepend('<div id="flashbook"/>');
		  
			var fn = function() {				
				var att = { 
					data: "/view/swf/book.swf?v09072202", 
					width: "1220",
					height: "750" 
				};
				var par = { 
					wmode: "transparent",
					menu: "false"
				};
				
				var id = "flashbook";
				var headObject = swfobject.createSWF(att, par, id);
				
				
				if (location.hash=='') {
					listTo(	location.href.replace(/.*\/book\/([0-9]+).*/,'$1' ) );
				}
				
/*				if ($.browser.msie) {					
					//$('#flashbook').append(
					alert($('<embed type="application/x-shockwave-flash" wmode="transparent" name="flashbook" src="/view/swf/book.swf" width="1200" height="750" pluginspage="http://www.adobe.com/go/getflashplayer" /><noembed>Need Flash Player</noembed>'));
					//);
				}
*/				
		    } 
			swfobject.addDomLoadEvent(fn);
		  
			
			$('#debug').html('[ flash ]');
		} else $('#debug').html('[ js ]');

	
	// центрирование
		resizeHandler();
		$(window).resize(function(){
			resizeHandler();
		});	
	
/*	 $().history(function(e, hash) {		
		 goURL(hash+'?up','main');
	 });
	 
	 
	 $().historyadd(function(e, currentHash, previousHash) {
		 alert(currentHash);
	  //      $(this).html('Navigation added: ' + currentHash);
	  });

*/	
	$(document).bind('hashChange', function(e, newHash){
						
		if (!clicked) {
			//document.title='';			
			return goURL(newHash.substr(1)+'?up',newHash.substr(1,5)=='/book'?'book':'main');			
			//console.log('> ' + newHash);
		} //else alert("!!!");
		clicked=false;
	});
	
});

function resizeHandler(){
	var vh=document.getElementsByTagName('html')[0].clientHeight;
	var vw=document.getElementsByTagName('html')[0].clientWidth;
	var h=vh-$('#all').height()-40;
	$('#all').css('margin-top', (h>0 ? (h/2+20): 20)+'px');
	if (flash && vh>750 && !$.browser.msie) $('#flashbook').css({ left:0, top:0, height: vh, width: vw, margin: '-20px 0 0 -2px'});
}

function init(trg) {
	// facebox
	
	if ( $.browser.msie ) $('area').facebox(); else areaReplace();
	$('a[rel*=facebox]').facebox();
	
	$("#"+trg+" a").click(function(){ 	
		
		if (loading) return false;
		if (this.rel!='' && this.rel!='facebox') {
			var u=this.href.replace(re,'');	
			
			goURL(u,this.rel);
			clicked=true;
			
			location.href="/#"+u;
			
			return false; 
		}		
	});
	
	var u = location.hash.substr(1);	
	u = u.replace(/[\/]+$/);
	var m = u.split('/');
	var s = "";

	if ((location.hash != '') && (m.length != 2)) {
		$("a").removeClass('active');
	} else if (location.hash != '') $("#menu a").removeClass('active');
			
	for (var i = 1; i < m.length; i++) {
		s += '/' + m[i];
		$("a[@href=" + s + "]").addClass('active');
	}
	
	//pageTracker = _gat._getTracker("UA-4992913-1");
	
}

function capitalize(str) {
	return str.substr(0,1).toUpperCase()+str.substr(1).toLowerCase();
}

function goURL(url,target){	
	loading=true;
	
	if (pageTracker) pageTracker._trackPageview(url);
	
	if (url=='/') { url='/news'; target='main'; }
	else if (url=='/?up') { url='/news'; }
	
	if (flash && target=='book')
	{
		var pg=url.replace(/\/book\/(\d{1,3}).*/,'$1');
		listTo(pg);
		bookopen=true;
		loading=false;
		
		return false;
	}
	
	clearTimeout(wait);
	wait=setTimeout(function(){ $('#ldr').fadeIn(); }, 1000);	
	jQuery(document).trigger('close.facebox')
	
//	$('#ldr').fadeIn();
	
	$("#loader").load(url, function(){
		
		clearTimeout(wait);		
		
		if (target=='book') {			
			$("#main").html('');
			$('#book').css('z-index','2');
			bookopen=true;
			
				
				lim=0;
				$("#loader img").each(function(){ lim++; })
				
				$('#ldr').fadeIn();
				
				
				$("#loader img").each(function(){
					
				    var image = new Image()
				    image.onload = function() {
				    	lim--;
				    	if (lim==0) {
				    		$('#ldr').fadeOut();
				    		$("#"+target).fadeOut(100,function() {
				    			$("#"+target).html($("#loader").html());
								$("#loader").html('');	
								
								document.title= "Портфолио - "+document.title.replace(/(.*)\-\s/,""); 
								
								init(target);
								
								$("#"+target).fadeIn(100, function() {
									loading=false;	
								})
				    		});			    		
				    	}
				    
				    }
				    image.src = $(this).attr('src')
				});
			
			
			return false;
		} 
		
		$("#"+target).fadeOut(50,function() {
				$("#"+target).html($("#loader").html());
				$("#loader").html('');
				
				document.title= capitalize($("h1").text())+": "+$("h2").text()+" - "+document.title.replace(/(.*)\-\s/,"");
				
				$('#content').css({opacity: 0});
				$('#wrapper').css({ overflow: 'hidden', height: 128, width: 534 });
				init(target);				
				
				$('#ldr').fadeOut();
				
				$("#"+target).fadeIn(50,function(){
										
					$(function(){		
						$('#text').columnize({width: 247, height: 130, buildOnce:true, doneFunc: function() {
							
							$('#content').css({opacity: 1, display: 'none'});							
							$('#content').fadeIn(100);							
							
							scTextInit();
																					
						}});
					});
										
					loading=false;
					if (bookopen) { closeBook(); }
					
					//if ($("h1").text() != '') document.title=capitalize($("h1").text())+": "+$("h2").text()+" - "+document.title.replace(/(.*)\-\s/,"");
				});
				
		})
	})	
}

function closeBook(){
	if (flash) {
		listTo(0);
		
	} else {
		$("#book").html('<a id="lpage"/><a id="rpage" href="/book/2" rel="book"><img src="/book/begin"/></a>').css('z-index','0');
		$("#book_menu a").removeClass('active');	
	}
	bookopen=false;
}

function scTextInit(){
	var m = jQuery.makeArray($('#text div.column'));
	
	if (m.length>2) {								
		$('#text').width(Math.round(m.length / 2)*2*287-5);
		if ($('#text_nav').text()=='')
			$('#content').append('<div id="text_nav"><a id="nav_f" href="javascript: void(0)" onclick="scrollNext()">дальше ...</a><a id="nav_b" href="javascript: void(0)" onclick="scrollBack()">... к началу</a></div>');								
	}
}

function scrollNext(){
	scrollText('+');
}
function scrollBack(){
	scrollText('-');
}

function scrollText(p){		
	$('#wrapper').scrollTo( p + '=574px', 300, {axis:'x', onAfter: function(){		
		$('#nav_b').css({ visibility: $('#wrapper').scrollLeft()>0 ? 'visible' : 'hidden' });
		$('#nav_f').css({ visibility: $('#wrapper').scrollLeft()<$('#text').width()-600 ? 'visible' : 'hidden' });
	} });

}

// keyNav
document.onkeydown = keyNav;
function keyNav (event)
{	
	if (!document.getElementById) return;
	if (window.event) event = window.event;
	if (event.ctrlKey)
	    {
		var link = null;
		var href = null;
		switch (event.keyCode ? event.keyCode : event.which ? event.which : null)
		    {		
			case 0x25:
				link = document.getElementById ('lpage');
				break;
			case 0x27:			
				link = document.getElementById ('rpage');
				break;
/*			case 0x26:
				link = document.getElementById ('up_page');
				break;
			case 0x28:
				link = document.getElementById ('down_page');
*/					
				break;
			case 0x24:
				link = $('a');
				link.href = '/book/0';
				break;
			case 77:
				$('a[id*=area]').each(function(){ $(this).toggleClass('area_over');  })		   		   		   
	   			setCookie('areas',getCookie('areas')!=1?1:0,7);
				break;
			
		    }
	    		
	    }
	switch (event.keyCode ? event.keyCode : event.which ? event.which : null)
	{
	case 0x20:			
		link = document.getElementById ('rpage');
		break;
	}
	if (link) document.location = '/#'+link.href.replace(re,'');
}


function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString()+";path=/");
}

function getCookie(c_name)
{
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
	    { 
	    c_start=c_start + c_name.length+1; 
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
	    } 
	  }
	return "";
}

var area_id=0;
function areaReplace(){
	$("area").each(
			function(){		
				area_id++;
				//var id = $(this).attr("href").substring(1);
				var pg=$(this).parent().attr("name");
				var id = area_id;				
				var coords = $(this).attr("coords").split(",");
				var div = '<a class="'+($(this).attr("class")==undefined?'video':$(this).attr("class"))+'" id="area_' + id + '" rel="'+($(this).attr("rel")==undefined?'facebox':$(this).attr("rel"))+'"'+($(this).attr("target")==undefined?'':' target="'+$(this).attr("target")+'"')+' href="'+$(this).attr("href")+'" title="'+$(this).attr("title")+'"></a>'
				$("#book").append(div)
				$("#area_" + id).css({ left: coords[0]-(pg=='map_rpage'?-610:0)+'px', top: coords[1]+'px', width: (coords[2]-coords[0])+'px', height: (coords[3]-coords[1])+'px', position: 'absolute', zIndex: '30'  });				
			}
		);
	
		$('map').remove();
	
		if (getCookie('areas')==1) $('a[id*=area]').each(function(){ $(this).toggleClass('area_over'); })
}


/*	FLASHBOOK	*/
function jsBeforeList(){
	$('#main, #menu, #book_menu, #right_menu').css('z-index',0);	
}

function jsAfterList(){	
	$('#book_menu, #right_menu').css('z-index',2);
	$('#menu').css('z-index',3);
}

function jsSetActive(num){	
	_active=num+1;
	
//	alert("!!!"+num);
	
	var u="/book/"+_active;
	clicked=true;	
	$("a").removeClass('active');
	$('#book_menu a[href$='+u+']').addClass('active');
	bookopen=true;
	
	if (_active>0) {
		if (location.hash!='') location.hash=u;
		$('#main').html('');		
	} else { $('#main').css('z-index',2); if (location.hash.substr(1,5)=='/book') {clicked=false; location.hash='/news';} bookopen=false; }
	
	if (pageTracker) pageTracker._trackPageview(url);
			
}

function jsRunPlayer(url){	
	jQuery.facebox({ video: url })
}

function listTo(value) {			
	 var movie = ( $.browser.msie ? window : document)["flashbook"];
	 try {
		 movie.flashListTo(value);
	 } catch (e) {
		 setTimeout(listTo,1000,value);		 
	 };	 
}