/** Variables list **/
var ib = '';
var to = '';
var galleryImg 	= '';
var myAnim		= '';
var myAlbum		= '';

//
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;

	//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,1,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';

	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:;" onclick="getImageInfo()">Image Info</a><br /><!--<hr />Rate Image<br /><img src="/images/infoBar/rate.png" class="msgIco" width="74" height="17" usemap="#Vote" border="0" />--><hr /><a href="javascript:void(0)" onclick="printImage()">Print Image</a><br /><hr /><a href="javascript:;" onclick="downloadImage()">Save Image</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);

}

/** Loads the image list **/
function loadGallery(album, page, num_per_page) {
	$('gallery').innerHTML = "Loading gallery information...";
	myAlbum = album;

	getGalleryScore(album);
	new Ajax.Request('/photos/gallery/'+user_id+'/'+album+'/'+page+'/'+num_per_page, {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);
	}

	appendToLog('galleryID: '+myAlbum+' loaded!');
}

function getGalleryScore(album) {

	new Ajax.Request('/users/getGalleryRating/'+album+'/'+user_id, {method:'get', onSuccess:doGetGalleryScore});
}

var doGetGalleryScore = function (t) {
	$('galleryOverall').innerHTML = t.responseText;
}
/** 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;
}
/** END **/

/**Shows the query pages **/
var doShowGalleryPages = function (t) {
	populatePopup(t.responseText);
	movePopup((posx-70), (posy+10));
}

/**Load image **/
function loadImage(imgSrc, myImageId, imageText) {


	loadComments(myImageId);
	image_id = myImageId;
	image_src = imgSrc;

	//Set preloader
	$('picture').innerHTML = "<img src='"+getImage('progress')+"' />";

	if (typeof imageText != 'undefined') {
		$('imageOf').innerHTML = imageText;
	}

	galleryImg = new Image();
	galleryImg.onload = showGalleryImg;
	galleryImg.src = imgSrc;
}

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 />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 />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" />';
		}
	}
	else {
		$('current_photo_user_rating').innerHTML = '';
	}
}

function showGalleryImg() {
	window.location.href = "#"+image_id+"_"+myAlbum;
	$('picture').innerHTML = '<img src="'+galleryImg.src+'"  style="border:3px 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 **/

/** Attach the hover listener **/
function attachHover(elem) {
//	myAnim = new YAHOO.util.Anim('ibholder', {width: { to: 100 }}, 1, YAHOO.util.Easing.bounceOut);
//	myAnim.animate();

	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);
//		if (!parent) {
//			myAnim.attributes.width = { to: 0 };
//			myAnim.animate();
//		}

	}
}

/** 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]);
}
/** 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>ChanceAtFame.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);
}
