/****************************************************************
Cookies
****************************************************************/
function createCookie(name,value){
	var date = new Date();
	date.setTime(date.getTime()+(3*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();

	document.cookie = name+"="+value+"; path=/";
}

function eraseCookie(name){
	createCookie(name,"",-1);
}

function readCookie(name){
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

var cookieName = "visited_pictures111";

function isVisited(name){
	return false;
	var c = readCookie(cookieName);
	if (!c) return 0;
	return c.indexOf(name) != -1;
}

function writeVisited(name){
	if (!isVisited(name)){
		var c = readCookie(cookieName);
		createCookie(cookieName,c+name);
	}
}

/****************************************************************
 Image resizing
****************************************************************/
var imgUrl=0;


var t0 = 800;		// total time
var tr = 400;		// accel/deccel time

var alphaStep = 25;
var alphaDelay = 70;

var photoDiv = document.getElementById("photoDiv");
var photoImg = 0;
var mainDiv = document.getElementById("mainDiv");
var photoNameDiv = document.getElementById("photoNameDiv");
var arrowsDiv =  document.getElementById("arrowsDiv");
var arrowsTd = document.getElementById("arrowsTd");
var rightTable = document.getElementById("rightTable");

var currentOpacity=0;
var imgWaitCycle=0;
var oldBrowser = isOldBrowser();
var isPortfolio = false;

function nextAlphaStep(){

	if (photoImg.readyState != "complete" && imgWaitCycle<300){
		window.setTimeout("nextAlphaStep()",100);
		imgWaitCycle++;

		return;
	}else if (imgWaitCycle>=300){
		//photoNameDiv.innerHTML = ":)";
		return;
	}

	imgWaitCycle = 0;

	currentOpacity+=alphaStep;
	photoImg.style.filter = "Alpha(Opacity="+currentOpacity+");";
	if (currentOpacity <100){
		window.setTimeout("nextAlphaStep()",alphaDelay);
	}else{
		currentOpacity=0;
	}
}

// static
var currentStep = 0;
var width = 650;
var height = 500;
var cx=500;
var cy=0;
var vx0 = 0;
var vy0 = 0;
var sx=0;
var sy=0;
var ax=0;
var ay=0;
var motionStart=0;
var currentTime = 0;
var lastIterationTime = 0;
var onResizeFinished = 0;
var runningMotion = 0;
var hasRightMargin=false;

function x(t,v0,a){
	if (t<tr){
		return a*t*t/2.0;
	}else if(t>=tr && t < t0-tr){
		return v0*tr/2.0+v0*(t-tr);
	}else{
		return v0*tr/2.0+v0*(t0-tr*2)+(v0*(tr - t0+t) - a*(tr - t0+t)*(tr - t0+t)/2);
	}
}


function nextResizeStep(){
	runningMotion = 1;

	var now = new Date();
	currentTime = now.getTime() - motionStart;

	var curX = x(currentTime,vx0,ax);
	var curY = x(currentTime,vy0,ay);

	/*document.getElementById("traceDiv").innerText =
		"\nxy(t) = " + curY +
			"\ncurrentTime = " + currentTime +
					"\nvy0 = " + vy0 ;
		*/
	photoDiv.style.width = (width +curX) +"px";
	photoNameDiv.style.width = (width +curX-20) +"px";
	photoDiv.style.height = (height +curY) +"px";
	if (rightTable)
		rightTable.style.height = (height +curY +5) +"px";


	if (hasRightMargin){
		arrowsDiv.style.width = (width +curX)/2 - 40 + "px";
	}else{
		arrowsDiv.style.width = (width +curX)/2 +10+ "px";
	}

	if (!oldBrowser){
		mainDiv.style.marginTop = -(height +curY+60)/2 + "px";
	}else{
		mainDiv.style.top = document.body.offsetHeight/2-30;//"283px";
		mainDiv.style.marginTop = -(height +curY+60)/2 + "px";
	}

	if (currentTime < t0){
		setTimeout("nextResizeStep();",10);
	}else{
		photoDiv.style.width = cx +"px";
		photoDiv.style.height = cy + "px";
		// Resizing finished
		runningMotion=0;

		width = cx;
		height = cy;

		if (onResizeFinished){
			onResizeFinished();
		}
	}

	lastIterationTime = currentTime;

}

var _cx,_cy,_onResizeFinished,_photoDiv;
function resize(__cx,__cy,__onResizeFinished,__photoDiv){
	_cx = __cx;
	_cy = __cy;
	_onResizeFinished = __onResizeFinished;
	_photoDiv = __photoDiv;
	//waitForImages(resize2
	resize2();
}

function resize2(){
	/*if (!flag) {
		alert(document.images[0].complete);
		setTimeout("resize(__cx,__cy,__onResizeFinished,__photoDiv);",2000);
		return;
	}*/

	if (_photoDiv)
		photoDiv = _photoDiv;

	//height = parseInt(photoDiv.style.height);
	//width = parseInt(photoDiv.style.width);

	 _cx = parseInt(_cx);
	 _cy = parseInt(_cy);

	if (_cx < 420){
		_cx += 100;
		hasRightMargin = true;
	}else{
		hasRightMargin = false;
	   }

	vx0 = (_cx - width)/(t0-tr);
	ax = vx0/tr;

	vy0 = (_cy - height)/(t0-tr);
	ay = vy0/tr;

	currentTime = 0;

	var now = new Date();
	lastIterationTime = currentTime = motionStart = now.getTime();

	onResizeFinished = function(){
		_onResizeFinished();
	}

	cx = _cx;
	cy = _cy;

	if (Math.abs(_cy - height) <= 3 && Math.abs(_cx - width) <= 3){
		photoDiv.style.width =cx+"px";
		photoDiv.style.height = cy +"px";
		onResizeFinished();
		return;
	}


	if (!runningMotion)
		nextResizeStep();
}

var myHash;

function obtainPicts() {
    if (picts.length == 0) {
        var i = 0;
        var obj;
        while (i < 100) {
            var obj = document.getElementById('ph_' + i);
            if (!obj) {
                i = 100;
            } else {
                pictures[obj.getAttributeNode('fname').value] = i;
                picts.push(obj.getAttributeNode('fname').value);
            }
            i++;
        }
    }
}

function checkHash() {
    if (picts.length == 0) obtainPicts();
    var th = window.location.hash;
    if (th.length > 1) {
        th = th.replace(/^#+/, '');
        if (myHash != th && th != '') {
            myHash = th;
            document.getElementById('ph_'+pictures[myHash]).onmousedown();
        }
    }
    var t = setTimeout("checkHash()", 200);
}

var pictures = new Array();
var picts = new Array();

function loadPhoto(_url,_cx,_cy,_next){
	if (imgUrl == _url){
		return;
	}

	photoDiv.innerHTML='<a href="#'+_next+'" class="noborder"><img id="photoImg" src="/images/spacer.gif" style="width: 450px; height: 220px" alt="Photo canvas"></a>';

	photoImg = document.getElementById("photoImg");

	imgUrl = _url;
	photoImg.style.display = "none";
	photoImg.src="/images/spacer.gif";
	photoImg.src=_url;
	photoImg.style.width= _cx+"px";
	photoImg.style.height= _cy+"px";

//	hideElement('thumbDiv');
	showElement('thumbDiv');

	resize(_cx,_cy,
		function(){
			photoImg.style.display = "";

			photoDiv.style.width =  cx;
			photoDiv.style.height =  cy;

			//photoImg.style.filter = "Alpha(Opacity=00);";
			imgWaitCycle = 0;
			//nextAlphaStep();

			showElement('squaresDiv');
			showElement('arrowsDiv');
			showElement('photoNameDiv');
			showElement('menuTd');
			showElement('menuTd2');
			showElement('menuTd3');

		}
	);
}

function loadHtml(html,_cx,_cy,_onLoad){
	//alert(11);
	imgUrl=0;
	photoDiv.innerHTML = "";

	photoDiv.style.width = (_cx) +"px";
	photoNameDiv.style.width = (_cx-20) +"px";
	photoDiv.style.height = (_cy) +"px";

	photoDiv.innerHTML = deReplaceQuotes(html);
	if (_onLoad) _onLoad();
}

function textImg(str,foreColor,backColor,align){
	//return str;

	var c1 = (foreColor >> 16)&0x000000FF;
	var c2 = (foreColor >> 8)&0x000000FF;
	var c3 = (foreColor)&0x000000FF;

	var f1 = (backColor >> 16)&0x000000FF;
	var f2 = (backColor >> 8)&0x000000FF;
	var f3 = (backColor)&0x000000FF;

	if (!align) align="left";

	return "<img src='/txt.php?text="+replaceQuotes(str)+
		"&c1="+c1+
		"&c2="+c2+
		"&c3="+c3+
		"&f1="+f1+
		"&f2="+f2+
		"&f3="+f3+
		"' "+
		" border=0 align='"+align+"'>";

}

function textImg2(str,foreColor,backColor,align){
	//return str;

	var c1 = (foreColor >> 16)&0x000000FF;
	var c2 = (foreColor >> 8)&0x000000FF;
	var c3 = (foreColor)&0x000000FF;

	var f1 = (backColor >> 16)&0x000000FF;
	var f2 = (backColor >> 8)&0x000000FF;
	var f3 = (backColor)&0x000000FF;

	if (!align) align="left";
	///return str;
	return "<img   src='txt.php?text="+replaceQuotes(str)+
		"&c1="+c1+
		"&c2="+c2+
		"&c3="+c3+
		"&f1="+f1+
		"&f2="+f2+
		"&f3="+f3+
		"'  "+
		" border=0 align='"+align+"'>";

}

/* ***************************************************************
 Squares
*************************************************************** */
var lastSelectedSquare=0;
var lastHoveredSquare=0;
var squaresArrayHeight=0;
var squaresArraySize=0;
function toPhoto(dir){
	//alert(55);

	var currentSqareNumber=0;
	var i=0;
	var currentSq=0;
	var nextSq=0;
	var sq = 0;

	while (i < 100){
		sq = document.getElementById("ph_"+i)

		if (sq == lastSelectedSquare){
			currentSq=sq;

			var nextSqId= dir==1?i+1:i-1;

			if (i == squaresArraySize-1 && dir == 1)
				nextSqId = 0;
			else if (i == 0 && dir != 1){
				nextSqId = (squaresArraySize-1);
			}

			nextSq = document.getElementById("ph_"+(nextSqId));

			if (nextSq){
				nextSq.onmousedown();
			}else{
				document.getElementById("ph_0").onmousedown();
			}

			return;
		}

		i++;
	}
}

function onPhotoSquareMouseOver(square,thumbnail){
	if (lastSelectedSquare != square)
		square.src="/images/square_hlight.gif";

	if (lastHoveredSquare != square && lastHoveredSquare != lastSelectedSquare)
		lastHoveredSquare.src="/images/square_normal.gif";

	lastHoveredSquare = square;

	showElement('thumbnail');
	document.getElementById("thumbnail").src = thumbnail;
}

function getPrevNext(filename) {
    filename = filename.replace(/^\/images\/photos\//i, '');
    var ret = new Array();
    var prev = pictures[filename] - 1;
    var next = pictures[filename] + 1;
    var all = picts.length - 1;
    if (prev < 0) {
        prev = all;
    }
    if (next > all) {
        next = 0;
    }
    ret['prev'] = picts[prev];
    ret['next'] = picts[next];
    return ret;
}

function onPhotoSquareMouseDown(square,imgName,w,h,hint,galleryName,galleryId,npr){

	if(lastSelectedSquare){
		lastSelectedSquare.src = "/images/square_normal.gif";
	}

	square.src="/images/square_selected.gif";
	
	a = getPrevNext(imgName);

	loadPhoto(imgName,w,h,a['next']);
	document.getElementById("prev").href="#"+a['prev'];
	document.getElementById("next").href="#"+a['next'];
	var t = 0;
	//if (!oldBrowser)
	//	t = decodeURIComponent(hint);
	//else
		t = hint;

	t = t.replace(/\&nbsp;/g," ");
	photoNameDiv.innerHTML = textImg2(t+" ",0x00999BA2,0x00333C46,"right");

	if (galleryId != 666 && galleryId && !isPortfolio){
		if (frm && frm == "portfolio") {
		    document.getElementById('homeBtn').src = "/images/back_to_portfolio.jpg";
		    document.getElementById('homeLink').href="javascript: void loadContent(\"gallery.php\",document.getElementById(\"porfolioLink\"));";
	} else {
	    document.getElementById('homeBtn').src = "/images/back_to_"+(npr?"new_projects":"galleries")+".jpg";
		document.getElementById('homeLink').href="javascript: void loadContent(\""+(npr?"new_projects":"galleries")+".php\",document.getElementById(\""+(npr?"newprojects":"gallery")+"Link\"));";
	}
	}else if (isPortfolio){
	    if (galleryId != 666 && galleryId) {
	        document.getElementById('homeBtn').src = "/images/see_gallery.gif";
		document.getElementById('homeLink').href="javascript: void loadContent(\"gallery.php&from=portfolio&gallery="+galleryId+"\",document.getElementById(\""+(npr?"newprojects":"gallery")+"Link\"));";
	} else {
		document.getElementById('homeBtn').src = "/images/spacer.gif";
	}
	}

	lastSelectedSquare = square;
}


/* visited photos */

function markVisitedAndLoadRandom(pid){
	var squares = document.getElementsByName("photoSquare");
	if (picts.length == 0) obtainPicts();
	var randomPhoto = Math.round((squares.length-1)*Math.random());
	var photoSelected = false;
	for (var i=0; i< squares.length; i++){
		if (isVisited(squares[i].id))
			squares[i].src="/images/square_hlight.gif";
        if (pid == '0') {
    		if (i == randomPhoto){
    			if (squares[i].id){
    				window.location.hash = '#' + picts[i];
    				photoSelected = true;
    			}else{
    				randomPhoto++; // hack
    			}
    		}
    	} else {
    	    if (squares[i].id == pid) {
    	        window.location.hash = '#' + picts[i];
    		    photoSelected = true;
    	    }
        }
	}

	if (!photoSelected && squares.length){
		window.location.hash = '#' + picts[0];
	}
}

var _onLoad;
var tries=0;
function waitForImages(onLoad){
	onLoad();
	return;
	_onLoad = onLoad;

	var flag=true;
	var notLoaded=0;
	var str="";
	for (var i=0; i<document.images.length;i++){
		if (!document.images[i].complete){
			notLoaded++;
			str += document.images[i].src+"<br>";
		}
	}

	//photoDiv.innerHTML = str;

	if (notLoaded > 0 && tries>20) {
		//alert(notLoaded+"/"+document.images.length);
		tries++;
		setTimeout("waitForImages(_onLoad);",200);
		return;
	}

	onLoad();
}

function showElement(id){
	var e = document.getElementById(id);
	if (e){
		e.style.display="";
	}
}

function hideElement(id){
	var e = document.getElementById(id);
	if (e){
		e.style.display="none";
	}
}

function isOldBrowser(){
	return (!navigator.userAgent ||
				navigator.userAgent.indexOf("Mac_PowerPC")!=-1 ||
				(navigator.userAgent.indexOf("Windows NT 5.0") != -1 &&
				navigator.userAgent.indexOf("MSIE 5") != -1)
	);
}

function move_box(an, box) {
	  var cleft = 0;
	  var ctop = 0;
	  var obj = an;
	  while (obj.offsetParent) {
	    cleft += obj.offsetLeft;
	    ctop += obj.offsetTop;
	    obj = obj.offsetParent;
	  }
	  box.style.left = cleft + 'px';
	  ctop += an.offsetHeight -0;
	  if (document.body.currentStyle &&
	    document.body.currentStyle['marginTop']) {
	    ctop += parseInt(
	      document.body.currentStyle['marginTop']);
	  }
	  box.style.top = ctop + 'px';
}

function showArticle(g,t){
	var w = window.open('showArticle.php?text='+g,'w1','menubar=no,resizable=no,scrollbars=yes,toolbar=no,left=270,top=130,width=450,height=530');
}

function replaceQuotes(str){
	//return preg_replace(array("[\"]","[']"),array("&qqq1;","&qqq2;"),$str);
	var s = str.replace("[\']","_q1_");
	s = s.replace("[\"]","_q2_");
	s = s.replace("&","_amp_");
	s = s.replace("#","_shrp_");
	return s;
}

function deReplaceQuotes(str){
	var s = str.replace(/_q1_/g,"'");
	s = s.replace(/_q2_/g,'"');
	s = s.replace(/_amp_/g,'&');
	s = s.replace(/_shrp_/,"#");
	return s;
}

var txt;

function debugEcho (what, pr) {
    if (!pr) {
        pr = "";
        txt = "";
    }
    if (typeof(what) == 'array' || typeof(what) == 'object') {
        txt += "Array\n";
        pr += "  ";
        var k = null;
        for (k in what) {
            txt += pr + "|" + k + "| => ";
            debugEcho (what[k], pr);
        }
    } else {
        txt += what +"\n";
    }
}