$(document).ready(function() { 
    
    var gallery_items = $("#image_carousel li");	
	var imageId = getUrlParameter("imageId");
		if (imageId == "") { imagedId = 0; } 	
    
	jQuery('#image_carousel').jcarousel({
        vertical: true
    });	
		
    // enumerate number of items in gallery
    $("#gallery_total").text(gallery_items.size());
    
    // handle clicks on the carousel    
    $("#image_carousel li a").bind('click', function() {
    	var thisEl = this;
		// load image into frame
		$("#image_frame img").attr("src",$(this).attr("href"));
		
		//$("#image_frame table").load($(this).attr("href"));
		emptyComments();
		
		$("#stats_container").load($(this).siblings(".ajax_comments_link").attr("value"), function() {
			// create direct link
			var thisURL = window.location; 
			var permalinkURL = thisURL.protocol + "?imageId=" + (parseInt($(thisEl).parent().attr("jcarouselindex"))-1);
			$("#permanent_link").attr("href",permalinkURL);	
		});
		// $("#comments_holder").load($(this).siblings(".ajax_comments_link").attr("value"));
		
		// clear selections on all li
		gallery_items.removeClass("selected");
		
		// add selection on currently selected
		$(this).parent().addClass("selected");
		
		// update image index    	    	
		$("#image_index").text(getSelectedImageIndex(gallery_items));
		
		// initialize external controls
		// externalControlsCheck(gallery_items); 
		
		
		
    	// negate behavior
    	return false;
    });
    
    // start on this item
    setSelectedItem(imageId);
    
    loadComments();
    postComments();
});

function getSelectedImageIndex(thisCol) {	
	var returnedIndex;
	
	$(thisCol).each(function(i) {			
    	if ($(this).hasClass("selected")) {       			
    		returnedIndex = i+1;	
    	}
    });
    return returnedIndex; 
}

function setSelectedItem(pId) {		
    $("#image_carousel li:eq("+pId+")").addClass("selected").children("a").click();
}

// get url parameter
function getUrlParameter(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function emptyComments() {
	$("#comments_holder").empty();
}

function loadComments() {
	$("a.load_comments").livequery('click',(function() {						
		$("#comments_holder").load($(this).attr("href"));    	
		return false;
    }));
    
   $("a.leave_comments").livequery('click',(function() {						
		$("#comments_holder").load($(this).attr("href"), function() {
			$.scrollTo("#leave_a_comment","slow");
		});
    	return false;
    }));
}

function postComments() {
	$("#comment_form #comment_poster_submit").livequery('click',(function() {			
		//window.console.log($(this).parent().attr("action"));
			   
		$(".error").hide();
		var hasError = false;
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		var responseData;
		
		if (document.getElementById("comment_poster_name")) {
			var nameVal = $("#comment_poster_name").val();
			if(nameVal == '') {
				$("#comment_poster_name").after('<span class="error">You forgot to enter a name.</span>');
				hasError = true;
			}
		
			var emailVal = $("#comment_poster_email").val();
			if(emailVal == '') {
				$("#comment_poster_email").after('<span class="error">You forgot to enter your email address.</span>');
				hasError = true;
			} else if(!emailReg.test(emailVal)) {	
				$("#comment_poster_email").after('<span class="error">Please enter a valid email address.</span>');
				hasError = true;
			}
				
			var locationVal = $("#comment_poster_location").val();
			var urlVal = $("#comment_poster_url").val();
		}
		
		var commentVal = $("#comment_poster_textarea").val();
		if(commentVal == '') {
			$("#comment_poster_textarea").after('<span class="error">You forgot to enter a comment.</span>');
			hasError = true;
		}
		
		var saveInfoVal = $("#comment_poster_save").val();
		var notifyVal = $("#comment_poster_notify").val();
		
		// don't forget hidden fields
		var iACT = $("#comment_form input[@name='ACT']").val();
		var iRET = $("#comment_form input[@name='RET']").val();
		var iURI = $("#comment_form input[@name='URI']").val();
		var iPRV = $("#comment_form input[@name='PRV']").val();
		var iXID = $("#comment_form input[@name='XID']").val();
		var iEntryId = $("#comment_form input[@name='entry_id']").val();
		var iSiteId = $("#comment_form input[@name='site_id']").val();
		//, ACT: iACT, RET: iRET, URI: iURI, PRV: iPRV, XID: iXID, entry_id: iEntryId, site_id: iSiteId		
		
		if(hasError == false) {
			//window.console.log("trying to post livequery form");
			
			// hide the form
			$(this).hide();
			// display a please wait animation status
			//$("#location to put").append('<img src="loading.gif" alt="Loading" id="loading" />');
			
			// post the form data to the appropriate place. - need to make this dynamic.
			$.post($(this).parent().attr("action"),
   				{ name: nameVal, email: emailVal, location: locationVal, url: urlVal, comment: commentVal , save_info: saveInfoVal, notify_me: notifyVal, ACT: iACT, RET: iRET, URI: iURI, PRV: iPRV, XID: iXID, entry_id: iEntryId, site_id: iSiteId	 },   					
   					function(data){
   						//window.console.log("data loaded" + data);
   						responseData = data;
						
   						$("#comments_holder").show("normal", function() {	
   							$("#comments_holder").html(responseData);
							$("#comments_container").after('<p>Success! Your comment was added.</p>');											
						});
						
   					}
			);
		}
		return false;
	}));	
}




