/***********************************************
* CMotion Image Gallery- й Dynamic Drive DHTML code library (www.dynamicdrive.com)
* Visit http://www.dynamicDrive.com for source code
* This copyright notice must stay intact for legal use
* Modified for autowidth and optional starting positions in
* http://www.dynamicdrive.com/forums/showthread.php?t=11839 by jschuer1 8/5/06
***********************************************/
													/* Modified and updated by Maxim Bielushkin*/
// Выдернуть шнур, выдавить стекло
var isOpera = self.opera
var isIE = document.all && !isOpera;
/*
if(isIE || isOpera) {	
	window.attachEvent("onload", initG);
} else {	
	window.addEventListener("load", initG, true);
}*/

var imagesinline = 3;
var smallImgWidth = 110;

var picMotionWidth = smallImgWidth+10;
var smallImgHeight = Math.floor(smallImgWidth*1.64);


var m = new Array(0,100);
var t = new Array();

var outImg ="";
var countImg;
var imgArray = new Array();
//var flag = false;
var ordNumber = 0;
var gRecArray = new Array();
var idd;

var popup = null;

if(document.getElementById('nov_motioncontainer')) {
	document.getElementById('nov_motioncontainer').style.overflow="hidden";
	document.getElementById('nov_div_l').style.display="block";
	document.getElementById('nov_div_r').style.display="block";
}
//document.getElementById('galDiv').style.width = 655;
//document.getElementById('manual').style.display = "none";

/*function showPopup(pBigImageSrc) {
	window.open(pBigImageSrc, '', 'width=360, height=570, location=0, address=0, status=0, toolbar=0');
	void 0;
}*/

function showPopup(pBigImageSrc) {
	var interval = null;
	var currOpacity = 0;
	
	appearing = function() {
		if(currOpacity >= 0 && currOpacity <1)	{
			currOpacity = parseFloat(popupImg.style.opacity);
			currOpacity += 0.1;			
			popupImg.style.opacity = currOpacity;
		} else {
			//alert("Cleared!");
			clearInterval(interval);	
		}	
	}
	/*if(popup)
		popup.close();*/
	popup = window.open('', '', 'width=360, height=570, location=0, address=0, status=0, toolbar=0');
	
	popup.document.write('<img id="popupImg" src="" width="340" height="550" border="0">');
	
	popupImg = popup.document.getElementById('popupImg');
	
	if(isIE) {
		popupImg.style.filter = "progid:DXImageTransform.Microsoft.Fade(duration=1.0,overlap=1.0)";
		popupImg.filters[0].Apply();
		
		popupImg.src = pBigImageSrc;
		popupImg.filters[0].Play();
	} else {
		popupImg.style.opacity = 0;
		popupImg.src = pBigImageSrc;
		
		interval = setInterval('appearing()', 70);
	}
	
	//return false;
}

/*function Appearing() {
	
}*/

function addGalBlock() {
	var d = new Date();
	var uniqId = d.getMilliseconds();
	
	while(uniqId < 100 || document.getElementById('galDiv'+uniqId)) {
		uniqId = d.getMilliseconds();
	}
	
	var galBlockHtml = '<TABLE id=mainTbl'+uniqId+' align=center><TBODY><TR><TD align=middle>'+
		'<DIV class="galleryDiv fleft" id=galDiv'+uniqId+'>'+
		'<DIV onclick="div_l('+uniqId+'); void 0;" class=div_l id=nov_div_l'+uniqId+' style="DISPLAY: block">'+
		'<IMG id=leftarr'+uniqId+' height=55 src="img_0/button_left_hid.gif" width=20 border=0></DIV>'+
		'<DIV onclick="div_r('+uniqId+'); void 0;" class=div_r id=nov_div_r'+uniqId+' style="DISPLAY: block">'+
		'<IMG id=rightarr'+uniqId+' height=55 src="img_0/button_right.gif" width=20 border=0></DIV>'+
		'<DIV class=motioncontainer id=nov_motioncontainer'+uniqId+' style="OVERFLOW: hidden">'+
		'<DIV id=nov_motiongallery'+uniqId+' style="POSITION: absolute; TOP: 0pt">'+
		'<DIV id=nov_trueContainer'+uniqId+' style="POSITION: absolute">'+
		'<DIV id=imgSmall'+uniqId+'></DIV>'+
		'</DIV></DIV></DIV></DIV></TD></TR></TBODY></TABLE>';	
	
	//return galBlockHtml;
			
	var galleryTable = '</pre><table id="galleryTable'+uniqId+'" class="galleryTable" cellpadding=0 cellspacing=0 border=0>'+
		'<col width="400"><col width="548">'+	
		'<tr>'+
			'<td class="bigImg vT" id="bigImg'+uniqId+'">Тут будет картинка!</td>'+
			'<td>'+				
				'<table class="h100" cellpadding=0 cellspacing=0 border=0>'+
					'<tr>'+
						'<td class="galText h100 vT" id="galText'+uniqId+'">'+
							'Природа – это внешний мир, в котором мы живем; этот мир подчиняется неизменным на протяжении миллионов лет законам. Природа первична, она не может быть создана человеком и мы должны воспринимать ее как данность.'+							
						'</td>'+
					'</tr>'+
					'<tr>'+
						'<td>'+ galBlockHtml +							
						'</td>'+
					'</tr>'+
				'</table>'+				
			'</td>'+
		'</tr>'+
	'</table>';
	
	galleryTable += '<p><DIV id=galleryContainer'+uniqId+' style="BORDER-RIGHT: red 1px dashed; PADDING-RIGHT: 15px; BORDER-TOP: red 1px dashed; DISPLAY: none; PADDING-LEFT: 15px; PADDING-BOTTOM: 15px; BORDER-LEFT: red 1px dashed; PADDING-TOP: 15px; BORDER-BOTTOM: red 1px dashed">&nbsp;</DIV></p>'+
		'<script language="javascript">createArray("'+uniqId+'");</script>';
	
	document.write(galleryTable);
	document.close();
}

function deleteLastScript() {
	document.scripts[document.scripts.length - 1].innerHTML = '';
}

function clr(obj) {
	var childs = obj.childNodes;
	for(i=0; i<childs.length; i++) {
		if(childs[i] && childs[i].tagName && childs[i].innerHTML.indexOf('addGalBlock') !=0)
			childs[i].innerHTML = childs[i].innerHTML.replace('addGalBlock()', '');
		else
			clr(childs[i]);		
	}
}


function createArray(pUniqId) {	
	
	if (!parent.document.getElementById('templateframe')) {			
				
		document.getElementById('nov_motioncontainer'+pUniqId).style.width = imagesinline * picMotionWidth;
    	document.getElementById('galText'+pUniqId).style.border = "none";
		document.getElementById('bigImg'+pUniqId).style.border = "none";
		document.getElementById('EBPT').style.overflow = "hidden";
		
		var galleryContainer = document.getElementById("galleryContainer"+pUniqId);
		var containerChilds = galleryContainer.childNodes;
		var n=0;
	        
	    for(i=0; i<containerChilds.length; i++){
				    
	        elem = containerChilds[i];
	        if(elem.tagName && elem.tagName == "IMG"){
	                
	    		imgArray[n] = new Image();
	    		loadImage = new Image();
	    		
	    		loadImage.src = elem.src;
	    		
	    		extIndex = loadImage.src.lastIndexOf(".");
			    ext = loadImage.src.substr(extIndex);
			    bigImageSrc = loadImage.src.substr(0, extIndex) + "_big" + ext;
			    
	    		outImg +=
	    			"<div class=\"previewPic\">"+
	    				"<div>"+
	    					//"<img class=\"smallPic\" width=\""+ smallImgWidth +"\" height=\""+smallImgHeight+"\" border=\"0\" style=\"cursor:pointer; cursor: hand;\" onClick=\"showPopup('" + bigImageSrc + "');\" src="+loadImage.src+">"+
	    					"<img class=\"smallPic\" width=\""+ smallImgWidth +"\" height=\""+smallImgHeight+"\" border=\"0\" style=\"cursor:pointer; cursor: hand;\" src="+loadImage.src+">"+
	    				"</div>"+
	    			"</div>";
	    
	            n++;
	        }	    
	    }
	    
	    countImg = n;
	
		document.getElementById('nov_motiongallery'+pUniqId).style.width = countImg * picMotionWidth+"px";
		document.getElementById("imgSmall"+pUniqId).innerHTML = outImg;
		outImg = '';
		
	
		if(n <= imagesinline) {
			document.getElementById("rightarr"+pUniqId).src="img_0/button_right_hid.gif";
			document.getElementById('nov_motioncontainer'+pUniqId).style.width = n * picMotionWidth;
			document.getElementById("galDiv"+pUniqId).style.width = 418 - 120*(imagesinline	- n);
		} else {
			document.getElementById("galDiv"+pUniqId).style.width = 418;	
		}
		
		//++ordNumber;
		gRecArray[gRecArray.length] = new galleryRecord(pUniqId, countImg);
		document.getElementById(pref+"motiongallery"+pUniqId).style.left = -picMotionWidth*gRecArray[getIndex(pUniqId)].startpos+'px';
	}	
}	

function getIndex(pId) {
	for(i=0; i<gRecArray.length; i++)
		if(gRecArray[i].uId == pId)
			return i;
}

 

function galleryRecord(uId, n) {
	this.uId = uId;
	this.startpos = 0;
	this.curPos = 0;
	this.n = n;
	this.crossmain = document.getElementById(pref+"motioncontainer"+uId);
	this.cross_scroll = document.getElementById(pref+"motiongallery"+uId);
	this.menuwidth = this.crossmain.offsetWidth;
	this.actualwidth = document.getElementById(pref+"trueContainer"+uId).offsetWidth;
	this.first = document.getElementById(pref+"motiongallery"+uId);
	this.last = this.first.cloneNode(true);
    this.insertPoint = document.getElementById(pref+"motioncontainer"+uId);
    this.ready = true;
}


    var maxspeed = 10;
   //var startpos=0;
    //var curPos = startpos;
    var pref = "nov_";
    var iedom=document.all||document.getElementById;
	var movestate=null;
	var lefttime=null;
	var righttime=null;
	var speed = false;
    //var ready = true;
    var delta = 0;		
  //  var div_l;
  //  var div_r;
	var actualwidth;
	var first;
	var last;
	var insertPoint;
	var crossmain;
	var cross_scroll;
	var menuwidth;
	var cross;
	//cross_scroll.style.left= -picMotionWidth*gRecArray[idd].startpos+'px'; //(menuwidth-actualwidth)/startpos+'px';	// Вычисление начального смещения путем деления длин двух дивов	
function initportvars(pUId){	
    crossmain 		= gRecArray[getIndex(pUId)].crossmain;
    cross_scroll 	= gRecArray[getIndex(pUId)].cross_scroll;
    menuwidth 		= gRecArray[getIndex(pUId)].menuwidth;										 // menuwidth - Длина верхнего дива
   // div_l=_(pref+"div_l"+iddd);
   // div_r=_(pref+"div_r"+iddd); 
    //actualwidth 	= gRecArray[pUId].actualwidth;             // actualwidth- Длина дива с картинками

    first 			= gRecArray[getIndex(pUId)].first;              		   // Блочок для создания копии полоски картинок
    //last 			= first.cloneNode(true);
    //last.id = pref+'motiongallery_move'+pUId;
    //insertPoint = gRecArray[pUId].insertPoint;
    //insertPoint.appendChild(last);
    //last.style.left = actualwidth+"px";
   
}



function div_l_move(uId){ 
	if (speed == false) {
	    offset = 0;
		cross = cross_scroll; 

	    menu_w = picMotionWidth*1; 
	   gRecArray[getIndex(uId)].curPos--;    	
	    
		speed = true;
		motionengine("left", maxspeed, uId); 
	}
}

                
function div_r_move(uId){ 
	if (speed == false) {
        offset = 0;
		cross = cross_scroll; 
	
	    menu_w = picMotionWidth*1; 
	    gRecArray[getIndex(uId)].curPos++;
    	
		speed = true;
		
		motionengine("right", maxspeed, uId); 
	}
}				
 		
function div_r(uId){
	//iddd=uId;
	initportvars(uId);
	
    if((gRecArray[getIndex(uId)].curPos < (gRecArray[getIndex(uId)].n - imagesinline)) && (gRecArray[getIndex(uId)].ready)){
    	gRecArray[getIndex(uId)].ready = false;
        div_r_move(uId);
    }
}

function div_l(uId){
	//iddd=uId;
	initportvars(uId);
	
    if(gRecArray[getIndex(uId)].curPos > 0 && gRecArray[getIndex(uId)].ready){
        gRecArray[getIndex(uId)].ready = false;
        div_l_move(uId);
    }
}
		
 function checkImg(uId){
 
        if(gRecArray[getIndex(uId)].curPos == 0){
            document.getElementById("leftarr"+uId).src="img_0/button_left_hid.gif";
        }else{
            document.getElementById("leftarr"+uId).src="img_0/button_left.gif";
        }
        
        if(gRecArray[getIndex(uId)].curPos == gRecArray[getIndex(uId)].n-imagesinline){
            document.getElementById("rightarr"+uId).src="img_0/button_right_hid.gif";
        }else{
            document.getElementById("rightarr"+uId).src="img_0/button_right.gif";
        }
 } 		
     
	
/*function which run moveleft and moveright functions*/
function motionengine(direct, maxspeed, uId){								// Джвижущая функция
                                           
         if (direct =="right"){
          scrollspeed=maxspeed;
          clearTimeout(righttime);
          moveleft(uId);	  /*moveleft() - вправо*/		// Все добро двигаем влево, кажется что движение идет вправо
         }
         else if (direct=="left"){
          scrollspeed=maxspeed;
          clearTimeout(lefttime);
          moveright(uId);   /*moveright() - влево*/
         }
         else
          scrollspeed=0;
      }

/*moveleft function*/

function moveleft(uId){
		idd = (uId)?uId:idd;
		if (offset < menu_w) {
		    cross.style.left = parseInt(cross.style.left) - delta+"px";
        }

	    delta  =  Math.floor((menu_w - offset)/4);
	    offset += delta;

        if(menu_w - offset < 4){
            cross.style.left = parseInt(cross.style.left) - (menu_w - offset) +"px";
            stopmotion();
            speed = false; 
            gRecArray[getIndex(idd)].ready = true;
            checkImg(idd);

        }else{
        	
            righttime=setTimeout("moveleft()",25);
        }
 
}

/*moveright function*/

function moveright(uId){
		idd = (uId)?uId:idd;    
		if ( offset < menu_w) {
		    cross.style.left = parseInt(cross.style.left) + delta+"px";
        }

	    delta  =  Math.floor((menu_w - offset)/4);
	    offset += delta
        
        
        
        if(menu_w - offset < 4){
            cross.style.left = parseInt(cross.style.left) + (menu_w - offset) +"px";
            stopmotion();
            speed = false;
            gRecArray[getIndex(idd)].ready = true;
            checkImg(idd);
        } else{        	
            lefttime=setTimeout("moveright()",25);
        }
}


/*End of speed of carousel*/
function stopmotion( e ){
          clearTimeout(lefttime);
          clearTimeout(righttime);
          movestate="";
      }

function _(e) { return document.getElementById ? document.getElementById(e) : eval("document.all."+v); }