/** Variables list **/
var ib = '';
var to = '';
var galleryImg 	= '';
var myAnim		= '';
var myAlbum		= '';
var currentPage = 0;

//
var myUrl = window.location.href;
if (((charPos = myUrl.indexOf('#')) > -1) && (myUrl.indexOf('/users/photo') > -1)) {
	image_id = myUrl.substring(charPos+1);
	imge		= image_id.split("_");
	var url = "/users/photo/"+imge[0];
	if (typeof imge[1] != 'undefined') {
		url+="/_"+imge[1]
	}
	window.location = url;
}

/** Basic initialization **/
function initInfoBar() {
	if ($('galleryPicture') == null) return;
	appendToLog('Initializing info bar!');

	//Get gallery to load
	var gal = 0;
	if ((fromchar = myUrl.indexOf('_')) > -1 && (tochar = myUrl.indexOf("#"))) {
		//if (tochar == -1) tochar=null;
		myAlbum = gal = myUrl.substring(fromchar+1);
	}

	ib = new ibInit('ib');
	loadGallery(gal,currentPage,10);
	loadComments(image_id);
}

/** Initialization of info bar **/
function ibInit(iname) {
	this.iname 					= iname;
	this.ib    					= document.createElement('table');
	this.ib.style.borderCollapse= 'collapse';
	this.ib.style.whiteSpace	= 'nowrap';
	this.ib.style.width			= '110px';
	this.ib.className			= 'galleryRightFloatIn';

	var ib_tb = document.createElement('tbody');

	var tr_top= document.createElement('tr');
	var tr_mid= document.createElement('tr');
	var tr_bot= document.createElement('tr');

	var td_top= document.createElement('td');
	var td_mid= document.createElement('td');
	var td_bot= document.createElement('td');

	td_top.style.padding 		= '0';
	td_top.style.background 	= 'url('+WEBPATH+'images/infoBar/top.png)';
	td_top.style.behavior	 	= 'url('+WEBPATH+'js/iepngfix.htc)';
	td_top.width 				= '200';
	td_top.height 				= '20';
	td_top.innerHTML			= '&nbsp;';

	td_mid.style.padding 		= '0 10px 0 20px';
	td_mid.style.whiteSpace		= 'nowrap';
	td_mid.style.fontSize		= '10px';
	td_mid.style.background 	= 'url('+WEBPATH+'images/infoBar/left.png)';
	td_mid.style.behavior	 	= 'url('+WEBPATH+'js/iepngfix.htc)';
	td_mid.width 				= '170';
	td_mid.innerHTML			= '<a href="javascript:void(0)" onclick="printImage()"><img src="/images/ico/gallery/print.png" alt="Print" class="img" />Print Image</a><br /><hr size="1" color="#4F4F4F" style="background:#4F4F4F" /><a href="javascript:;" onclick="getOrig()"><img src="/images/ico/gallery/original.png" alt="View Original" class="img" />View Original</a><hr size="1" color="#4F4F4F" style="background:#4F4F4F" /><a href="javascript:;" onclick="downloadImage()"><img src="/images/ico/gallery/download.png" alt="Download" class="img" />Save Image</a><hr size="1" color="#4F4F4F" style="background:#4F4F4F" /><a href="javascript:void(0)" onclick="Report()" style="color: #ff0000;"><img src="/images/ico/gallery/report.png" alt="Report" class="img" />Report</a><span id="current_photo_user_rating"></span>';

	td_mid.style.verticalAlign	= 'top';
	td_mid.nowrap				= 'nowrap';

	td_bot.style.padding 		= '0';
	td_bot.style.background 	= 'url('+WEBPATH+'images/infoBar/bottom.png)';
	td_bot.style.behavior	 	= 'url('+WEBPATH+'js/iepngfix.htc)';
	td_bot.width 				= '200';
	td_bot.height 				= '20';
	td_bot.innerHTML			= '&nbsp;';

	tr_top.appendChild(td_top);
	tr_mid.appendChild(td_mid);
	tr_bot.appendChild(td_bot);

	ib_tb.appendChild(tr_top);
	ib_tb.appendChild(tr_mid);
	ib_tb.appendChild(tr_bot);

	this.ib.appendChild(ib_tb);

	this.ibh				= document.createElement('div');
	this.ibh.style.position = 'absolute';
	this.ibh.id				= 'ibholder';
	this.ibh.style.zIndex 	= 200;
	this.ibh.style.right 	= '0px';
	this.ibh.style.top		= '0px';
	this.ibh.style.width	= '0px';
	this.ibh.style.overflow = 'hidden';

	this.ibh.appendChild(this.ib);

	//Append to the image conteiner
	$('galleryPicture').appendChild(this.ibh);

}

var origImg = '';

function getOrig() {
	var url = "/photos/getOrig/"+image_id;
	hideModelPopup();
	hideOtherPopup();

	fillPopup("<img src='"+getImage('progress')+"' />");
	showCenteredPopup(true);

	new Ajax.Request(url, {method:'get', onSuccess:doGetOrig});
}

var doGetOrig = function (t) {
	var url = t.responseText;

	origImg = new Image();
	origImg.onload = loadOrig;
	origImg.src = '/files/'+url;
}

function loadOrig() {
	var width 	= origImg.width;
	var height 	= origImg.height;

	if (windowWidth < width+40 || windowHeight < height+40) {
		fillPopup('<div style="width: '+(windowWidth < width+40?(windowWidth-140):width+20)+'px; height: '+( windowHeight < height+40?windowHeight-140:height+20)+'px; overflow:scroll"><img src="'+origImg.src+'" alt="image" /></div>');
	}else {
		fillPopup('<img src="'+origImg.src+'" alt="image" width="'+width+'" height="'+height+'" />');
	}
	reCenterPopup();
}

/** Loads the image list **/
function loadGallery(album, page, num_per_page) {
	if ((typeof(album) == 'undefined')) {
		populatePopup('Required parameters missing!');
		showCenteredPopup();
		popupLocked = true;
		setTimeout('popupLocked=false; hidePopup();', 4000);
		return false;
	}
	$('gallery').innerHTML = "Loading gallery information...";
	myAlbum = album;
	currentPage = page;
	if (myAlbum=='') myAlbum = '0/0';

	getGalleryScore(myAlbum);

	appendToLog('Requested galleryID: '+album+' page '+currentPage+'!');

	//if (myAlbum.indexOf('/') < 0) myAlbum += '/0';
	url = '/photos/gallery/'+user_id+'/'+myAlbum+'/'+page+'/'+num_per_page;
	new Ajax.Request(url, {method:'get', onSuccess:doLoadGallery});
}

var doLoadGallery = function (t) {
	$('gallery').innerHTML = t.responseText;
	window.location.href = "#"+image_id+"_"+myAlbum;

	//Check if the user have access to the gallery
	if ($('gallerySelector')) {
		var color = $("gallerySelector").options[$("gallerySelector").selectedIndex].style.color;
		if (color == 'red') {
			sendGalleryRequestDialog();
		}else if (color == 'grey') {
			showGalleryPending();
		}
		//alert($("gallerySelector").options[$("gallerySelector").selectedIndex].style.color);
	}

	//Hide previous higlighted image
	if ($('thumb_holder')) {
		var imagesList = $('thumb_holder').getElementsByTagName('img');
		for (i=0;i<imagesList.length;i++) {
			imagesList[i].className = 'gallery_thumb';
		}
	}
	//Set highlight
	if ($('gallery_thumb_'+image_id)) {
		$('gallery_thumb_'+image_id).className = 'gallery_thumb2';
	}

	appendToLog('galleryID: '+myAlbum+' page '+currentPage+' loaded!');
}

function getGalleryScore(album) {

	new Ajax.Request('/users/getGalleryRating/'+album+'/'+user_id, {method:'get', onSuccess:doGetGalleryScore});
}

var doGetGalleryScore = function (t) {
	$('galleryOverall').innerHTML = t.responseText;

	appendToLog('Gallery score for id '+myAlbum+' loaded!');
}
/** END **/

/** Load comments for an image **/
function loadComments(myImage) {
	$('comments').innerHTML = "<div style='margin-top: 20px; float: left; color: #666666; font-size:12px'>Loading comments...</div>";
	new Ajax.Request('/photos/comment/'+myImage, {method:'get', onSuccess:doLoadComments});
}

var doLoadComments = function (t) {
	$('comments').innerHTML = t.responseText;

	appendToLog('Comments for album '+myAlbum+' loaded!');
}
/** END **/

/**Shows the query pages **/
var doShowGalleryPages = function (t) {
	populatePopup(t.responseText);
	var offsetWidth = (windowWidth - 960) / 2;
	if (offsetWidth < 0) offsetWidth = 0;
	movePopup(780 + offsetWidth, 900);
	showPopup();
}

/**Load image **/
function loadImage(imgSrc, myImageId, imageText) {
	loadComments(myImageId);
	image_id = myImageId;
	image_src = imgSrc;
	image_text = imageText;

	//Set preloader
	$('picture').innerHTML = "<img src='"+getImage('progress')+"' />";

	if (typeof imageText != 'undefined') {
		$('imageOf').innerHTML = imageText;

		var imagePos = imageText.split(" ");
		if (imagePos[0] > 0) { //Load the target page...
			var targetPage = Math.floor((imagePos[0]-1) / 10)+1;
			if (targetPage != currentPage) {
				loadGallery(myAlbum, targetPage, 10);
			}
		}
	}

	//Hide previous higlighted image
	if ($('thumb_holder')) {
		var imagesList = $('thumb_holder').getElementsByTagName('img');
		for (i=0;i<imagesList.length;i++) {
			imagesList[i].className = 'gallery_thumb';
		}
	}
	//Set highlight
	if ($('gallery_thumb_'+image_id)) {
		$('gallery_thumb_'+image_id).className = 'gallery_thumb2';
	}


	galleryImg = new Image();
	galleryImg.onload = showGalleryImg;
	galleryImg.src = imgSrc;
}

function showGalleryImg() {
	window.location.href = "#"+image_id+"_"+myAlbum;
	$('picture').innerHTML = '<img src="'+galleryImg.src+'"  style="border:1px solid black" />';

	new Ajax.Request('/users/get_rating/'+image_id, {method:'get', onSuccess:setPhotoRating});		//get photo rating by current user
	appendToLog("ImageID: "+image_id+" loaded!");
}
/** END **/

var setPhotoRating = function (t) {

	users_vote = t.responseText;

	//Add voting stars
	if (users_vote.length > 0) {
		if((users_vote > 0) && (users_vote < 6)) {
			$('current_photo_user_rating').innerHTML = '<br /><hr size="1"/>Your Rating<br /><img src="/images/gallery/star_empty.gif" id="photo_vote_1" alt="" /><img src="/images/gallery/star_empty.gif" id="photo_vote_2" alt="" /><img src="/images/gallery/star_empty.gif" id="photo_vote_3" alt="" /><img src="/images/gallery/star_empty.gif" id="photo_vote_4" alt="" /><img src="/images/gallery/star_empty.gif" id="photo_vote_5" alt="" />';
			voteWithStars(users_vote, 'photo_vote');
		}
		else {
			$('current_photo_user_rating').innerHTML = '<br /><hr size="1"/>Rate Image<br /><img src="/images/gallery/star_empty.gif" id="photo_vote_1" alt="Rate photo with 1 star" title="Rate photo with 1 star" onclick="preVoteWithStars(1,\'photo_vote\');" class="pointer" /><img src="/images/gallery/star_empty.gif" id="photo_vote_2" alt="Rate photo with 2 stars" title="Rate photo with 2 stars" onclick="preVoteWithStars(2,\'photo_vote\');" class="pointer" /><img src="/images/gallery/star_empty.gif" id="photo_vote_3" alt="Rate photo with 3 stars" title="Rate photo with 3 stars" onclick="preVoteWithStars(3,\'photo_vote\');" class="pointer" /><img src="/images/gallery/star_empty.gif" id="photo_vote_4" alt="Rate photo with 4 stars" title="Rate photo with 4 stars" onclick="preVoteWithStars(4,\'photo_vote\');" class="pointer" /><img src="/images/gallery/star_empty.gif" id="photo_vote_5" alt="Rate photo with 5 stars" title="Rate photo with 5 stars" onclick="preVoteWithStars(5,\'photo_vote\');" class="pointer" />';
		}
	}

	getGalleryScore(myAlbum);

	appendToLog('Photo rating set:'+users_vote+'');
}

/** Attach the hover listener **/
function attachHover(elem) {
	elem.onmouseover = function (e) {
		var targ;
		if (!e) e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		if (targ.nodeType == 3)	targ = targ.parentNode;

		myAnim = new YAHOO.util.Anim('ibholder', {width: { to: 100 }}, 1, YAHOO.util.Easing.bounceOut);//

		myAnim.animate();
	}

	elem.onmouseout = function (e) {
		var targ;
		if (!e) e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		if (targ.nodeType == 3)	targ = targ.parentNode;

		setTimeout("var parent = findParent(mouseTarget, 'galleryImage');if (parent == false) {myAnim = new YAHOO.util.Anim('ibholder', {width: {from:100, to: 0 }}, 1, YAHOO.util.Easing.bounceOut); myAnim.animate();}", 400);
	}
}

/** Under picture buttons **/
function getFirst() {
	$('picture').innerHTML = "<img src='"+getImage('progress')+"' />";
	new Ajax.Request('/users/getFirstImg/'+image_id+'/'+myAlbum, {method:'get', onSuccess:showGalImage});
}

function getPrev() {
	$('picture').innerHTML = "<img src='"+getImage('progress')+"' />";
	new Ajax.Request('/users/getPrevImg/'+image_id+'/'+myAlbum, {method:'get', onSuccess:showGalImage});
}

function getNext() {
	$('picture').innerHTML = "<img src='"+getImage('progress')+"' />";
	new Ajax.Request('/users/getNextImg/'+image_id+'/'+myAlbum, {method:'get', onSuccess:showGalImage});
}

function getLast() {
	$('picture').innerHTML = "<img src='"+getImage('progress')+"' />";
	new Ajax.Request('/users/getLastImg/'+image_id+'/'+myAlbum, {method:'get', onSuccess:showGalImage});
}

var showGalImage = function (t) {
	var data = t.responseText.split(',');

	//$('imageOf').innerHTML = data[2];
	//image_text = data[2];
	//$('picture').innerHTML = data[0];
	window.location.href = "#"+data[1];

	loadImage(data[0], data[1], data[2]);
	appendToLog('Image: '+data[1]+' loaded!');
}
/** END **/

/** Save the user comment and reloads the comments container**/
//NB: not used
function saveComment(photoId) {
	var req_string = $('comment').value;
	var url = '/photos/save_comment/'+ photoId;
	new Ajax.Request(url, {method:'post', postBody:req_string, onSuccess: handlerFunc});
	loadComments(photoId);
}

/** Open print popup and forces the print dialog **/
function printImage() {
	var img = $('picture').firstChild;

	var popup = window.open('/blank.html', 'popup', 'width='+(img.width+20)+', height='+(img.height+30));
	popup.document.writeln('<html><head><title>BreakABone.com - Image print</title></head><body>'+$('picture').innerHTML+"<script type='text/javascript'>window.print()</script></body></html>");

	//setTimeout("popup.print()", 2000);
	popup.focus();
}

/** Forced download of the current image **/
function downloadImage() {
	loc = WEBPATH+'photos/download_img/'+image_id;
	document.location = loc;
	return true;
}

function voteForImg(userRating) {

}

/** Shows EXIF information for the current image **/
function getImageInfo() {
	hideModelPopup();
	hideOtherPopup();

	fillPopup("Loading image information...");
	showDimmer();
	showCenteredPopup();

	new Ajax.Request('/photos/getExifInfo/'+image_id, {method:'get', onSuccess: doGetImageInfo});
}

var doGetImageInfo = function (t) {
	fillPopup(t.responseText);
	reCenterPopup();
}

function preVoteWithStars(rating, var_names) {
	voteWithStars(rating, var_names);
	var url = '/users/save_rating/'+ image_id;
	var req_string = 'rating=' + rating;
	new Ajax.Request(url, {method:'post', postBody:req_string, onSuccess: handleRefresh});
}

function voteWithStars(rating, var_names) {
	if ((typeof(rating) == 'undefined') || (rating < 1) || (rating > 5)) rating = 0;
	if (typeof(var_names) == 'undefined') {		//voting from a comment (uses hidden variables)
		var_names = 'star_vote';
		document.getElementById(var_names).value = rating;
	}

	for (i = 1; i < 6; i++) {
		if (rating >= i) {
			$(var_names + '_' + i).src = WEBPATH+'images/gallery/star_full.gif';
		}
		else {
			$(var_names + '_' + i).src = WEBPATH+'images/gallery/star_empty.gif';
		}
	}
}

function showGalleryPending() {
	var text = "<center>This user is still considering your gallery request!</center>";
	showDimmer();
	fillPopup(text);
	showCenteredPopup();

	setTimeout('hideDimmer(true)', 2500);
}

function sendGalleryRequestDialog() {
	var text = "<center>This gallery is set as private! You need special permissions from the gallery owner to view the images! Do you wish to send \"Gallery Request\"?<br /><br /><input type='button' value='Yes' onclick='sendGalleryRequest()' /> <input type='button' value='No' onclick='hideDimmer(true)' /></center>";
	showDimmer(true);
	fillPopup(text);
	showCenteredPopup();
}

function sendGalleryRequest() {
	fillPopup("<center>Sending gallery request...<br /><br /><img src=\""+getImage('upload')+"\" alt=\"Upload bar...\" width=\"220\" height=\"19\" /></center>");
	reCenterPopup();
	new Ajax.Request('/photos/send_request/'+myAlbum, {method:'get', onSuccess:doSendGalleryRequest});
}

var doSendGalleryRequest = function(t) {
	fillPopup(t.responseText);
	reCenterPopup();
	setTimeout('hideDimmer(true)', 2500);
}