// cmrl.js v1.0.0
/* Redirect in case there is hash virtual address
--------------------- */
if (document.location.hash && document.location.hash.substr(0, 3) == '#!/') { document.location.replace(document.location.hash.substr(2)); }

function openWindow(winURL, winName, winWidth, winHeight) {
	winTop = ((screen.height / 2) - (winHeight / 2));
	winLeft = ((screen.width / 2) - (winWidth / 2));
	window.open(winURL, winName, 'width=' + winWidth + ', height=' + winHeight + ', top=' + winTop + ', left=' + winLeft);
}

/* Change textarea height
--------------------- */
function focusRows(textarea) {
	if (!document.getElementById('textarea_shadow')) {
		var textarea_shadow = document.createElement('div');
		textarea_shadow.setAttribute('id', 'textarea_shadow');
		textarea_shadow.style.width = (textarea.clientWidth ? textarea.clientWidth - 6 : 250) + 'px';
		textarea_shadow.style.position = "absolute";
		textarea_shadow.style.visibility = "hidden";
		textarea_shadow.style.fontSize = "9pt";
		textarea_shadow.style.textAlign = "left";
		textarea_shadow.style.lineHeight = "16px";
		textarea_shadow.style.wordWrap = "break-word";
		document.getElementById('add_comment_form').appendChild(textarea_shadow);
	}
	if (!textarea.value) { textarea.rows = 2; }
}
function blurRows(textarea) {
	if (!textarea.value) { textarea.rows = 1; }
}
function setRows(textarea) {
	document.getElementById('textarea_shadow').innerHTML = textarea.value.replace(/\n/g, '<br />') + 'w';
	rowsNumber = Math.floor(document.getElementById('textarea_shadow').offsetHeight / 16);
	rowsNumber = rowsNumber < 2 ? '2' : rowsNumber;
	textarea.rows = rowsNumber;
}

/* Photo navigation
--------------------- */
function photoNav(eventID, photoID, imageURL, photos_array) {
	var current_index, t, currentUrl;
	var preloaded_image = new Array();
	var next_img_ready = new Array();
	
	function addComment(comment) {
		if(comment != '') {
			document.getElementById('submit_comment').disabled = true;
			document.getElementById('submit_comment').className = 'disabled';
			document.getElementById('add_comment_form').getElementsByTagName('textarea')[0].disabled = true;
			$.ajax({
				url: "/ajax/photoaddcomment/",
				data: "id=" + photos_array[current_index][0] + "&c=" + comment.replace(/\n/g, '%0A'),
				success: function(response) {
					document.getElementById('add_comment_form').getElementsByTagName('textarea')[0].value = '';
					var comment_response = eval(response);
					new_comment = photos_array[current_index][6].push(comment_response);
					addComments();
				},
				error: function(error) {
					alert("No se pudo agregar el comentario, inténtalo más tarde.");
				},
				complete: function(msg) {
					document.getElementById('submit_comment').disabled = false;
					document.getElementById('submit_comment').className = '';
					document.getElementById('add_comment_form').getElementsByTagName('textarea')[0].disabled = false;
				}
			});
		}
	}
	
	function addComments() {
		html_var = "";
		for(i=0;i<photos_array[current_index][6].length;i++) {
			p = photos_array[current_index][6][i];
			html_var = html_var + '<div id="comentario-' + p[0] + '" class="comment"><a href="' + p[5] + '" class="avatar"><img src="' + p[4] + '" alt="" /></a><div class="comment_content"><div class="comment_text">' + p[1] + ' ' + p[2] + '</div><div class="comment_actions"><a href="#comentario-' +  p[0] + '">' + p[3] + '</a> · <a href="#">Reportar</a></div></div></div>';
		}
		document.getElementById('comments_wrapper').innerHTML = html_var;
	}
	
	function addKeyBehavior(e) {
		var KeyType = window.event ? event : e;
		if (!KeyType.altKey && !KeyType.ctrlKey && !KeyType.shiftKey) {
			var KeyID = KeyType.keyCode;
			switch (KeyID) {
				case 37:
					current_index > 0 ? navLink(true) : document.location = "/fotos/"+eventID+"/";
					break;
        	
				case 39:
					current_index < (photos_array.length-1) ? navLink(false) : document.location = "/fotos/"+eventID+"/";
					break;
			}
		}
	}
	
	function addLinkBehavior() {
		if (document.getElementById('submit_comment')) {
			document.getElementById('submit_comment').onclick = function onclick(event) {
				addComment(document.getElementById('add_comment_form').getElementsByTagName('textarea')[0].value);
				return false;
			};
		}
		document.getElementById('photo_nav').getElementsByTagName('a')[0].onclick = function onclick(event) {
			if (!event) { var event = window.event; }
			if (current_index && event.which != 2) {
				navLink(true);
				return false;
			}
		};
		document.getElementById('photo_nav').getElementsByTagName('a')[2].onclick = function onclick(event) {
			if (!event) { var event = window.event; }
			if (current_index < (photos_array.length - 1) && event.which != 2) {
				navLink(false);
				return false;
			}
		};
		document.getElementById('photo').getElementsByTagName('a')[0].onclick = function onclick(event) {
			if (!event) { var event = window.event; }
			if (current_index < (photos_array.length - 1) && event.which != 2) {
				navLink(false);
				return false;
			}
		};
	}
	
	function checkHashChange() {
		if (currentUrl != document.location.pathname + document.location.hash) {
			currentUrl = document.location.pathname + document.location.hash;
			newPhotoID = photoID;
			if (document.location.hash) {
				splitUrl = document.location.hash.split('/');
				newPhotoID = splitUrl[splitUrl.length - 2];
			}
			for (i=0;i<=photos_array.length;i++) {
				if (photos_array[i][0] == newPhotoID) {
					current_index = i;
					break;
				}
			}
			updateImage(false);
		}
		return true;
	}
	
	function init() {
		for (i=0;i<=photos_array.length;i++) {
			if (photos_array[i][0] == photoID) {
				current_index = i;
				break;
			}
		}
		addLinkBehavior();
		document.onkeydown = addKeyBehavior;
		preloadImages();
		currentUrl = document.location.pathname + document.location.hash;
		setInterval(checkHashChange, 300);
	}
	
	function navLink(prev) {
		if (prev) {
			current_index--;
		} else {
			current_index++;
		}
		
		updateImage(true);
	}
	
	function preloadImages() {
		for (i = current_index + 1; i < current_index + 3; i++) {
			if (i < photos_array.length && !preloaded_image[i]) {
				preloaded_image[i] = new Image();
				preloaded_image[i].src = imageURL+photos_array[i][1];
			}
		}
	}
	
	function updateInfo(setNewHash) {
		clearTimeout(t);
		document.getElementById('photo').getElementsByTagName('img')[0].src = preloaded_image[current_index].src;
		Stars.update_stars(photos_array[current_index][3], photos_array[current_index][4], false, photos_array[current_index][0]);
		if (document.getElementById('add_comment_form')) {
			document.getElementById('add_comment_form').action = "/fotos/"+eventID+"/"+photos_array[current_index][0]+"/#comments";
			document.getElementById('add_comment_form').getElementsByTagName('textarea')[0].value = '';
		}
		document.getElementById('photo_nav').getElementsByTagName('a')[0].href = "/fotos/"+eventID+"/"+(current_index > 0 ? (photos_array[current_index-1][0])+"/" : '');
		document.getElementById('photo_nav').getElementsByTagName('a')[2].href = "/fotos/"+eventID+"/"+(current_index < (photos_array.length-1) ? (photos_array[current_index+1][0])+"/" : '');
		document.getElementById('photo').getElementsByTagName('a')[0].href = "/fotos/"+eventID+"/"+(current_index < (photos_array.length-1) ? (photos_array[current_index+1][0])+"/" : '');
		addComments();
		document.getElementById('meta').getElementsByTagName('h4')[0].innerHTML = photos_array[current_index][2];
		if (setNewHash) {
			document.location.hash = '!/fotos/'+eventID+'/'+photos_array[current_index][0]+'/';
			currentUrl =document.location.pathname + document.location.hash;
		}
		preloadImages();
		$.get("/ajax/photoupdateviews/", {id: photos_array[current_index][0]} );
	}
	
	function updateImage(setNewHash) {
		t = setTimeout("document.getElementById('photo').getElementsByTagName('img')[0].src = '/images/spacer.gif'", 1250);
		
		if (preloaded_image[current_index] && preloaded_image[current_index].complete) {
			updateInfo(setNewHash);
		} else if (!preloaded_image[current_index]) {
			preloaded_image[current_index] = new Image();
			preloaded_image[current_index].src = imageURL + photos_array[current_index][1];
			preloaded_image[current_index].onload = function() {
				updateInfo(setNewHash);
			};
		} else if (preloaded_image[current_index] && !preloaded_image[current_index].complete) {
			preloaded_image[current_index].onload = function() {
				updateInfo(setNewHash);
			};
		} else { alert('Error en la navegación de las fotos.'); }
	}
	
	this.init=init;
}

/* Rating system
--------------------- */
function rating_system(stars, votes, voted, photo_id){
	vote_enabled = false;
	stars_init = Math.round(votes > 0 ? stars / votes : 0);
	var rating_array = new Array('Califica esta foto', 'Malísima', 'No tan buena', 'Regular', 'Está bien', '¡La mejor!', 'Ya votaste', 'No puedes votar', '¡Gracias por votar!', 'Votando...');

	function change_stars(star_number) {
		for (i = 1; i < 6; i++) {
			if (i <= star_number){
				document.getElementById('star_' + i).src = '/images/global/star_on.png';
			} else {
				document.getElementById('star_' + i).src = '/images/global/star_off.png';
			}
		}
	}
	
	function clear_stars() {
		if(vote_enabled) {
			set_msg(0);
			change_stars(stars_init);
		}
	}
	
	function disable_stars() {
		vote_enabled = false;
		set_msg(7);
		change_stars(0);
		set_status('');
	}
	
	function init() {
		if(navigator.cookieEnabled) {
			if(!voted) {
				vote_enabled = true;
				set_msg(0);
			} else { set_msg(6); }
		} else { set_msg(7); }
		set_status(votes == 1 ? '1 voto' : votes + ' votos');
		change_stars(stars_init);
	}
	
	function set_msg(msg) {
		document.getElementById('rating_msg').childNodes[0].nodeValue = rating_array[msg];
	}
	
	function set_status(msg) {
		document.getElementById('rating_count').childNodes[0].nodeValue = msg;
	}
	
	function show_stars(star_number) {
		if(vote_enabled) {
			set_msg(star_number);
			change_stars(star_number);
		}
	}
	
	function set_star(star_number) {
		if(vote_enabled && navigator.cookieEnabled) {
			vote_enabled = false;
			set_msg(9);
			$.ajax({
				url: "/ajax/photoaddstar/",
				data: "id=" + photo_id + "&s=" + star_number,
				success: function(response) {
					set_msg(8);
					change_stars(star_number);
					set_status("Diste "+(star_number == 1 ? "1 estrella" : star_number+" estrellas"));
				},
				error: function(req) {
					if (req.status == 403) {
						set_msg(6);
					} else {
						alert("No se pudo agregar tu voto, inténtalo más tarde.");
						vote_enabled = true;
						clear_stars();
					}
				}
			});
		} else if (!navigator.cookieEnabled) { alert('Para poder votar necesitas tener habilitadas tus cookies'); }
	}
	
	function update_stars(update_stars, update_votes, update_voted, update_pid){
		stars = update_stars;
		votes = update_votes;
		stars_init = Math.round(votes > 0 ? stars / votes : 0);
		voted = update_voted;
		photo_id = update_pid;
		init();
	}
	
	this.clear_stars=clear_stars;
	this.disable_stars=disable_stars;
	this.init=init;
	this.set_star=set_star;
	this.show_stars=show_stars;
	this.update_stars=update_stars;
}
