
$(function() {

  $('a.schedule').click(function() {
    $(this).parents('.actions').hide();
    $(this).parents('.shoot').find('form').show().find('input:first').focus();
  });

  $('a#schedule_new_shoot').click(function() {
    $('.shoot.unrequested').show().find('form').show();
    $('a#schedule_new_shoot').hide();
  });

  $('form.edit_shoot .cancel, form.new_shoot .cancel').click(hideShoot);

  function hideShoot() {
    $(this).parents('form').hide();
    $(this).parents('.shoot').find('.actions').show();
    $('.shoot.unrequested').hide();
    $('a#schedule_new_shoot').show();
  }

});


$.fn.extend({
  inlineLabel: function(){
    return this.each(function(){
      var div   = $(this);
      var input = div.find(':input:first');
      var label = div.find('.inline_example');
      if(!label.length) label = div.find('label:first');

      label.addClass('inline').click(function() { input.focus(); });
      if(input.val()) label.addClass('value_entered');
 
      input
      .focus(function(){
        label.addClass('entering_text');
      })
      .blur(function(){
        label.removeClass('entering_text');
        if(!input.val()) label.removeClass('value_entered');
      })
      .keypress(function(){
        label.addClass('value_entered');
      })
      .keyup(function(){
        if(!input.val()) label.removeClass('value_entered');
      });
    });
  }
});

$(function(){
  $('.inline_label').inlineLabel();
});


(function($) {

$(function() {
  $('a.ajax').jaxyLink();
  $('form.ajax').jaxyForm();
  $('a.submit').submitOnClick();
  $('select.submit').submitOnChange();
});

$.fn.extend({

  jaxyLink: function() {
    return this.live('click', function() {
      $.getScript(this.href);
      return false;
    });
  },

  jaxyForm: function() {
    return this.each(function(i, form) {
      form = $(form);
      // ajax file uploads use an iframe hack, so tell the server we want a js response
      if (/multipart/.test(form.attr('enctype'))) {
        form.append('<input type="hidden" name="format" value="js" />');
      }
      form.ajaxForm({dataType: 'script'});
    });
  },

  submitOnClick: function() {
    return this.live('click', submitTargetOrParent);
  },

  submitOnChange: function() {
    return this.live('change', submitTargetOrParent);
  },
  
  findTarget: function() {
    var target = this.attr('target'),
        found = this.parents(target);

    if (!found.length) found = $(target);
    return found;
  }

});

function submitTargetOrParent() {
  var el = $(this);

  if (el.attr('target')) {
    el.findTarget().submit();
  } else {
    el.closest('form').submit();
  }

  return false;
}

var $val = $.fn.val;
$.fn.val = function(values) {
  if (values == undefined) return $val.apply(this, arguments);

  if (values.constructor == Object) {
    for (var name in values) {
      $(this).find('[name="' + name + '"]').val(values[name]);
    }
    return this;
  }

  return $val.apply(this, arguments);
}

})(jQuery);


(function($) {
  $.fn.extend({
    loadLater: function() {
      this.each(function() {
        var elem = $(this);
        var url = elem.attr('data-source');
        var waitLoopId = setInterval(waitLoop, 1500);

        function performReplace(data) {
          data = $(data);
          elem.animate({opacity: 0}, 800, null, function() {
            data.css({opacity: 0});
            elem.replaceWith(data);
            data.animate({opacity: 1}, 800);
          });
          clear();
        }

        function error() {
          elem.html('Failed to load');
        }

        function complete(xhr, textStatus) {
          if (xhr.status != 204 && textStatus == 'success') {
            performReplace(xhr.responseText);
          }
        }

        function clear() {
          clearInterval(waitLoopId);
        }

        function waitLoop() {
          $.ajax({
            url: url,
            complete: complete,
            error: error,
            method: 'get'
          });
        }
      });
    }
  });
})(jQuery);


$(function() {

  $('#submit_order_link').click(function() {
    $('form').submit();
    return false;
  });

  $('#billing_address_same').change(function() {
    //alert('yo '+$(this).attr('checked'));
    if ($(this).attr('checked') == true){
      $('#billing_address_fields').hide(); 
    } else {
      $('#billing_address_fields').show();
    }
    return false;
  });

});


$(function() {

  //reset favorites (for browser back navigation) 
  $('input[value=true]').each(function(i,o){
    markThumbnailFavorited(indexOfThumbnail(o));
  });

  $('#order_prints_link').click(function() {
    $('form').submit();
    return false;
  });

  $('#preview').hide();

  $('#photos .photo').hover(function() {
    $(this).addClass('hover');
  }, function() {
    $(this).removeClass('hover');
  });
  
  // mark favorites
  $('.photo .favorites').click(function() {
    markThumbnailFavorited(indexOfThumbnail(this));
    return false;
  });

  $('#preview .favorites').click(function() {
    markPreviewFavorited();
    return false;
  });
  
  function markThumbnailFavorited(index){
    var photo = photoForIndex(index);
    toggleFavoriteButtonText(photo.find('.favorites'));
    if(photo.hasClass('favorite')) {
      photo.removeClass('favorite');
      photo.find('.marker').remove();
      photo.find('input').val('');
    } else {
      photo.addClass('favorite');
      photo.append('<img src="/images/favorite_marker.png" alt="favorite" class="marker" />');
      photo.find('input').val('true');
    }
    var count = $('.photo.favorite').length;
    $('#favorites_count').find('span:first').text(count); 
  }

  function markPreviewFavorited(){
    markThumbnailFavorited(currentPreviewIndex());
    showPreviewFavoriteInfo(currentPreviewIndex());
  }

  function toggleFavoriteButtonText(button){
    var addText = 'add to favorites';
    var removeText = 'remove from favorites';
    if(button.text() == addText)
      button.text(removeText);
    else
      button.text(addText);
  }

  $('.photo .preview').click(function() {
    showPreview(indexOfThumbnail(this));
  });

  $('#previous_photo').click(function() {
    showPreview(currentPreviewIndex()-1);
  });

  $('#next_photo').click(function() {
    showPreview(currentPreviewIndex()+1);
  });

  function currentPreviewIndex(){
    return parseInt($('#current_index').html());
  }

  function indexOfThumbnail(thumbnail){
    return parseInt($(thumbnail).parents(".photo").find(".index").html());
  }

  function photoForIndex(index){
    return $(':contains('+index+').index').parents('.photo');
  }

  function showPreview(index){
    $('#photos').hide();
    showPreviewFavoriteInfo(index);

    var url = photoForIndex(index).find('img').attr('src').replace("/thumb/", "/showcase/");
    var img = new Image();  
    img.onload = function() { 
      $("#preview_photo").attr("src", url); 
      $('#preview').show();
    }; 

    $('#previous_photo').show();
    $('#next_photo').show();
    if(index == "1")
      $('#previous_photo').hide();
    if(index == $("#total").html())
      $('#next_photo').hide();
    $("#current_index").html(index);
    img.src = url; 
  }

  function showPreviewFavoriteInfo(index){
    $('#preview .favorites').text(photoForIndex(index).find('.favorites').text()); 
    var photo = $('#preview')

   if(photoForIndex(index).hasClass('favorite')) {
     $('#large_preview').addClass('favorite');
     $('#large_preview').append('<img src="/images/favorite_marker.png" alt="favorite" class="marker" />');
     $('#preview .favorites').addClass('remove')
   } else {
     $('#large_preview').removeClass('favorite');
     $('#large_preview').find('.marker').remove();
     $('#preview .favorites').removeClass('remove')
   }
  }

  $('#back_to_gallery').click(function() {
    $('#photos').show();
    $('#preview').hide();
  });

  if(!$('#summary_track').length) { return; }

  $(window).scroll(function() {
    var top = $(window).scrollTop();
    var x   = $('#summary_track').offset().left;
    var y   = $('#summary_track').offset().top;
    if(top >= y-10) {
      $('#summary_track').removeClass('pinned').addClass('scrolling');
      $('#summary').css('left', x + 'px');
    } else {
      if(y > 10) {
      $('#summary').css('left', '');
        $('#summary_track').addClass('pinned').removeClass('scrolling');
      }
    }
  });

});


$(function() {
  $("#sortable").sortable({
  update:function(event,ui){
    var itemId = ui.item.attr("id").replace(/[^\d]/g, "");
    var itemPosition = ui.item.parent().children().index(ui.item) + 1; // acts_as_list is 1-based, not 0-based
    $.post('/portfolio_shots/' + itemId, {_method:"PUT", position:itemPosition}, function(){
    })  
  }
  });
  $("#sortable").disableSelection();
});


$(function() {

  $('.markup :text').keyup( function(e){
    $(this).limitPrecision(2);
    var row = $(this).closest('tr');
    var basePrice = row.find('td.base_price').html().toFloat();
    var markup = $(this).val().toFloat();
    var fullPrice = '$' + (basePrice + markup).toFixed(2);
    row.find('td.client_pays').html(fullPrice);
  });

});




$(function() {
  $('#see_more_prices_link').click(function() {
     var title         = $('#name');
     var wrapperOffset = $('#main_content').offset();
     var linkOffset    = $(this).offset();
     var prices        = $('#see_more_prices');
     var hidePrices    = $('#hide_prices');

     var top           = title.offset().top - wrapperOffset.top + title.height() + 10;
     var left          = Math.round(linkOffset.left) - Math.round(wrapperOffset.left) - 10;
     var height        = linkOffset.top - wrapperOffset.top - top - $(this).height() + 7;

     prices.css({ 'top': top+'px', 'left': left+'px', 'height': height+'px' }).fadeIn(150);
     return false;
  });

  $('#hide_prices').click(function() {
    $('#see_more_prices').hide();
  });
});


$(function() {

  $("div.scrollable").scrollable();

  $(".items img").click(function() { 
    var wrap = $("#large_image")
    //wrap.fadeTo("fast", 0.1); 
    var url = $(this).attr("src").replace("thumb", "showcase"); 
    var img = new Image();  
    img.onload = function() { 
      wrap.find("img").attr("src", url); 
      //wrap.fadeTo("fast", 1); 
    }; 
    img.src = url; 
  }).filter(":first").click();

});



$(function() {

  $(document).ready(function() {
    updateSummary();
  });

  $('#make_payment_link').click(function() {
    $('form').submit();
    return false;
  });
  
  $('.item input').keyup( function(e){
    $(this).forceToInt();
    if ($(this).val() == '0')
      $(this).select();
    updateSummary();
    return false;
  });

  $('.item input').click( function(e){
    $(this).select();
    return false;
  });

  $('.increment.arrow').click(function() {
    changeFieldBy(this, 1);
    return false;
  });

  $('.decrement.arrow').click(function() {
    changeFieldBy(this, -1);
    return false;
  });

  function changeFieldBy(element, diff){
    input = $(element).parents('.item').find('input');
    val = parseInt(input.val())+diff;
    if (isNaN(val) || val < 0)
      val = 0;
    input.val(val);
    updateSummary();   
  }

  function buildCartContents(){
    var summary = new Array();
    $('.item input[value!=0]').each(function(i,o){
      item = $(o).parents('.item');
      productId = item.find('.productId').html();
      count = parseInt($(o).val());
      description = item.find('.name').html();
      price = item.find('.price').html().replace(/[^\d|\.]/g,'');
      if(summary[productId]){
        summary[productId][0] += count; 
      }else{
        var orderLine = [count, description, price];
        summary[productId] = orderLine;
      }
    });
    return summary;
  }

  function updateSummary(){
    //alert($('.item input[value!=0]').html());
    $('#summary table tr').remove();
    var summary = buildCartContents();
    var total = 0.0;
    for (var productId in summary) {
      orderLine = summary[productId];
      var row = '<tr>';
      row += '<td class="item white bold">'+orderLine[1]+'</td>';
      row += '<td class="white bold">'+orderLine[0]+'</td>';
      row += '<td class="equal">=</td>';
      lineTotal = parseFloat(orderLine[2])*orderLine[0];
      row += '<td>$'+lineTotal.toFixed(2)+'</td>';
      row += '</tr>';
      $('#summary table').append(row);
      total += lineTotal;
    }
    var totRow = '<tr id="totals">';
    totRow += '<td class="white" colspan="3">subtotal:</td>';
    totRow += '<td class="bold">$'+total.toFixed(2)+'</td>';
    totRow += '</tr>';
    $('#summary table').append(totRow);
  }

});


$(function() {
  
  $('input[name="shoot[contact_method_preference]"]').change(function() {
    $('#phone_fields').toggle($(this).val() == 'phone');
  });

  $('input[name="shoot[contact_method_preference]"]:checked').change();

});


$(function() {
  $('a.zenbox').live('click', function() { Zenbox.render(); return false; });
  $('a.coming_soon').live('click', function() { return false; });
});

$.fn.extend({

  limitPrecision: function(limit) {
    var decimalPosition = this.val().indexOf('.');
    var precisionEntered = (this.val().length - decimalPosition) - 1;

    if (decimalPosition >= 0 && precisionEntered > limit){
      numberEntered = this.val().toFloat();
      this.val(numberEntered.toFixed(2));
    }
    return this;
  },

  forceToInt: function(){
    this.val(this.val().toInt());
    return this; 
  }

});

String.prototype.toInt = function() {
  var number = parseInt(this.replace(/[^\d]/g,''));
  if (isNaN(number)) return 0;
  return number;
};

String.prototype.toFloat = function() {
  var number = parseFloat(this.replace(/[^\d|\.]/g,''));
  if (isNaN(number)) return 0;
  return number;
};



/**
 * tools.scrollable 1.1.2 - Scroll your HTML with eye candy.
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/scrollable.html
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : March 2008
 * Date: ${date}
 * Revision: ${revision} 
 */
(function($) { 
		
	// static constructs
	$.tools = $.tools || {};
	
	$.tools.scrollable = {
		version: '1.1.2',
		
		conf: {
			
			// basics
			size: 6,
			vertical: false,
			speed: 400,
			keyboard: true,		
			
			// by default this is the same as size
			keyboardSteps: null, 
			
			// other
			disabledClass: 'disabled',
			hoverClass: null,		
			clickable: true,
			activeClass: 'active', 
			easing: 'swing',
			loop: false,
			
			items: '.items',
			item: null,
			
			// navigational elements			
			prev: '.prev',
			next: '.next',
			prevPage: '.prevPage',
			nextPage: '.nextPage', 
			api: false
			
			// CALLBACKS: onBeforeSeek, onSeek, onReload
		} 
	};
				
	var current;		
	
	// constructor
	function Scrollable(root, conf) {   
		
		// current instance
		var self = this, $self = $(this),
			 horizontal = !conf.vertical,
			 wrap = root.children(),
			 index = 0,
			 forward;  
		
		
		if (!current) { current = self; }
		
		// bind all callbacks from configuration
		$.each(conf, function(name, fn) {
			if ($.isFunction(fn)) { $self.bind(name, fn); }
		});
		
		if (wrap.length > 1) { wrap = $(conf.items, root); }
		
		// navigational items can be anywhere when globalNav = true
		function find(query) {
			var els = $(query);
			return conf.globalNav ? els : root.parent().find(query);	
		}
		
		// to be used by plugins
		root.data("finder", find);
		
		// get handle to navigational elements
		var prev = find(conf.prev),
			 next = find(conf.next),
			 prevPage = find(conf.prevPage),
			 nextPage = find(conf.nextPage);

		
		// methods
		$.extend(self, {
			
			getIndex: function() {
				return index;	
			},
			
			getClickIndex: function() {
				var items = self.getItems(); 
				return items.index(items.filter("." + conf.activeClass));	
			},
	
			getConf: function() {
				return conf;	
			},
			
			getSize: function() {
				return self.getItems().size();	
			},
	
			getPageAmount: function() {
				return Math.ceil(this.getSize() / conf.size); 	
			},
			
			getPageIndex: function() {
				return Math.ceil(index / conf.size);	
			},

			getNaviButtons: function() {
				return prev.add(next).add(prevPage).add(nextPage);	
			},
			
			getRoot: function() {
				return root;	
			},
			
			getItemWrap: function() {
				return wrap;	
			},
			
			getItems: function() {
				return wrap.children(conf.item);	
			},
			
			getVisibleItems: function() {
				return self.getItems().slice(index, index + conf.size);	
			},
			
			/* all seeking functions depend on this */		
			seekTo: function(i, time, fn) {

				if (i < 0) { i = 0; }				
				
				// nothing happens
				if (index === i) { return self; }				
				
				// function given as second argument
				if ($.isFunction(time)) {
					fn = time;
				}

				// seeking exceeds the end				 
				if (i > self.getSize() - conf.size) { 
					return conf.loop ? self.begin() : this.end(); 
				} 				

				var item = self.getItems().eq(i);					
				if (!item.length) { return self; }				
				
				// onBeforeSeek
				var e = $.Event("onBeforeSeek");

				$self.trigger(e, [i]);				
				if (e.isDefaultPrevented()) { return self; }				
				
				// get the (possibly altered) speed
				if (time === undefined || $.isFunction(time)) { time = conf.speed; }
				
				function callback() {
					if (fn) { fn.call(self, i); }
					$self.trigger("onSeek", [i]);
				}
				
				if (horizontal) {
					wrap.animate({left: -item.position().left}, time, conf.easing, callback);					
				} else {
					wrap.animate({top: -item.position().top}, time, conf.easing, callback);							
				}
				
				
				current = self;
				index = i;				
				
				// onStart
				e = $.Event("onStart");
				$self.trigger(e, [i]);				
				if (e.isDefaultPrevented()) { return self; }				
	
				
				/* default behaviour */
				
				// prev/next buttons disabled flags
				prev.add(prevPage).toggleClass(conf.disabledClass, i === 0);
				next.add(nextPage).toggleClass(conf.disabledClass, i >= self.getSize() - conf.size);
				
				return self; 
			},			
			
				
			move: function(offset, time, fn) {
				forward = offset > 0;
				return this.seekTo(index + offset, time, fn);
			},
			
			next: function(time, fn) {
				return this.move(1, time, fn);	
			},
			
			prev: function(time, fn) {
				return this.move(-1, time, fn);	
			},
			
			movePage: function(offset, time, fn) {
				forward = offset > 0;
				var steps = conf.size * offset;
				
				var i = index % conf.size;
				if (i > 0) {
				 	steps += (offset > 0 ? -i : conf.size - i);
				}
				
				return this.move(steps, time, fn);		
			},
			
			prevPage: function(time, fn) {
				return this.movePage(-1, time, fn);
			},  
	
			nextPage: function(time, fn) {
				return this.movePage(1, time, fn);
			},			
			
			setPage: function(page, time, fn) {
				return this.seekTo(page * conf.size, time, fn);
			},			
			
			begin: function(time, fn) {
				forward = false;
				return this.seekTo(0, time, fn);	
			},
			
			end: function(time, fn) {
				forward = true;
				var to = this.getSize() - conf.size;
				return to > 0 ? this.seekTo(to, time, fn) : self;	
			},
			
			reload: function() {				
				$self.trigger("onReload");
				return self;
			},			
			
			focus: function() {
				current = self;
				return self;
			},
			
			click: function(i) {
				
				var item = self.getItems().eq(i), 
					 klass = conf.activeClass,
					 size = conf.size;			
				
				// check that i is sane
				if (i < 0 || i >= self.getSize()) { return self; }
				
				// size == 1							
				if (size == 1) {
					if (conf.loop) { return self.next(); }
					
					if (i === 0 || i == self.getSize() -1)  { 
						forward = (forward === undefined) ? true : !forward;	 
					}
					return forward === false  ? self.prev() : self.next(); 
				} 
				
				// size == 2
				if (size == 2) {
					if (i == index) { i--; }
					self.getItems().removeClass(klass);
					item.addClass(klass);					
					return self.seekTo(i, time, fn);
				}				
		
				if (!item.hasClass(klass)) {				
					self.getItems().removeClass(klass);
					item.addClass(klass);
					var delta = Math.floor(size / 2);
					var to = i - delta;
		
					// next to last item must work
					if (to > self.getSize() - size) { 
						to = self.getSize() - size; 
					}
		
					if (to !== i) {
						return self.seekTo(to);		
					}
				}
				
				return self;
			},
			
			// bind / unbind
			bind: function(name, fn) {
				$self.bind(name, fn);
				return self;	
			},	
			
			unbind: function(name) {
				$self.unbind(name);
				return self;	
			}			
			
		});
		
		// callbacks	
		$.each("onBeforeSeek,onStart,onSeek,onReload".split(","), function(i, ev) {
			self[ev] = function(fn) {
				return self.bind(ev, fn);	
			};
		});  
			
			
		// prev button		
		prev.addClass(conf.disabledClass).click(function() {
			self.prev(); 
		});
		

		// next button
		next.click(function() { 
			self.next(); 
		});
		
		// prev page button
		nextPage.click(function() { 
			self.nextPage(); 
		});
		
		if (self.getSize() < conf.size) {
			next.add(nextPage).addClass(conf.disabledClass);	
		}
		

		// next page button
		prevPage.addClass(conf.disabledClass).click(function() { 
			self.prevPage(); 
		});		
		
		
		// hover
		var hc = conf.hoverClass, keyId = "keydown." + Math.random().toString().substring(10); 
			
		self.onReload(function() { 

			// hovering
			if (hc) {
				self.getItems().hover(function()  {
					$(this).addClass(hc);		
				}, function() {
					$(this).removeClass(hc);	
				});						
			}
			
			// clickable
			if (conf.clickable) {
				self.getItems().each(function(i) {
					$(this).unbind("click.scrollable").bind("click.scrollable", function(e) {
						if ($(e.target).is("a")) { return; }	
						return self.click(i);
					});
				});
			}				
			
			// keyboard			
			if (conf.keyboard) {				
				
				// keyboard works on one instance at the time. thus we need to unbind first
				$(document).unbind(keyId).bind(keyId, function(evt) {

					// do nothing with CTRL / ALT buttons
					if (evt.altKey || evt.ctrlKey) { return; }
					
					// do nothing for unstatic and unfocused instances
					if (conf.keyboard != 'static' && current != self) { return; }
					
					var s = conf.keyboardSteps;				
										
					if (horizontal && (evt.keyCode == 37 || evt.keyCode == 39)) {					
						self.move(evt.keyCode == 37 ? -s : s);
						return evt.preventDefault();
					}	
					
					if (!horizontal && (evt.keyCode == 38 || evt.keyCode == 40)) {
						self.move(evt.keyCode == 38 ? -s : s);
						return evt.preventDefault();
					}
					
					return true;
					
				});
				
			} else  {
				$(document).unbind(keyId);	
			}				

		});
		
		self.reload(); 
		
	} 

		
	// jQuery plugin implementation
	$.fn.scrollable = function(conf) { 
			
		// already constructed --> return API
		var el = this.eq(typeof conf == 'number' ? conf : 0).data("scrollable");
		if (el) { return el; }		 
 
		var globals = $.extend({}, $.tools.scrollable.conf);
		conf = $.extend(globals, conf);
		
		conf.keyboardSteps = conf.keyboardSteps || conf.size;
		
		this.each(function() {			
			el = new Scrollable($(this), conf);
			$(this).data("scrollable", el);	
		});
		
		return conf.api ? el: this; 
		
	};
			
	
})(jQuery);


$(function() {
  $('.thumbnail.load_later').loadLater();

  $('.thumbnail').each(function() {
    var div   = $(this);
    var image = div.find('img');
    var link  = div.find('a');

    var leftOffset = image.offset().left - div.offset().left - 11;
    link.css({ 'left': leftOffset+'px' });
  });

  $('#upload_progress').hide();
  $('#upload_complete').hide();

  $('#upload_more').click(function() {
    $('#select_photos_form').show();
    $('#upload_complete').hide();
  });

  $('#select_photos_form a.button').click(function() {
    $('#select_photos_form').hide();
    $('#upload_progress').show();

    $('#file_listing li:first').each(function(index, file) {
      animateUpload(file);
    });
  });
});

$.fn.extend({
  startUpload: function() {
    $(this).addClass('active');
  },

  updateProgress: function(percent) {
    var height = $(this).height();
    percent    = Math.ceil((100-percent)/(100/height));
    $(this).css('background-position', '0 ' + percent + 'px');
  },

  uploadComplete: function() {
    $(this).removeClass('active');
    var image = '<img src="/images/complete.png" alt="complete">';
    $(this).append(image);
    $(this).find('img').fadeIn(300);
  }
});

