var currentPic=0;
var oldCurrentPic=0;
var maxPic=1;
var cat=0;
var iTimer;
var comments=0;

var newImage		= new Image();

var isSlShow		= 0;
var isPlay			= 0;
var isShowCaptions	= 1;
var isHideInterface	= 1;

var slideShowInterfaceTimer;
var slideShowTimeoutTimer;
var slideShowInfoTimeoutTimer;

var fadeTimeout;

var ie=false;

var rightListW	= 145;
var leftMenuW	= 195;
var topMenuH	= 25;

var MIN_DESKTOP_W = 1000;

//var sizeX		= 100;
//var sizeY		= 100;

var imgXY;

var slideShowTimeout			= 5000;
var slideShowIntefaceTimeout	= 3000;
var slideShowInfoTimeout		= 1000;

var photosList = new Array();
var photosIdxList = new Array();


document.onmousemove	= mouseMove;
document.onmouseup  	= mouseUp;
document.onkeyup		= keyUp;

function Picture(id,picCatId,picFname,picViews,descTitle,descBody,picRating,picVoters,picCatName,date,time,model,manufacturer){
	this.id=id;
	this.picCatId=picCatId;
	this.picFname=picFname;
	this.picViews=picViews;
	this.descTitle=descTitle;
	this.descBody=descBody;
	this.picRating=picRating;
	this.picVoters=picVoters;
	this.picCatName=picCatName;
	this.date=date;
	this.time=time;
	this.model=model;
	this.manufacturer=manufacturer;
}




if (navigator.appName=="Microsoft Internet Explorer") ie=true;

tmpImage = new Image();

//loadin  = new Image();
//loadin.src = HOST_BASE_URL+"img/loading.gif";

function ToggleMenu(){
	if(document.getElementById("menuLayer").style.display=="none")	showMenu();
	else hideMenu();
}

function hideMenu(){
	document.getElementById("menuLayer").style.display="none";
	//Effect.DropOut('menuLayer');
}

function showMenu(){
	 //Effect.Appear('menuLayer');
	document.getElementById("menuLayer").style.display="block";
}

/**
* Get maximum rectangle for main image.
* Return array(width, height)
*/
function getMaxImgXY(){
	var winSize = getWindowSize();
	if(isSlShow == 1){
		imgX = winSize[0];
		imgY = winSize[1];
	}
	else{
		rightListW = document.getElementById("PhotMenu").offsetWidth;
		//alert(MIN_DESKTOP_W +"<"+ winSize[0]);
		if(MIN_DESKTOP_W > winSize[0]){
			imgX = winSize[0] - rightListW - 4;
		}
		else{
			imgX = winSize[0] - leftMenuW-rightListW-4-10;
		}
		imgY = winSize[1] - topMenuH-4;
	}
	
	return new Array(imgX, imgY);
}



function adjustSize(){
	if(isMobile){
		adjustSizeMobile();
	}
	else{
		var winSize = getWindowSize();
		if ((winSize[1]-575)<0){
			document.getElementById("menuLayer").style.top="10px";
		}else{
			document.getElementById("menuLayer").style.top=(winSize[1]-575)/2 +"px";	
		}
		document.getElementById("menuLayer").style.left=(winSize[0]-460)/2+"px";
		
		document.getElementById('photMenuWrap').style.width=winSize[0]-rightListW + 'px';
		if(! isAndroid){
			document.getElementById('PhotMenu').style.height = winSize[1] + 'px';
		}

	}
}

function getWindowSize() {
	var w = 0, h = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		// Non-IE
		w = window.innerWidth;
		h = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		// IE 6+ in 'standards compliant mode'
		w = document.documentElement.clientWidth;
		h = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		// IE 4 compatible
		w = document.body.clientWidth;
		h = document.body.clientHeight;
	}
	return new Array(w,h);
}



function positionMainImg(){
	var winSize = getWindowSize();
	var imgDiv = document.getElementById('mainImgDiv');
	
	if(isSlShow == 1){
		imgDiv.style.left	= Math.floor((winSize[0]-imgDiv.offsetWidth)/2) +'px';
		imgDiv.style.top	= Math.floor((winSize[1]-imgDiv.offsetHeight)/2) +'px';
	}
	else{
		rightListW = document.getElementById("PhotMenu").offsetWidth;
		
		if(MIN_DESKTOP_W > winSize[0]){
			var desiredLeft = (winSize[0]-rightListW-imgDiv.offsetWidth)/2;
			if(desiredLeft > 0){
				imgDiv.style.left	= Math.floor(desiredLeft)+'px';
			}
			else{
				imgDiv.style.left	= '0px';
			}
			//imgDiv.style.left	= Math.floor((winSize[0]-rightListW-imgDiv.offsetWidth)/2)+'px';
			//document.getElementById("detailsDiv").style.background="url('images/white_50pct.png') transparent";
			document.getElementById("detailsDiv").style.margin="25px 0px 20px 0px";
			document.getElementById("likeFrame").style.display="none";
		}
		else{
			if(!isMobile){
				document.getElementById("likeFrame").style.display="block";
			}
			
			imgDiv.style.left	= Math.floor((winSize[0]-rightListW-leftMenuW-imgDiv.offsetWidth)/2)+leftMenuW+'px';
		}
		

		
		var desiredTop = Math.floor((winSize[1]-imgDiv.clientHeight-topMenuH)/2);
		if(desiredTop > 0){
			imgDiv.style.top = desiredTop + topMenuH + 'px';
		}
		else{
			imgDiv.style.top = topMenuH + 'px';
		}
		//imgDiv.style.top	= Math.floor((winSize[1]-imgDiv.clientHeight-topMenuH)/2) + topMenuH +'px';
		//alert(winSize[1]+"-"+imgDiv.offsetHeight+"-"+topMenuH);
	}
}


function checkPic(){
	if(newImage.complete){
		if(ie){
			document.getElementById('mainImg').filters[0].apply();
			document.getElementById('mainImg').src=newImage.src;
			if(mainImg.filters[0].status==1){
				mainImg.filters[0].play();
			}
		}
		else{
			document.getElementById('mainImg').src=newImage.src;
		}
		positionMainImg();
		updatePictureDetailsObj(photosList[currentPic]);
		
		if(isPlay == 1){
			slideShowTimeoutTimer = setTimeout('next()', slideShowTimeout);
		}
		hideWait();

		var nextFileName = "http://dmpaykin.appspot.com/img?ac=load&w="+imgXY[0]+"&h="+imgXY[1]+"&n="+getPicture('next').picFname;
		//var nextFileName = IMG_URL+"?constrain=true&w="+imgXY[0]+"&h="+imgXY[1]+"&img="+getPicture('next').picFname;
		tmpImage.src=nextFileName;
	}
	else{
		showWait();
		//document.getElementById('loadingLayer').style.visibility="visible";
		//document.getElementById('loadingBgLayer').style.visibility="visible";
	
		setTimeout('checkPic()', 200);
	}
}

function showWait(){
	if(!isMobile){
		document.getElementById('loadingLayer').style.visibility="visible";
		document.getElementById('loadingBgLayer').style.visibility="visible";
	}
}
function hideWait(){
	if(!isMobile){
		fadeOut('loadingLayer',300);
		document.getElementById('loadingBgLayer').style.visibility="hidden";
	}
}
// Border Functions \\
function setBorder(obj){
	obj.className = 's_img_sel'
}

function clrBorder(obj){
	obj.className = 's_img';
}

/*
function mouseWheel(){
if(event.wheelDelta>=120) prev();
else next();
}

function scrollDown(){iTimer=setInterval('document.getElementById("scDiv").doScroll("Down")', 120);}

function scrollUp(){iTimer=setInterval('document.getElementById("scDiv").doScroll("Up")', 120);}

function stopScroll(){clearInterval(iTimer);}
*/
function updatePictureDetails(xmlDoc){
/*	
	document.getElementById("ratingInp").value=xmlDoc.getElementsByTagName("newrating")[0].childNodes[0].nodeValue;
	document.getElementById("votersSpan").innerHTML=xmlDoc.getElementsByTagName("voters")[0].childNodes[0].nodeValue;
	document.getElementById("viewsSpan").innerHTML=xmlDoc.getElementsByTagName("views")[0].childNodes[0].nodeValue;
*/	
//			document.getElementById("comCell").innerHTML=(xmlDoc.getElementsByTagName("desc_title")[0].childNodes[0])?xmlDoc.getElementsByTagName("desc_title")[0].childNodes[0].nodeValue : " ";
	
	resetRating();
}


function updatePictureDetailsObj(pic){
	document.getElementById("ratingInp").value=pic.picRating;
	document.getElementById("votersSpan").innerHTML=pic.picVoters;
	document.getElementById("viewsSpan").innerHTML=pic.picViews;
	
	document.getElementById("picDate").innerHTML=pic.date;
	document.getElementById("picTime").innerHTML=pic.time;
	
	
	document.getElementById("slideShowCaptions").innerHTML=pic.descTitle + ", " + pic.date + " " + pic.time;
	
	document.getElementById("comCell").innerHTML=pic.descTitle;
	document.getElementById("downloadLnk").href = downloadUrl + pic.picFname;
	
	if(!isMobile){
		document.getElementById("likeFrame").src = FACEBOOK_CAT_URL + "p"+pic.id;
	}

	if(isSlShow==1){
		//document.getElementById("slideShowCaptions").innerHTML=pic.descTitle;
		if(isShowCaptions==1 && pic.descTitle != ''){
			document.getElementById("slideShowCaptions").style.visibility = 'visible'
		}
		else{
			document.getElementById("slideShowCaptions").style.visibility = 'hidden'
		}
	}
	
	
	resetRating();
}





var dragObject  = null;
var mouseOffset = null;
var nMousePositionX;
var nMousePositionY;


function getMouseOffset(target, ev){
	ev = ev || window.event;

	var docPos    = getPosition(target);
	var mousePos  = mouseCoords(ev);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function getPosition(e){
	var left = 0;
	var top  = 0;
	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}
	left += e.offsetLeft;
	top  += e.offsetTop;
	return {x:left, y:top};
}

function mouseMove(ev){
	ev           = ev || window.event;
	var mousePos = mouseCoords(ev);

	nMousePositionX = mousePos.x;
	nMousePositionY = mousePos.y;

	if(dragObject && dragObject != null){
		dragObject.style.position = 'absolute';
		dragObject.style.top      = mousePos.y - mouseOffset.y;
		dragObject.style.left     = mousePos.x - mouseOffset.x;
		return false;
	}
	
	if(isSlShow == 1){
		showSlideShowInterface();
	}
	
}
function mouseUp(){
	dragObject = null;
}

function makeDraggable(event,item){

	if(typeof(item) != 'object'){
		item = document.getElementById(item);
	}

	if(!item) return;
	dragObject  = item;
	mouseOffset = getMouseOffset(item, event);
}

function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	if(document.body==null){
		return {x:0, y:0};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}




//	Start rating \\
function roundRating(rating){
	var base = Math.floor(rating);
	var rest = rating - base;
	
	if(rest < 0.33 ){
		res = base;
	}else{
		if (rest < 0.66){
			res = base + 0.5;
		}else{
			res = base + 1;
		}
	}	
	return res;
}
function resetRating(){
	currentRating = document.getElementById("ratingInp").value;
	doSetRating(currentRating);
}
function setRating(rating, timeout){
	if (timeout>0){
		doSetRating(rating);
		setTimeout("doSetRating("+rating+");",timeout)
	}else{
		doSetRating(rating)
	}
}
function doSetRating(rating){
	rating=roundRating(rating);	
	for (i=1; i<=5; i++){
		starObj=document.getElementById("starsImg_" + i);
		
		if(i-0.5 == rating){
			starObj.src=STARS_HALF_URL
		}else{
			if(rating >= i) {starObj.src=STARS_ONE_URL;}
			if(rating < i) {starObj.src=STARS_ZERO_URL;}
		}
	}
}
// End rating \\




//	//	//	// Slide Show  \\	\\	\\	\\
function startSlideShow(isAutoPlay){
	isSlShow = 1;
	if(isAutoPlay){
		isPlay = 1;
		document.getElementById('slideShowPause').style.display='block';
		document.getElementById('slideShowPlay').style.display='none';
	}

	hideInterface();
	positionMainImg();
	displayTimeout();
	showSlideShowInterface();
	reloadPic();
	
}
function endSlideShow(){
	clearInterval(slideShowInterfaceTimer);
	clearTimeout(slideShowTimeoutTimer);

	isPlay = 0;
	isSlShow = 0;

	document.getElementById('slideShowPause').style.display='none';
	document.getElementById('slideShowPlay').style.display='block';
	showInterface();
	positionMainImg();
	hideSlideShowInterface();
	reloadPic();
}

function hideInterface(){
	document.getElementById('photMenuWrap').style.display = 'none';
	document.getElementById('PhotMenu').style.display = 'none';
	document.getElementById('detailsDiv').style.display = 'none';
	document.getElementById('likeFrame').style.display = 'none';
	document.getElementById('menuLayer').style.display = 'none';
	document.getElementById('slideShowInterface').style.display = 'block';
	document.body.className = 'bodySlideShow';
}

function showInterface(){
	document.getElementById('PhotMenu').style.display = 'block';
	if(isMobile){
		document.getElementById('mainImgDiv').style.display='none';
	}
	else{
		document.getElementById('photMenuWrap').style.display = 'block';	
		document.getElementById('likeFrame').style.display = 'block';
	}
	document.getElementById('detailsDiv').style.display = 'block';
	document.getElementById('slideShowInterface').style.display = 'none';
	document.body.className = '';
}

function hideSlideShowInterface(){
	clearInterval(slideShowInterfaceTimer);
	fadeOut('slideShowControls',300);
	//document.getElementById('slideShowControls').style.visibility = 'hidden';
}

function showSlideShowInterface(){
	clearInterval(slideShowInterfaceTimer);
	if(isHideInterface==1){
		slideShowInterfaceTimer = setInterval('hideSlideShowInterface();', slideShowIntefaceTimeout);		
	}
	fadeIn('slideShowControls',300);
	
/*	else{
		document.getElementById('slideShowControls').style.display = 'block';
		document.getElementById('slideShowControls').style.visibility = 'visible';
	}
*/	
}

function next(){
	if(isPlay == 0){
		showInfoDiv('Next');
	}
	var pic = getPicture('next');
	changePic(pic.id);
}

function prev(){
	if(isPlay == 0){
		showInfoDiv('Prev');
	}
	var pic = getPicture('prev');
	changePic(pic.id);
}

function reloadPic(){
	var pic = photosList[currentPic];
	if(pic != null){
		changePic(pic.id);
	}
}

function pause(){
	showInfoDiv('Pause');
	isPlay = 0;
	document.getElementById('slideShowPause').style.display='none';
	document.getElementById('slideShowPlay').style.display='block';
	clearTimeout(slideShowTimeoutTimer);
}

function play(){
	showInfoDiv('Play');
	isPlay = 1;
	document.getElementById('slideShowPause').style.display='block';
	document.getElementById('slideShowPlay').style.display='none';
	next();
}

function plus(){
	slideShowTimeout += 1000;
	displayTimeout();
}

function minus(){
	if(slideShowTimeout >= 4000){
		slideShowTimeout -= 1000;
	}
	displayTimeout();
}


function displayTimeout(){
	document.getElementById('slideShowTimeout').innerHTML = slideShowTimeout/1000;
}


function getPicture(mode){
	var maxPic = photosIdxList.length;
	var result = null;
	for (i = 0; i < maxPic; i++){
		if (photosIdxList[i] == currentPic){
			if(mode == 'next'){
				idx = i + 1;
				if(idx >= maxPic){
					idx = 0;
				}
			}
			else{
				idx = i - 1;
				if (idx < 0){
					idx = maxPic -1;
				}
			}
			return	photosList[photosIdxList[idx]];
		}
	}
	return null;
}

function keyUp(e){
	var keyCode = (window.event) ? event.keyCode : e.keyCode;
	if(isSlShow == 1){
		switch (keyCode){
		case 32:
			if(isPlay == 1){
				pause();
			}else{
				play();
			}
			break;
		case 39:
			next();
			break;
		case 37:
			prev();
			break;
		case 27:
			endSlideShow();
			break;
		default:
			break;
		}
	}	
}

function showInfoDiv(msg){
	document.getElementById("slideShowInfo").innerHTML = msg;
	document.getElementById("slideShowInfo").style.display = 'block';
	document.getElementById("slideShowInfo").style.visibility = 'visible';
	clearTimeout(slideShowInfoTimeoutTimer);
	slideShowInfoTimeoutTimer = setTimeout('fadeOut("slideShowInfo",200);', slideShowInfoTimeout);	

//	slideShowInfoTimeoutTimer = setTimeout('document.getElementById("slideShowInfo").style.display="none";', slideShowInfoTimeout);	
}

function toggleCaptions(){
	if(isShowCaptions==0){
		isShowCaptions = 1;
		
		document.getElementById('slideShowCaptionsBtn').innerHTML = 'Hide captions';
		if (document.getElementById('slideShowCaptions').innerHTML != ''){
			document.getElementById('slideShowCaptions').style.visibility = 'visible';
		}
	}
	else{
		isShowCaptions = 0;
		document.getElementById('slideShowCaptionsBtn').innerHTML = 'Show captions';
		document.getElementById('slideShowCaptions').style.visibility = 'hidden';
	}
}

function preloadSlideshowData(){
	bgTmp  = new Image();
	bgTmp.src = HOST_BASE_URL+"img/slShowIntBg.png";	
	prevTmp  = new Image();
	prevTmp.src = HOST_BASE_URL+"img/slShowPrev.gif";
	playTmp  = new Image();
	playTmp.src = HOST_BASE_URL+"img/slShowPlay.gif";
	pauseTmp  = new Image();
	pauseTmp.src = HOST_BASE_URL+"img/slShowPause.gif";
	playTmp  = new Image();
	playTmp.src = HOST_BASE_URL+"img/slShowPlay.gif";
	nextTmp  = new Image();
	nextTmp.src = HOST_BASE_URL+"img/slShowNext.gif";
	exitTmp  = new Image();
	exitTmp.src = HOST_BASE_URL+"img/slShowExit.gif";
	plusTmp  = new Image();
	plusTmp.src = HOST_BASE_URL+"img/slShowPlus.gif";
	minusTmp  = new Image();
	minusTmp.src = HOST_BASE_URL+"img/slShowMinus.gif";	

	photMenu_TTmp  = new Image();
	photMenu_TTmp.src = HOST_BASE_URL+"images/photMenu_T.gif";	
	photMenu_BTmp  = new Image();
	photMenu_BTmp.src = HOST_BASE_URL+"images/photMenu_B.gif";	
	photMenu_MTmp  = new Image();
	photMenu_MTmp.src = HOST_BASE_URL+"images/photMenu_M.gif";	

}


var fadedObjects = new Array();
function findInArray(array,obj){
	var res = -1;
	var len = array.length;
	for(i=0; i<len; i++){
		if(array[i] == obj){
			res = i;
			break;
		}
	}
	return res;
}

function setOpacity(id, opacity){
	obj = document.getElementById(id);
	obj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+opacity+')';
	obj.style.opacity = opacity/100;
	if(opacity==0){
		obj.style.visibility = 'hidden';
		obj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+100+')';
		obj.style.opacity = 1;
	}
	if(opacity > 0 ){
		obj.style.visibility = 'visible';
	}
	
}

function fadeOut(id, millisec){
	obj = document.getElementById(id);
	
	if(obj.style.visibility != 'hidden'){
		clearTimeout(fadeTimeout);
		
		var speed = Math.round(millisec / 20); 
		var timer = 0; 
		for (i = 100; i >= 0; i-=5){
			fadeTimeout = setTimeout('setOpacity("'+id+'", '+i+');', timer*speed);	
			timer++;
		}
	}
}

function fadeIn(id, millisec){
	obj = document.getElementById(id);
	
	if(obj.style.visibility != 'visible'){
		clearTimeout(fadeTimeout);
		var speed = Math.round(millisec / 20); 
		var timer = 0; 
		for (i = 10; i <= 105; i+=5){
			setTimeout('setOpacity("'+id+'", '+i+');', timer*speed);	
			timer++;
		}
	}
}







function attachTouchHandlers(){
	
	document.addEventListener('touchstart', function(event) {
		touchStart = event.touches[0];
	}, false);
	document.addEventListener('touchend', function(event) {
		var dx = touchEnd.pageX - touchStart.pageX;
		var dy = touchEnd.pageY - touchStart.pageY;
		
		if(Math.abs(dx) > Math.abs(dy)){ // horizontal -> next/rev
			if(Math.abs(dx) > 50){
				if(dx > 0){
					next();
				}
				else{
					prev();
				}
				event.preventDefault();
			}
		}
		else{ // vertical
			if(Math.abs(dy) > 50){
			
			}
			else{
	
			}
		}
		touchStart = null;
		touchEnd=null;
	}, false);		
	
	document.addEventListener('touchmove', function(event) {
		touchEnd = event.touches[0];
	    //event.preventDefault();
	  //  var touch = event.touches[0];
	    //alert("Touch x:" + touch.pageX + ", y:" + touch.pageY);
	}, false);
}

function adjustSizeMobile(){
	var THUMB_WIDTH = 120;
	
	var winSize = getWindowSize();
	var margin = (winSize[0]%120)/2
	
	document.getElementById('PhotMenu').style.margin = '25px '+margin+'px';
}

function initMobile(){
	attachTouchHandlers();
	window.scrollTo(0,1);
	
	//document.getElementById('photMenuWrap').style.display='none';
	
	var links = document.getElementById("PhotMenu").getElementsByTagName("a");
	var linksNo = links.length;

	for(var i=0; i<linksNo; i++){
		var link = links[i];
		document.addEventListener('click', function(event) {
			startSlideShow();
			document.getElementById('mainImgDiv').style.display='block';
			
			event.preventDefault();
		}, true);	
	}	
}


{
}

