var bBuisyFlag = 0;
var ActiveUrl = "";
var AdminPanelLoaded = false;

var NavAjax = new AjaxReq();
NavAjax.SetUrl("/passport/");
NavAjax.SetMethod("POST");

var LoaderDiv = 0;
var bForceReload = false;

var Global_login = "";

var PastContent;
var ScrollStek = new Array();
var MenuHidden = 0;
var pictList = 0;
var menuList = 0;
var activeOffset = 0;
var AtiveElems = new Array();
var PastURL;

function logOut( inEvnt)
{
	NavAjax.SetParam("XML_resolt", "1" );
    NavAjax.SetUrl("/passport/");
    NavAjax.SetParam("action", "logout" );
    NavAjax.SetCallBackFunction( logOutColback );
	NavAjax.Request();
}
function logOutColback()
{
	LoadPage(null, document.location.protocol+'//'+document.location.host + "/");
}

function autorize(inEvnt)
{

    NavAjax.SetParam("XML_resolt", "1" );
    NavAjax.SetUrl("/passport/");
    NavAjax.SetParam("action", "auth" );
	NavAjax.SetParam("login", $("#in_login").get()[0].value );
	NavAjax.SetParam("password", $("#in_pass").get()[0].value );

	NavAjax.SetCallBackFunction( AutorizeColback );
	NavAjax.Request();
	NavAjax.ClearParam();

	/*
	$("#light_box").remove();
	LoaderDiv = $("<div id='loader_div' style=' position:absolute; top:300px; left:450px; font-size:20px; '> <div class='PartLoader' >&nbsp;</div>   </div>");
 	LoaderDiv.appendTo("#PageContaner");
    LoaderDiv.css('opacity',0);
    LoaderDiv.animate({'top':'-=30','opacity':'1'},600);
    setTimeout( function(){ LoaderDiv.remove();  $("#nopass").fadeIn(700);}, 2500 );
    */
}

function AutorizeColback()
{


	if( NavAjax.GetResponseText().indexOf( "denied" ) != -1 )
	{
	     $("#nopass").fadeIn(700);
	}
	else if(  NavAjax.GetResponseText().indexOf( "accept" ) != -1 )
	{
		bForceReload = true;
		if( ActiveUrl == null || ActiveUrl == undefined || ActiveUrl == "")ActiveUrl = document.location.protocol+'//'+document.location.host + "/" ;
		LoadPage(null, ActiveUrl);

		var reg= /\<login\>([\s\S]*)\<\/login\>/m;
		var arr = reg.exec(NavAjax.GetResponseText());

		Global_login = arr[1];
		if(  NavAjax.GetResponseText().indexOf( "isadmin" ) != -1 )
		{
			if( AdminPanelLoaded == false)
 			{
				PreloadScript("/skn/std/scr/windows.js");
				PreloadScript("/skn/std/scr/admin.js");
				PreloadScript("/scr/calend.js");
				PreloadScript("/skn/std/scr/files_control.js");
				PreloadCSS("/css/datepicker.css");
			}
		}
		else
		{

		}

	}
}

function LoadPage(inEvnt, targetPage)
{


	while( ScrollStek.length != 0)
	{
		var CurScroll = ScrollStek.pop();
		CurScroll.remove();
		CurScroll = 0;
	}
	$("#light_box").remove();
	evt = (window.event)?event:inEvnt;
	if(evt)
	{
			sender = evt.target || evt.srcElement;
			evt.returnValue    = 0;
			if(evt.preventDefault)evt.preventDefault();
		}
		if( targetPage[0] == "." && targetPage[1] == "/")  targetPage =ActiveUrl + targetPage.substring(2,0);
		bBuisyFlag = 1;
		bForceReload = false;

     // document.title= "+++ загрузка +++";
      var mastBehidden = 0;
      NavAjax.RemoveParam("get_menu");
      if( (targetPage.indexOf("portfolio") != - 1 && targetPage.indexOf("work_") != - 1)   )
      {
        mastBehidden = 1;
        if(menuList == 0) NavAjax.SetParam("get_menu", "true" );
      	if(MenuHidden == 0)
      	{

      		MenuHidden = 1;
            $("#footer_nav").animate({"bottom":"-140"}, 500);
            menuList = $("<div style='position:absolute; left:160px; bottom:30px; overflow:hidden; z-index:10; width:600px; height:175px; white-space: nowrap; vertical-align:bottom;'>"
            +"</div>");
            AtiveElems[0] =  $("<div class='pright' style='top:" + ( $("#pageBody").attr('offsetHeight') - 150  ) + "px;left:790px;' onclick='StartScroll(300);'></div>");
            AtiveElems[1] =  $("<div class='pleft' style='top:" + ( $("#pageBody").attr('offsetHeight') - 150  ) + "px;left:78px;' onclick='StartScroll(-300);'></div>");
            AtiveElems[0].appendTo("#pageBody");
            AtiveElems[1].appendTo("#pageBody");
            menuList.appendTo("#pageBody");

      	}
      }

	  if( targetPage.indexOf("other/cont") != - 1   )
      {

	  	mastBehidden = 1;
	  	if(menuList == 0) NavAjax.SetParam("get_menu", "true" );
		if(MenuHidden == 0)
		{
		  MenuHidden = 1;
	      $("#footer_nav").animate({"bottom":"-140"}, 500);
          menuList = $("<div class='map_bott' ></div>");
          menuList.appendTo("#pageBody");
		}

	  }

	  if(mastBehidden == 0 && MenuHidden == 1)
	  {
	  	MenuHidden = 0;
	  	$("#footer_nav").animate({"bottom":"0"}, 500);
	  	setTimeout(function(){menuList.remove(); menuList = 0; AtiveElems[0].remove();AtiveElems[1].remove();}, 500);
	  }
      PastURL   = ActiveUrl;
 	  ActiveUrl = targetPage;
 	  NavAjax.SetUrl(targetPage);
 	  NavAjax.SetParam("isAjax", "true" );
      NavAjax.SetCallBackFunction(ContentLoaded);
      PastContent = $("<div style='height:630px; overflow:hidden;'></div>");

	  $("#PageContaner").wrapInner( PastContent );
	  PastContent= $("#PageContaner > div").first();

	  if( navigator.appVersion.indexOf("MSIE") == -1)
	  {
	   		PastContent.css('opacity',0.99);
		    PastContent.animate( {'opacity':"0.3"}, 500,'linear', function(){ NavAjax.Request(); NavAjax.ClearParam(); } );
	   }
       else
       {
       	    PastContent= $("#PageContaner  *");
       	    PastContent.each( function() {$(this).css('opacity',0.30); } );
       	    NavAjax.Request();
       	    NavAjax.ClearParam();

       }

       LoaderDiv = $("<div id='loader_div' style=' position:absolute; top:300px; left:450px; font-size:20px; '> <div class='PartLoader' >&nbsp;</div>   </div>");
       LoaderDiv.appendTo("#PageContaner");
       LoaderDiv.css('opacity',0);
       LoaderDiv.animate({'top':'-=30','opacity':'1'},600);



}

function ContentLoaded()
{
	var reg= /\<content\>([\s\S]*)\<\/content\>/m;
	var arr = reg.exec(NavAjax.GetResponseText());

	//alert( NavAjax.GetResponseText() );
	$("#PageContaner").attr('innerHTML',arr[1] );
	bBuisyFlag = 0;


	var reg2 =  /\<execute\>([\s\S]*?)\<\/execute\>/mg;

	while ( arr = reg2.exec(NavAjax.GetResponseText() ))
	{
		eval( arr[1]);
	}

    //alert( NavAjax.GetResponseText() );
	//for(i = 0; i <= arr.length ; i++ ){alert(arr[i]); }// }


}




function ACB_SetTitle(newTitle, len)
{
    //if(len == undefined || len == NaN)len = 1;

	document.title =  newTitle;
    yaCounter2197723.hit(ActiveUrl, newTitle, PastURL);
    //.substring(0, len)  ;
//	len+=3;
//	if( len < newTitle.length -1)	setTimeout("ACB_SetTitle(\"" + newTitle + "\", " + len + ")", 15);



}

/////////////////////////////// Portfolio
function PCB_crealteListMenu(baseUrl)
{

	if(pictList == 0 )return;
	var Element;
	var offsetElem = 0;
	var newDivElem;

	while(Element = pictList.shift() )
	{
		newDivElem = $("<div style='float:left;height:160px;overflow:hidden;  margin-left:6px; line-height:1px;'><a href='" + baseUrl + "work_" + Element['id'] + "' title='" + Element['name'] +"' style='display:block;'   ><img src='/img_processor/preview/" + Element['prev'] + " /' width='90px'  height='66px'  class='pImageLink' style='margin:0px;width:90px;height:66px;' onclick='SelectElem(event," +offsetElem + ", \""  + baseUrl + "work_" + Element['id'] +"/\"  ); ' ><br /><img src='' border='0' alt='' width='90px' style='margin-left:1px;width:90px; height:25px; border:0px none;'  height='25px'/></a></div>");
		menuList.append(newDivElem);
        offsetElem++;
        flip( newDivElem.find("img").get()[0], newDivElem.find("img").get()[1]);
	}

	menuList.wrapInner("<div></div>");
    menuList.find('div').first().css("width",offsetElem * 160);
    SelectElem(null, activeOffset, null);
    //SetSizeActive(   activeOffset);
}

function SetSizeActive( Position)
{

	var aList = menuList.get()[0].getElementsByTagName('a');


    var TotalOffset = 0;
	for(i = 0; i < aList.length; i++)
	{
		dist = Position - i;
		if(dist < 0 )dist = -dist;

		if( dist > 1)dist = 1;
		koef = 0.85 - 0.25 *dist;

		aList[i].style.width     = Math.round( 150 * koef +2) + 'px';
		aList[i].style.height    = Math.round( 110 * koef) + 'px';
		aList[i].style.marginTop = Math.round( 112 - 110 * koef ) + 'px';

		var imgIn = aList[i].getElementsByTagName('img');


		imgIn[0].style.width     = Math.round( 150 * koef) + 'px';
		imgIn[0].style.height    = Math.round( 110 * koef) + 'px';

		if(imgIn[1])
		{
				imgIn[1].style.width     = Math.round( 150 * koef) + 'px';
				imgIn[1].style.height    = Math.round( 50* koef) + 'px';
        }
        else
        {
        	imgIn = aList[i].getElementsByTagName('canvas');
        	//alert(imgIn[0])
        	if(imgIn[0])
			{
				imgIn[0].style.width     = Math.round( 150 * koef) + 'px';
				imgIn[0].style.height    = Math.round( 50* koef) + 'px';
        	}
        }




		/*if( i <= Position)
		{
			if( dist == 1) TotalOffset +=  Math.round( 150 * koef) + 8;
			else TotalOffset +=  Math.round( 150 * koef) *dist + 3;
		}*/


	}
	menuList.find('div').first().css('marginLeft', -Math.round(ScrollNow) + 230);

}

var SelectBusy  = 0;
var SpeedScroll = 0, SpeedChange = 0;
var ScrollNow   = 0, NeedScroll  = 0;

function SelectElem(inEvnt, Offset, needUrl)
{
	if( SelectBusy )
	{
		evt = (window.event)?event:inEvnt;
		sender = evt.target || evt.srcElement;
      	evt.returnValue    = 0;
 	  	if(evt.preventDefault)evt.preventDefault();
		return;
	}
	SelectBusy  = 1;

	if(needUrl)LoadPage(inEvnt, needUrl);

	SpeedChange = Math.abs( Offset -  activeOffset) / 10;
	if(SpeedChange < 0.1) SpeedChange = 1;
	NeedScroll  = Math.floor( (Offset) * (0.6 * 150 + 8) );

	SpeedScroll = Math.abs(  NeedScroll -  ScrollNow) / 10;


	ScrollingMenu(Offset);




}
function ScrollingMenu( NeedPos )
{
	if(Math.abs(activeOffset - NeedPos) < SpeedChange*0.6 )
	{
		activeOffset = NeedPos;
		SelectBusy   = 0;
		ScrollNow    = NeedScroll;
	}
	else
	{
			if(activeOffset < NeedPos){activeOffset += SpeedChange;}
			else if(activeOffset > NeedPos){activeOffset -= SpeedChange;}

			if(ScrollNow < NeedScroll){ScrollNow += SpeedScroll;}
			else if(ScrollNow > NeedScroll){ScrollNow -= SpeedScroll;}


			setTimeout(function(){ScrollingMenu(NeedPos);},50 );
	}
    SetSizeActive(activeOffset);

}

function StartScroll( ioffset)
{
	if( SelectBusy) return;
	SelectBusy = 1;
	SpeedScroll = 30;
	NeedScroll = ScrollNow +ioffset ;

	Scroll();

}

function Scroll()
{
	if(Math.abs(ScrollNow - NeedScroll) < SpeedScroll*0.6 )
	{
		SelectBusy   = 0;
		ScrollNow    = NeedScroll;
	}
	else
	{
        if(ScrollNow < NeedScroll){ScrollNow += SpeedScroll;}
		else if(ScrollNow > NeedScroll){ScrollNow -= SpeedScroll;}
		setTimeout( Scroll ,50 );
	}
    menuList.find('div').first().css('marginLeft', -Math.round(ScrollNow) + 230);
}


//////////////////////////////////////////////////////////////////
function flip(src, dest)
{
  if (document.all && !window.opera)
  {
    dest.src = src.src;
    $(dest).css("filter","flipv; alpha(opacity=95, finishopacity=0, style=1, startX=0, finishX=0, startY=0, finishY =120%); blur(Add=1, Direction=3, Strength=6); wave(add=0, freq=3, lightstrength=10, phase=2, strength=3)");
    $(dest).animate( {"filter.wave.phase":100},"slow");
    $(dest).css("height","10px");
  } else
  {
    var canvas = document.createElement('canvas');
    if (canvas.getContext)
    {
      if(dest != undefined) setTimeout( function(){ docanvas(canvas,src, dest)},50);
    }
  }
}

function docanvas(CanvInp, sourc, destanation)
{
  var context = CanvInp.getContext("2d");

  CanvInp.style.height = parseInt(destanation.style.height)+'px';
  CanvInp.style.width  = parseInt(destanation.style.width)+'px';



  CanvInp.height = parseInt(destanation.style.height);
  CanvInp.width  = parseInt(destanation.style.width);
  CanvInp.style.padding = '0px';
  CanvInp.style.margin  = '0px';

  context.translate(0, parseInt(destanation.style.height) );



  context.scale(1,-1);
  context.drawImage(sourc, 0, 0, parseInt(destanation.style.width), parseInt(destanation.style.height) );
    var canvasData = context.getImageData(0, 0, CanvInp.width, CanvInp.height);


  for(var i = 0; i < canvasData.width; i++)
  {
        for(var j = 0; j < canvasData.height; j++)
        {
            var idx = (i + j * canvasData.width) * 4;
            var alpha = 127 - 127* j/ canvasData.height;

            //var alpha = 130 - 255* j/ canvasData.height  + 120 * Math.sin(  3.14 * i/canvasData.width);
            canvasData.data[idx + 3] = (alpha <0 ? 0 : alpha>255 ? 255: alpha ); // ALPHA - альфа-канал
        }
    }
    context.putImageData(canvasData, 0, 0);
   $(destanation).replaceWith(CanvInp);

}
/////////////////////////////////////////////

