$.Gallery = function() {
  this.initialize = function(galleryData) {
    this.galleryData = galleryData;
    this.images = galleryData.images;
		this.index = 0;
		this.amountOfClicks = 0;
		this.adShowInterval = 4; 						// How many clicks before showing an ad
		this.adDomId = 'interstitial_ad'; 	// The DOM ID of the interstitial ad
		this.showingAd = false;							// Are we showing an ad right now?
		this.preloadedImages = Array();
		this.preloadWindowSize = 3;
		this.nextGallery = false;
		this.prevGallery = false;
		this.preloadContainer = $('body').append('<div id="img-cache" style="display:none/>').children('#img-cache');
  }
  
  this.preloadWindow = function() {
    for(var i = this.index - this.preloadWindowSize; i < this.index + this.preloadWindowSize; i++) {
      var idx = (i<0) ? this.images.length + i : i;
      if(idx >= this.images.length || idx < 0) idx = 0;
      var imgSrc = this.images[idx].full_path;
      if( $.inArray(imgSrc, this.preloadedImages) == -1) {
        this.preloadedImages.push(imgSrc);
        $('<img/>').attr('src', imgSrc).appendTo(this.preloadContainer);
      }
    }
  }
  
  this.navigate = function(direction) {
    if(this.nextGallery && (direction == "forward") && (this.index == this.images.length - 1)) {
      window.location = "/galleries/" + this.nextGallery;
      return false;
    }
    if(this.prevGallery && (direction == "backward") && (this.index == 0)) {
      window.location = "/galleries/" + this.prevGallery;
      return false;
    }
    
    if(this.shouldDisplayAd()) {
      this.displayAd();
      return false;
    }
    if(direction == "forward") {
      this.index = this.getNextIndex();
    } else if(direction == "backward") {
      this.index = this.getPreviousIndex();
    }
    this.render(this.index);
  }
  
  this.getNextIndex = function() {
    if(this.index + 1 > this.images.length - 1) return 0;
    return this.index + 1;
  }
  
  this.getPreviousIndex = function() {
    if(this.index -1 < 0) return this.images.length - 1;
    return this.index - 1;
  }
  
  this.render = function(idx) {
    var image = this.images[idx];
    $('#full_image').attr('src', image.full_path);
    $('#image_count').html((idx + 1) + " of " + this.images.length);
    $('#image_title').html(image.title);
    $('#image_description').html(image.description);
    var credit = (image.credit == "") ? "" : "Credit: " + image.credit;
    $('#image_credit').html(credit);
    
    if(this.showingAd) this.hideAd();
    
    if(this.amountOfClicks != 0) {  // After Initial Load
  		// record omniture stat
  		s.pageName = this.galleryData.title + " - " + image.title;
  		var s_code=s.t();
		
  		// Deep linking
  		document.location.href = document.location.href.split("#")[0] + "#" + (image.id);
	  } else {
      // initial load
	  }
	  
	  /* Comments */
    this.getComments(image.id);
    this.preloadWindow();
  }
  
  this.getComments = function(imageId) {
    var commentsUrl = $('#comment_form').attr('action').split(/\/images\/\d+\//).join('/images/'+imageId+'/').split(/\/list$/).join("") + '/list';
    if(this.commentXhr) this.commentXhr.abort();
    this.commentXhr = $.get(commentsUrl, function(data) {
      $('#comments').empty().html(data);
      $('.comments .amount').html($('#comments .comment').length);
    }),
    $('#comment_form').attr('action', commentsUrl.split(/\/list$/).join(""));
  }
  
  this.shouldDisplayAd = function() {
    if(this.galleryData.display_interstitial_ads == false) return false;
		this.amountOfClicks++;
		return (this.amountOfClicks % this.adShowInterval) == 0;
  }
  
  this.displayAd = function() {
    this.showingAd = true;
    if(!this.ad) {
      this.ad = adFactory.getAd(300,250);
      this.ad.setParam("pos", 2);
      this.ad.setParam("photo", "ad");
      this.ad.setParam("!category", "expandables");
    }
    $('#interstitial_ad').show();
    $('#interstitial_ad iframe').contents().find('body').empty();
    $('#interstitial_ad iframe').contents()[0].write(this.ad._getAdTag());
    var iframe = $('<iframe style="display:none;"></iframe>');
    $('body').append(iframe); // prevents infinite browser spinner
    iframe.remove();
  }
  
  this.hideAd = function() {
    $('#interstitial_ad').hide();
    this.showingAd = false;
  }
  
  this.getIndexByID = function(image_id) {
		for(var i = 0; i < this.images.length; i++) {
			if(this.images[i].id == image_id) {
				return i;
			}
		}
		return 0;
	}
}

$('.comments .flag a').live('click', function(evt) {
  evt.preventDefault();
  $(this).parent().html('Thank you, This comment will be checked by our moderators.');
  var id = $(this).parent().attr('id').split('-')[1];
});
$('.comments .pagination a').live('click', function(evt) {
  evt.preventDefault();
  $('#comments').load($(this).attr('href'));
});

$(document).ready(function() {
  $('#gallery_show .previous').click(function(evt) {
    evt.preventDefault();
    sfGallery.navigate('backward');
  });
  $('#gallery_show .next').click(function(evt) {
    evt.preventDefault();
    sfGallery.navigate('forward');
  });
  
  //dhtmlHistory.initialize();
  //dhtmlHistory.addListener(urlChangeListener);
});

function validateComment() {
	var errors = "";
	var emailRegex = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var linkRegex = /(http:\/\/|https:\/\/|www\.|\.com|\.net|\.org|\.edu|\.gov|\.php|\.asp|\.htm|\.html)/;
	
	if( $('#comment_name').val() == "" || $('#comment_name').val() == "YOUR NAME" ) {
		errors += "You must provide a name.<br/>";
	}
	if( !emailRegex.test( $('#comment_email').val() ) ) {
		errors += "You must provide a valid email address.<br/>";
	}
	if( $('#comment_body').val() == "" || $('#comment_body').val() == "TYPE YOUR MESSAGE HERE" ) {
		errors += "You must enter a comment.<br/>";
	}
	if( linkRegex.test( $('#comment_name').val() ) || linkRegex.test( $('#comment_body').val() ) ) {
		errors += "Your name or comment cannot contain links.<br/>";
	}
	if(errors != "") {
		$('#comment_errors').html("<strong>There were some errors:</strong><br/>" + errors);
		return false;
	}
	return true;
}
