
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
	
	LabPrints Online Storefronts JavaScript Library
	Full Source
	
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */



/* GLOBALS
************************************************************************** */

var ie6 										= false;
var ie7 										= false;
var ie											= false;
var safari = false;


// slideshow
var animating 									= false;
var waiting 									= false;
var waitingForNext								= false;
var waitingForPrev 								= false;
var speed 										= 50;
var photosShown 								= 0;
var picHeight 									= 0;
var timeout 									= 0;
var slideshowStatus 							= 'playing';
var previous_image_group_description 			= '';
var previous_image_group_id 					= '';
var previous_image_id							= '';
var next_image_group_description				= '';
var next_image_group_id 						= '';
var next_image_id 								= '';
var current_image_is_favorite 					= '';
var current_group_description 					= '';
var current_group_id 							= '';
var current_image_id 							= '';
var this_is_last_image							= 0;
var slideshow_api_page 							= '';
var server_image_path 							= '';
var apiURL 										= '';
var current_image_path 							= '';
var previous_image_path 						= '';
var next_image_path 							= '';
var add_image_id 								= '';
var original_redirect_url 						= '';

// compare
var active_image_id 							= '';
var active_drop									= '';
var currentLeft 								= 0;
var thumbWidth 									= 145;
var storefront_api 								= '';
var server_image_path 							= '';
var left_disabled 								= true;
var right_disabled 								= false;
var hiddenArea 									= 0;
var image1_id 									= '';
var image2_id 									= '';
var droppable_height 							= 0;
var loading_compare_image 						= false;
var hover1										= false;
var hover2										= false;
var scrubInterval								= '';

var packCurrentLeft 								= 0;
var pack_left_disabled 								= true;
var pack_right_disabled 								= false;
var pack_droppable_height 							= 0;
var packScrubInterval								= '';
var package_id;

var largeCurrentLeft 								= 0;
var large_left_disabled 								= true;
var large_right_disabled 								= false;

var largeScrubInterval								= '';
var bw_color_count_as_1 = true;
var drag_in_progress = false;
var dragging_enabled = true;
var complete_message_has_been_shown = false;
var recordLocationInterval = '';
var package_scroller_contents = new Array();
var package_scroller_has_changed = true;
var multipose = false;
var photo_album = false;



/* ------------------------------------
	FUNCTION			hookPrintLinks()
	PURPOSE				Hooks any print links
------------------------------------ */

function hookPrintLinks() {
	$('.print').click(function(e) {
		e.preventDefault();
		window.print();
		return false;
	});
}


/* ------------------------------------
	FUNCTION			urlencode()
	PURPOSE				Mimics urlencode() from PHP
------------------------------------ */

function urlencode(str) {
	str = escape(str);
	str = str.replace('#', '%23');
	// str = str.replace('+', '%2B');
	// str = str.replace('%20%26%20', '%20%26%20');
	// str = str.replace('*', '%2A');
	// str = str.replace('/', '%2F');
	// str = str.replace('@', '%40');
	return str;
}



/* ------------------------------------
	FUNCTION			addEmpties()
	PURPOSE				Adds empty thumbnail comtainers on the home page
						for aesthetic purpose only
------------------------------------ */

function addEmpties() {
	if($('#eventthumbs li').length!=0) {
		$('li.placeholder').remove();							// get rid of any existing; we don't want them
		var thumbsPerRow = 0;									// placeholder
		var thumbCount = $('#eventthumbs li').size();
		if(thumbCount>0) {										// are there any thumbs to work with?
			var firstThumbOffset = $('#eventthumbs li').offset();
			var firstOffseTop = firstThumbOffset.top;
			$('#eventthumbs li').each(function() {
				var currentOffset = $(this).offset();
				var currentTop = currentOffset.top;
				if(currentTop==firstOffseTop) {
					thumbsPerRow++;
				}
			});
			if(thumbCount%thumbsPerRow!=0) {
				var thumbsNeeded = thumbsPerRow - (thumbCount%thumbsPerRow);
				if(thumbsNeeded!=thumbsPerRow) {
					for(var i=1;i<=thumbsNeeded;i++) {
						$('#eventthumbs ul').append('<li class="placeholder"><div class="thumbnailhelp"><div class="thumbnail">&nbsp;</div></div></li>');
					}
				}
			}
		}
	}
}


/* ------------------------------------
	FUNCTION			manageHeights()
	PURPOSE				Provide some control for variable font size defaults
						causing gallery list items to render improperly
------------------------------------ */

function manageHeights() {
	if($('#eventthumbs li').length!=0) {
		var tallest = 0;
		$('#eventthumbs li').each(function() {
			if($(this).height()>tallest) { tallest = $(this).height(); }
			if(tallest<225) { tallest = 225; }
		});
		$('#eventthumbs li').each(function() {
			$(this).height(tallest);
		});
	}
}


/* ------------------------------------
	FUNCTION			checkLogoSize()
	PURPOSE				Make sure logo images don't flow outside container
------------------------------------ */

function checkLogoSize() {
	var widest = $('#border3').width();
	var logowidth = $('#border3 img').width();
	if(logowidth>widest) { 
		$('#border3 img').width(widest);
	}
}


/* ------------------------------------
	FUNCTION			checkSidebarHeight
	PURPOSE				Ensures the sidebar height matches that of the content
------------------------------------ */

function checkSidebarHeight () {

	// IE6 breaks in this case
	if( ie6 ){ return; }

	if( !safari ){

		sidebarheight = $('#sidebar').height();
		contentsidebarheight = $('#contentsidebar').height();
		containerheight = $('#sidebarcontainer').height();	

		//alert(sidebarheight + '|' + contentsidebarheight +  '|' + containerheight);	

		if($('.pagination').length!=0) { // account for pagination sections
			addon = $('.pagination').height();
		} else {
			addon = 0;
		}

		new_height = Math.max( addon + containerheight, sidebarheight, contentsidebarheight) ;

		$('#sidebarcontainer').height( new_height );
		$('#sidebarcontainer').parent().height( new_height );

	} else {

		// original
		if($('#sidebar').length!=0) {
			sidebarheight = $('#sidebar').height();
			contentsidebarheight = $('#contentsidebar').height();
		
			if(contentsidebarheight>sidebarheight) {
				diff = contentsidebarheight - sidebarheight;
				if($('.pagination').length!=0) { // account for pagination sections
					diff = diff + 350;
				} else {
					diff = diff + 150;
				}
				if(diff>400) {
					$('#sidebar ul ul').height(diff);
				}	
			}
		
			if($('#contentsidebar').height()<$('#sidebar ul ul').height() - 300) {
				$('#contentsidebar').height($('#sidebar ul ul').height()+150);
			}
		}
	}
}



/* ------------------------------------
	FUNCTION			hookFavoriteLogin
	PURPOSE				Binds functionality to the favorites login modal
------------------------------------ */

function hookFavoriteLogin() {
	if(ie6==false) {
		var validator = $('#customer_favorites_form').validate({
			rules: {
				favorites_email: {
					required: true,
					email: true
				},
				favorites_email_validate: {
					required: true,
					equalTo: '#favorites_email'
				}
			},
		
			messages: {
				favorites_email: {
					required: "Required",
					email: 'Invalid Email'
				},
				favorites_email_validate: {
					equalTo: 'Emails do not match'
				}
			},

			errorPlacement: function(error, element) {
				error.prependTo(element.parent());
				$('label.error').animate({ paddingRight: 25 }, {
					duration: 300,
					easing: 'easeInOutQuad',
					complete: function() {
						$('label.error').animate({ paddingRight: 2 }, {
							duration: 800,
							easing: 'easeOutBounce' });
					}
				});
			},

			success: function(label) {
				label.html('&nbsp;').addClass('valid');
			}

		});
	}
	
	// hook close button
	$('.buttons a').click(function() {
		$('.modalClose').click();
		return false;
	});
	
	// focus the first input
	$('#favorites_email').focus();
}


/* ------------------------------------
	FUNCTION			hookFavToggle
	PURPOSE				Hook the favorite toggle (event images and enlarged image page)
------------------------------------ */

function hookFavToggle() {
	if($('a.favoritetoggle').length!=0) {
		$('#favoriteLogin').hide();
		$('a.favoritetoggle').click(function(e) {
			e.preventDefault();
			if($('.nofavorites').length!=0||$('.noFavorites').length!=0) {
				tmpURL = $(this).attr("href").split("/");
				add_image_id  = tmpURL[tmpURL.length-1];
				$('#add_image_id').attr('value',add_image_id);
				$('#favoriteLogin').modal();
				hookFavoriteLogin();
			} else {
				$(this).addClass('loading');
				if($(this).hasClass('added')) { $(this).removeClass('added'); $(this).unbind('mouseout'); }
				if($(this).hasClass('removed')) { $(this).removeClass('removed'); $(this).unbind('mouseout'); }
				var status = $(this).attr('class').replace(new RegExp("favoritetoggle"), "").replace(new RegExp("favorite"), "").replace(new RegExp("loading"), "").replace(/^\s+|\s+$/g, '');
				var favLink = $(this);
				$.ajax({
					type: 'GET',
					url: $(this).attr('href'),
					success: function() {
						if(status=='off') {
							favLink.attr('class','favorite on added');
							var href = favLink.attr('href').replace(new RegExp("add_to_favorites"), "remove_from_favorites");
							favLink.attr('href',href);
							favLink.attr('title','Remove as favorite');
							favLink.mouseout(function() {
								favLink.removeClass('added');
								favLink.unbind('mouseout');
							});
						} else {
							favLink.attr('class','favorite off removed');
							var href = favLink.attr('href').replace(new RegExp("remove_from_favorites"), "add_to_favorites");
							favLink.attr('href',href);
							favLink.attr('title','Add as favorite');
							favLink.mouseout(function() {
								favLink.removeClass('removed');
								favLink.unbind('mouseout');
							});
						}
					}
				});
			}
			return false;
		});
	}
}


/* ------------------------------------
	FUNCTION			hookFavoritesLink
	PURPOSE				Hook sidebar favorites link to check whether
						or not we need to invoke the login
------------------------------------ */

function hookFavoritesLink() {
	if($('.nofavorites').length!=0) {
		var original_redirect_url = $('#favorites_redirect').attr('value');
		$('.nofavorites').click(function(e) {
			e.preventDefault();

			// check to see if we're in the slideshow...
			if(original_redirect_url.indexOf('slideshow')>0) {
				redirectURL = original_redirect_url + current_image_id + '/' + current_group_id;
				$('#favorites_redirect').attr('value',redirectURL);
				$('#add_image_id').attr('value',current_image_id);
			} else if( multipose || photo_album){
				// don't do anything, wait until below...
			} else if(original_redirect_url.indexOf('view_images')<0) {
				tmpURL = $(this).attr("href").split("/");
				add_image_id  = tmpURL[tmpURL.length-1];
				$('#add_image_id').attr('value',add_image_id);
			}
			
			// check to see if this is the sidebar button
			if($(this).parent().parent().attr('id')=='sidebar') {
				if( photo_album ){				
					$('#favorites_redirect').attr('value','view_photo_album/index/' + package_id + '/lp_customer_favorites');
				} else if( multipose ){
					$('#favorites_redirect').attr('value','view_multipose/index/' + package_id + '/lp_customer_favorites');				
				} else {
					$('#favorites_redirect').attr('value','view_images/index/lp_customer_favorites');
				}
			}
			$('#favoriteLogin').modal();
			hookFavoriteLogin();
			return false;
		});
	}
}


/* ------------------------------------
	FUNCTION			hookLightboxLinks
	PURPOSE				Bind to any links which should lightbox
						larger images
------------------------------------ */

function hookLightboxLinks() {
	$('a.lightbox').lightBox();
}


/* ------------------------------------
	FUNCTION			hookPagination
	PURPOSE				Bind to the pagination function on the
						Event Images page
------------------------------------ */

function hookPagination() {
	if($('.pagination form').length!=0) {
		$('.pagination form').submit(function(e) {
			e.preventDefault();
			var targetSelect = $(this).find('label').attr('for');
			$('select#' + targetSelect + ' option:selected').each(function () { targetURL = $(this).attr('value'); });
			window.location = targetURL;
			return false;
		});
	}
}


/* ------------------------------------
	FUNCTION			hookBackToTop
	PURPOSE				Include a Back to Top link if there
						is enough page content
------------------------------------ */

function hookBackToTop() {
	if($('#eventimagethumbs').length!=0) {
		// ADD BACK TO TOP LINK
		var thumbcount = $('#eventimagethumbs li').size();
		if(thumbcount>30) {
			$('#eventimagethumbs').after('<p id="backtotop"><a href="#header">Back to top</a></p>');
			$('#backtotop a').click(function(e) {
				e.preventDefault();
				var speed = (Math.floor(thumbcount/3))*100;
				while(speed>2500) { speed = Math.floor(speed/2); }
				$.scrollTo( '#header', speed, {easing:'easeOutCubic'} );
			});
		}
	}
}


/* ------------------------------------
	FUNCTION			fixEventImageHeights
	PURPOSE				Ensure that all Storefront Event image
						containers are of equal height
------------------------------------ */

function fixEventImageHeights() {
	/*  This is commented out because when a large number of
	 thumbs are being loaded, the script gives up too soon because
	 thumbsLoaded never reaches totalThumbs, which causes rendering
	 issues.  If you can find a fix, go for it!
	 
	// fix some quirky cross-browser issues
	var thumbsLoaded = 0;

	var totalThumbs = $('#eventthumbs li').size();
	$('#eventthumbs img').load(function() {
		thumbsLoaded++;
		if(thumbsLoaded==totalThumbs) {*/
			addEmpties();
			manageHeights();
		/*}
	});*/
}


function initImagesPage(){

	// Hide it initially
	$('#multipose_modal').hide();
	$('#discount_modal').hide();

	// Make it show up when one of the links is clicked
	$('.package_modal_trigger').click(function(e) {
		e.preventDefault();
		$('#multipose_modal').modal();
		return false;
	});
	$('.discount_modal_trigger').click(function(e) {
		e.preventDefault();
		$('#discount_modal').modal();
		return false;
	});
	
	// Make it hidden again
	$('.back_to_images').click( function(e){
		$('.modalClose').click();
	});
	
	

}



























/* SLIDESHOW
************************************************************************** */


/* ------------------------------------
	FUNCTION			loadImage
	PURPOSE				Cycles a new image in the slideshow. Able to 
						pass direction in which slideshow is traveling
	VARIABLES			String direction		'next'
												'previous'
						Boolean force			When true, will force a new 
												image to load. For use when 
												slideshow is paused.
------------------------------------ */

function loadImage(direction, force) {
	waiting = false;
	$('#slideshowimage').addClass('loading');
	if(slideshowStatus=='playing'||(typeof force != 'undefined')) {
		
		// hide the favorite status
		if(ie7==true) {
			$('#favcontrol').hide();
		} else {
			$('#favcontrol').fadeOut('fast');
		}
		
		$('#imagecontainer').fadeOut(300,function() {
			
			// check to see if the whole slideshow has played, if so, force pause and display message
			if(this_is_last_image==1) {
				$('#pause').click();
				$('#slideshowinner').html('<p class="notice">You have viewed all the images for this event.</p><p class="notice">Press play to restart the slideshow.</p>');
				$('#slideshowimage').removeClass('loading');
				$('#imagecontainer').fadeIn(1500);
				this_is_last_image = 0;
				$('#this_is_last_image').text("0");
				return false;
			}
			
			// check to see if there is no image to display
			if(typeof(current_image)!='undefined') {
				if(current_image=="") {
					$('#pause').click();
					$('#slideshowinner').html('<p class="notice">There are no images available to display.</p>');
					$('#slideshowimage').removeClass('loading');
					$('#imagecontainer').fadeIn(1500);
					return false;
				}	
			}

			// LOAD current_image_path
			var img = new Image();
			
			// Need to update at least the image id and group id
			if(direction=='current') {
				targetImage = $('#server_image_path').text()+$('#current_image_id').text();
			} else if(direction=='prev') {
				targetImage = $('#server_image_path').text()+$('#previous_image_id').text();
				if($('#previous_image_group_id').text().replace(/^\s+|\s+$/g, '')!='') {
					$('#current_group_id').text($('#previous_image_group_id').text());
				}
				$('#current_image_id').text($('#previous_image_id').text());
			} else {
				targetImage = $('#server_image_path').text()+$('#next_image_id').text();
				if($('#next_image_group_id').text().replace(/^\s+|\s+$/g, '')!='') {
					$('#current_group_id').text($('#next_image_group_id').text());
				}
				$('#current_image_id').text($('#next_image_id').text());
			}
			
			$(img).load(function () {
				$('#slideshowimage').removeClass('loading');
				$('#slideshowinner').empty().append(this);
				$(this).attr('id','nextimage');
				$('#imagename').fadeOut('fast',function() {
					$('#imagename').text($('#current_image_id').text());
					$('#imagename').fadeIn('fast');
				});

				$('#nextimage').attr('id','currentimage');
				$('#imagecontainer').fadeIn(1500,function() {photosShown++;});

				// SET UP ALL VARIABLES
				current_group_id = $('#current_group_id').text();
				current_image_id = $('#current_image_id').text();
				slideshow_api_page = $('#slideshow_api_page').text();
				server_image_path = $('#server_image_path').text();
				apiURL = slideshow_api_page + '/' + current_group_id + '/' + current_image_id;

				// MAKE AJAX REQUEST
				$.get(apiURL, function(data){
					$(data).find('Property').each(function() { 
						switch($(this).attr('key')) {
						case "previous_image_group_description":
							previous_image_group_description = $(this).text();
							$('#previous_image_group_description').text(previous_image_group_description);
							break;
						case "previous_image_group_id":
							previous_image_group_id = $(this).text();
							$('#previous_image_group_id').text(previous_image_group_id);
							break;
						case "previous_image_id":
							previous_image_id = $(this).text();
							$("#previous_image_id").text(previous_image_id);
							break;
						case "next_image_group_description":
							next_image_group_description = $(this).text();
							$('#next_image_group_description').text(next_image_group_description);
							break;
						case "next_image_group_id":
							next_image_group_id = $(this).text();
							$('#next_image_group_id').text(next_image_group_id);
							break;
						case "next_image_id":
							next_image_id = $(this).text();
							$('#next_image_id').text(next_image_id);
							break;
						case "current_image_is_favorite":
							current_image_is_favorite = $(this).text();
							$('#current_image_is_favorite').text(current_image_is_favorite);
							break;
						case "current_group_description":
							current_group_description = $(this).text();
							$('#current_group_description').text(current_group_description);
							break;
						case "this_is_last_image":
							this_is_last_image = $(this).text();
							$('#this_is_last_image').text(this_is_last_image);
							break;
						default:
							break;
						}
					});

					if(current_image_is_favorite.toUpperCase()=='FALSE') {
						if($('#favcontrol a').hasClass('nofavorites')) {
							$('#favcontrol a').attr('class','nofavorites off');
						} else {
							$('#favcontrol a').attr('class','off');
						}
					} else {
						if($('#favcontrol a').hasClass('nofavorites')) {
							$('#favcontrol a').attr('class','nofavorites on');
						} else {
							$('#favcontrol a').attr('class','on');
						}
					}
					
					// show the favorite status
					if(ie7==true) {
						$('#favcontrol').show();
					} else {
						$('#favcontrol').fadeIn('fast');
					}

					// DONE PARSING XML AND SETTING VARS, SETTIMEOUT AND REPEAT

					current_image_path = server_image_path + current_image_id;
					previous_image_path = server_image_path + previous_image_id;
					next_image_path = server_image_path + next_image_id;
					speed = $('#speedslider').slider('value');
					timeout = Math.floor(6000 - (speed*50));

					if(slideshowStatus=='playing') {
						waiting = true;
						setTimeout('loadImage("next")',timeout);
					}

					if(typeof force != 'undefined') {
						hookNext();
						hookPrev();
					}
					
					// Stop thievery
					stopImageDrag();

				});
			})
			.attr('src', targetImage);
			
		});
	}
}


/* ------------------------------------
	FUNCTION			hookNext
	PURPOSE				Add functionality to Next button
------------------------------------ */

function hookNext() {
	$('#controlNext').fadeTo(150, 0.99);
	if(ie6) { $('#controlNext').removeClass("invisible"); }
	$('#next').removeClass('inactive');
	$('#next').unbind('click');
	$('#next').click(function(e) {
		e.preventDefault();
		unhookNext();
		loadImage('next', 'force');
		return false;
	});
}


/* ------------------------------------
	FUNCTION			hookPrev
	PURPOSE				Add functionality to Previous button
------------------------------------ */

function hookPrev() {
	$('#controlPrev').fadeTo(150, 0.99);
	if(ie6) { $('#controlPrev').removeClass("invisible"); }
	$('#prev').removeClass('inactive');
	$('#prev').unbind('click');
	$('#prev').click(function(e) {
		e.preventDefault();
		unhookPrev();
		loadImage('prev','force');
		return false;
	});
}


/* ------------------------------------
	FUNCTION			unhookNext
	PURPOSE				Remove functionality and disable Next button
------------------------------------ */

function unhookNext() {
	waitingForNext=true;
	$('#next').unbind('click');
	$('#next').click(function() { return false; });
	$('#next').addClass('inactive');
	$('#controlNext').fadeTo(150, 0.5);
	if(ie6) { $('#controlNext').addClass("invisible"); }
}


/* ------------------------------------
	FUNCTION			unhookPrev
	PURPOSE				Remove functionality and disable Previous button
------------------------------------ */

function unhookPrev() {
	waitingForPrev=true;
	$('#prev').unbind('click');
	$('#prev').click(function() { return false; });
	$('#prev').addClass('inactive');
	$('#controlPrev').fadeTo(150, 0.5);
	if(ie6) { $('#controlPrev').addClass("invisible"); }
}


/* ------------------------------------
	FUNCTION			hookPause
	PURPOSE				Add functionality to Pause button
------------------------------------ */

function hookPause() {
	unhookNext();
	unhookPrev();
	$('#pause').click(function(e) {
		if(slideshowStatus!='paused') {
			e.preventDefault();
			hookNext();
			hookPrev();
			slideshowStatus = 'paused';
			$(this).unbind('click');
			$(this).attr('id','play');
			hookPlay();
			return false;
		}
	});
}


/* ------------------------------------
	FUNCTION			hookPlay
	PURPOSE				Add functionality to Play button
------------------------------------ */

function hookPlay() {
	$('#play').click(function(e) {
		if(slideshowStatus!='playing') {
			e.preventDefault();
			unhookNext();
			unhookPrev();
			slideshowStatus = 'playing';
			$(this).unbind('click');
			$(this).attr('id','pause');
			hookPause();
			if(waiting==false) { loadImage('next'); }
			return false;
		}
	});
}


/* ------------------------------------
	FUNCTION			hookAltFavToggle
	PURPOSE				Hooks favorite button to toggle favorite status
------------------------------------ */

function hookAltFavToggle() {
	$('#favcontrol a, #actionFavorite a, .compare_fav a').click(function(e) {
		e.preventDefault();
		
		// slideshow check and var setup
		if(slideshowStatus=='playing') {
			$('#pause').click();
		}
		
	
		if($('.nofavorites').length==0&&$('.noFavorites').length==0) {					// make sure user is logged in
			toggle = $(this);
			if(toggle.hasClass('off')) {
				toggle.addClass('loading');
				if($('.compare_fav a').length!=0) {			// if we're on the compare page, we've already got the URL
					targetURL = $(this).attr('href');
				} else {
					targetURL = $('#link_to_add_favorite').text() + $('#current_image_id').text();
				}
				$.ajax({
					type: 'GET',
					url: targetURL,
					success: function() {
						toggle.removeClass('loading');
						toggle.removeClass('off');
						toggle.addClass('on');
					}
				});
				if($('.compare_fav a').length!=0) {			// if we're on the compare page, we need to swap the URL
					updatedURL = $(this).attr('href').replace(new RegExp("add_to_favorites"), "remove_from_favorites");
					$(this).attr('href',updatedURL);
				}
			}
			if(toggle.hasClass('on')) {
				toggle.addClass('loading');
				if($('.compare_fav a').length!=0) {			// if we're on the compare page, we've already got the URL
					targetURL = $(this).attr('href');
				} else {
					targetURL = $('#link_to_remove_favorite').text() + $('#current_image_id').text();
				}
				$.ajax({
					type: 'GET',
					url: targetURL,
					success: function() {
						toggle.removeClass('loading');
						toggle.removeClass('on');
						toggle.addClass('off');
					}
				});
				if($('.compare_fav a').length!=0) {			// if we're on the compare page, we need to swap the URL
					updatedURL = $(this).attr('href').replace(new RegExp("remove_from_favorites"), "add_to_favorites");
					$(this).attr('href',updatedURL);
				}
			}
			
			// if we're on the compare page, we need to toggle classes of the group images...
			if($('.compare_fav a').length!=0) {
				tmpURL = $(this).attr("href").split("/");
				fav_toggle_id  = tmpURL[tmpURL.length-1];
				$('#groupimagelist img').each(function() {
					if($(this).attr('alt')==fav_toggle_id) {
						if($(this).hasClass('yesfav')) {
							$(this).removeClass('yesfav');
							$(this).addClass('nofav');
							
							// we need to check to see if the same image is in both repositories
							if(image1_id==image2_id) {
								// ensure the same classes
								$('#controls1 .compare_fav a').attr('class','off');
								$('#controls2 .compare_fav a').attr('class','off');
								// also need to fix the favorite URL
								updatedURL = $('#controls1 .compare_fav a').attr('href').replace(new RegExp("remove_from_favorites"), "add_to_favorites");
								$('#controls1 .compare_fav a').attr('href',updatedURL);
								updatedURL = $('#controls2 .compare_fav a').attr('href').replace(new RegExp("remove_from_favorites"), "add_to_favorites");
								$('#controls2 .compare_fav a').attr('href',updatedURL);
							}
						} else {
							$(this).removeClass('nofav');
							$(this).addClass('yesfav');
							
							// we need to check to see if the same image is in both repositories
							if(image1_id==image2_id) {
								// ensure the same classes
								$('#controls1 .compare_fav a').attr('class','on');
								$('#controls2 .compare_fav a').attr('class','on');
								// also need to fix the favorite URL
								updatedURL = $('#controls1 .compare_fav a').attr('href').replace(new RegExp("add_to_favorites"), "remove_from_favorites");
								$('#controls1 .compare_fav a').attr('href',updatedURL);
								updatedURL = $('#controls2 .compare_fav a').attr('href').replace(new RegExp("add_to_favorites"), "remove_from_favorites");
								$('#controls2 .compare_fav a').attr('href',updatedURL);
							}
						}
					}
				});
			}
			
		}
		return false;
	});
}


/* ------------------------------------
	FUNCTION			hookSpeedControl
	PURPOSE				Establish slider for speed control
------------------------------------ */

function hookSpeedControl() {
	$('#speedslider').slider();
}


/* ------------------------------------
	FUNCTION			initSlideshow
	PURPOSE				Invoke all slideshow functionality
------------------------------------ */

function initSlideshow() {
	$('#slideshowimage').addClass('loading');
	hookSpeedControl();
	hookPause();
	hookAltFavToggle();
	loadImage('current');
	var temp = $('#speedslider').slider("moveTo", 50);
}



























/* COMPARE IMAGES
************************************************************************** */

/* ------------------------------------
	FUNCTION			scrub
	PURPOSE				Provides a constant animation for the images
------------------------------------ */

function scrub(direction) {
newLeft = currentLeft;
	if(direction=='right') {
		fullListWidth 			= $('#groupimagelist ul').width();
		listContainerWidth 		= $('#groupimagelist').width();
		if(currentLeft>(listContainerWidth-fullListWidth)) {
			newLeft = currentLeft-15;
		} else {
			$('#rightscrub').mouseup();
			disableRight();
		}
	} else {
		if(currentLeft<0) {
			newLeft = currentLeft+15;
		} else {
			$('#leftscrub').mouseup();
			disableLeft();
		}
	}
	currentLeft = newLeft;
	$('#groupimagelist ul').css('left',newLeft);
}



/* ------------------------------------
	FUNCTION			hookLeft
	PURPOSE				Hook the left scroller
------------------------------------ */

function hookLeft() {
	left_disabled = false;
	$('#left a').removeClass('inactive');
	$('#left a').unbind('click');
	$('#left a').unbind('mouseup');
	$('#left a').unbind('mousedown');
	$('#left a').unbind('mouseout');
	
	
	$('#lefthop').click(function(e) {
		e.preventDefault();
		if(currentLeft<0) {
			currentLeft = currentLeft + ($('#groupimagelist').width() - (thumbWidth));

			// check to make sure we don't go too far, and disable the button
			if(currentLeft>=0) {
				currentLeft = 1;
				disableLeft();
			}

			// need to enable right button
			if(right_disabled) { hookRight(); }

			$('#groupimagelist ul').animate({ left:currentLeft }, {
				duration: 1300,
				easing: 'easeInOutQuart'
			});
		}
		return false;
	});
	
	// left scrub -- hooks mousedown to continually slide
	$('#leftscrub').mousedown(function() {
		if(right_disabled) { hookRight(); }
		scrubInterval = setInterval('scrub("left")',5);
	})
	.mouseup(function() {
		clearInterval(scrubInterval);
		return false;
	})
	.mouseout(function() {
		clearInterval(scrubInterval);
		return false;
	});
	
	$('#left').fadeTo(150, 0.99);
}


/* ------------------------------------
	FUNCTION			hookRight
	PURPOSE				Hook the right scroller
------------------------------------ */

function hookRight() {
	if($('#groupimagelist ul').width()>$('#groupimagelist').width()){
		right_disabled = false;
		$('#right a').removeClass('inactive');
		$('#right a').unbind('click');
		$('#right a').unbind('mouseup');
		$('#right a').unbind('mousedown');
		$('#right a').unbind('mouseout');
		
		// right hop -- slide over an entire visible section automatically
		$('#righthop').click(function(e) {
			e.preventDefault();
			
			fullListWidth 			= $('#groupimagelist ul').width();
			listContainerWidth 		= $('#groupimagelist').width();
			
			if(currentLeft>(listContainerWidth-fullListWidth)) {
				adjustment = listContainerWidth - (thumbWidth);
				currentLeft = currentLeft - (listContainerWidth - (thumbWidth));

				// check to see if we're going to create too much whitespace on the right
				if(currentLeft<(listContainerWidth-fullListWidth)) {
					currentLeft = 0-(fullListWidth-listContainerWidth);
					disableRight();
				}
				
				// need to enable left button
				if(left_disabled) { hookLeft(); }
				
				$('#groupimagelist ul').animate({ left:currentLeft }, {
					duration: 1300,
					easing: 'easeInOutQuart'
				});
			}
			return false;
		});
		
		// right scrub -- hooks mousedown to continually slide
		$('#rightscrub').mousedown(function() {
			if(left_disabled) { hookLeft(); }
			scrubInterval = setInterval('scrub("right")',5);
		})
		.mouseup(function() {
			clearInterval(scrubInterval);
			return false;
		})
		.mouseout(function() {
			clearInterval(scrubInterval);
			return false;
		});
		
		$('#right').fadeTo(150, 0.99);
	} else {
		disableRight();
	}
}


/* ------------------------------------
	FUNCTION			disableLeft
	PURPOSE				Disable left scroller if no more images are available
------------------------------------ */

function disableLeft() {
	$('#left a').unbind('click');
	$('#left a').click(function() { return false; });
	$('#left a').addClass('inactive');
	$('#left').fadeTo(150, 0.3);
	left_disabled = true;
}


/* ------------------------------------
	FUNCTION			disableRight
	PURPOSE				Disable right scroller if no more images are available
------------------------------------ */

function disableRight() {
	$('#right a').unbind('click');
	$('#right a').click(function() { return false; });
	$('#right a').addClass('inactive');
	$('#right').fadeTo(150, 0.3);
	right_disabled = true;
}


/* ------------------------------------
	FUNCTION			hookGroups
	PURPOSE				Hook the list of groups to load via AJAX
------------------------------------ */

function hookGroups( caller ) {
	$('.groups li a, .favorites:not(.nofavorites) a').click(function(e) {
		e.preventDefault();
		
		// need to reset the scrolling functionality
		disableLeft();
		disableRight();
		
		groupLink = $(this);
		$('#groupimagelist ul').fadeOut(500, function() {
			targetURL = groupLink.attr("href").split("/");
			group_id = targetURL[targetURL.length-1];
			apiURL = storefront_api + '/get_group_images/' + base64_encode(group_id);
			//apiURL = storefront_api + '/get_group_images/' + urlencode(group_id);
			$('#groupimagelist ul').empty();
			$('#groupimagelist div').addClass("loading");

			// MAKE AJAX REQUEST
			$.get(apiURL, function(data){
				$('#groupimagelist div').removeClass("loading");
				$('#current_group').text($(data).find("ImageGroup").attr("ID"));
				$(data).find("Image").each(function() {
					thumbID = $(this).attr("ID");
					fav_status = $(this).attr("IsFavorite");
					if(fav_status.toUpperCase()=="FALSE") {
						fav_status = 'nofav';
					} else {
						fav_status = 'yesfav';
					}
					$('#groupimagelist ul').append('<li><div class="outer"><div class="middle comparemiddle"><div class="inner compareinner"><span class="hidden source_image_id">' + thumbID + '</span><img title="' + thumbID + '" src="' + server_image_path + '/thumb/' + thumbID + '" alt="' + $(this).text() + '" class="comparesource ' + fav_status + '" /></div></div></div></li>');
				});
				// This code is reused in Compare and MP pages
				// 0 is when it's used in Compare
				// 1 is when it's used in Multipose
				
				$('.groups ul li a').removeAttr('id');
				
				$('.groups ul li a').each( function(){
					if( $(this).text() == group_id ){
						$(this).attr('id', 'active');
					}
				});
				
				
				if( caller == 0 ){
					initScrolling();
				} else if( caller == 1){
					//initScrollingPackageContents();
					hookPackageDraggables();

	$("#groupimagelist ul").css("left",0);
	currentLeft = 0;

					$('#groupimagelist ul').width((thumbWidth * $('#groupimagelist ul li').size())+thumbWidth);
					if($('#groupimagelist ul').width()==0) { $('#groupimagelist ul').width(thumbWidth); }

					hookLeft();
					hookRight();

				}
				
				$("#groupimagelist ul").fadeIn(1000);
			});
		});
		return false;
	});
}


/* ------------------------------------
	FUNCTION			hookDraggables
	PURPOSE				Hook all the group images to be draggable
------------------------------------ */

function hookDraggables() {

	$('.comparesource').draggable({
		zIndex:500,
		helper:'clone',
		appendTo:'#clonehelper',
		scroll:false,
		containment:'#comparecontainer',
		opacity:0.75,
		start: function() { 
			active_image_id = $(this).parent().find("span.source_image_id").text(); 
			
			// need the location and dimension of drop1
			drop1offset = $('#drop1').offset();
			drop1left = drop1offset.left;
			drop1top = drop1offset.top;
			drop1width = $('#drop1').width();
			drop1height = $('#drop1').height();
			
			// need the location and dimension of drop2
			drop2offset = $('#drop2').offset();
			drop2left = drop2offset.left;
			drop2top = drop2offset.top;
			drop2width = $('#drop2').width();
			drop2height = $('#drop2').height();
			},
		drag: function() {
			helperoffset = $('#clonehelper img').offset();
			helperleft = helperoffset.left;
			helpertop = helperoffset.top;
			
			// determine if the helper is in drop1
			if((helperleft>drop1left)&&(helpertop>drop1top)&&(helpertop<(drop1top+drop1height))&&(helperleft<(drop1left+drop1width))) {
				$('#drop1').addClass('droppable-hover');
				hover1 = true;
			} else {
				$('#drop1').removeClass('droppable-hover');
				hover1 = false;
			}
			
			// determine if the helper is in drop2
			if((helperleft>drop2left)&&(helpertop>drop2top)&&(helpertop<(drop2top+drop2height))&&(helperleft<(drop2left+drop2width))) {
				$('#drop2').addClass('droppable-hover');
				hover2 = true;
			} else {
				$('#drop2').removeClass('droppable-hover');
				hover2 = false;
			}
		},
		stop: function() {
			$('#drop1').removeClass('droppable-hover');
			$('#drop2').removeClass('droppable-hover');
			if(hover1==true||hover2==true) {
				if(hover1==true) {
					active_drop = $('#drop1');
				} else {
					active_drop = $('#drop2');
				}
				
				// load the new image
				if(loading_compare_image==false)
				{
					helper = $('#clonehelper img');
					disableDrag();
					active_drop.parent().find('.imagename').text(helper.attr('alt'));

					// check to see if image is a favorite
					if(helper.hasClass('yesfav')) {
						// currently is a favorite, need to generate link to remove
						targetFavURL = $('#link_to_remove_favorite').text() + active_image_id;
						targetFavClass = 'on';
					} else {
						// currently is not a favorite, need to generate link to add
						targetFavURL = $('#link_to_add_favorite').text() + active_image_id;
						targetFavClass = 'off';
					}

					// set proper classes
					targetToggle = active_drop.parent().parent().find('.compare_fav a');
					if(targetToggle.hasClass('on')&&targetFavClass=='off') {
						targetToggle.removeClass('on').addClass('off');
					}
					if(targetToggle.hasClass('off')&&targetFavClass=='on') {
						targetToggle.removeClass('off').addClass('on');
					}
					targetToggle.attr('href',targetFavURL);

					// we'are always loading the color version, take out any bw classes
					active_drop.parent().parent().find('li a.color').each(function() {
						$(this).removeClass('color');
						$(this).addClass('bw');
					});

					// set the proper image id for the cart
					active_drop.parent().parent().find('input.imageid').attr('value',active_image_id);


					active_drop.height(droppable_height);
					active_drop.empty();
					active_drop.removeClass("empty");
					// $(this).css('backgroundImage','none');
					active_drop.addClass("loading");
					var img = new Image();
					$(img).load(function () {
						$(this).hide();
						active_drop.removeClass('loading');
						workingImage = $(this);
						active_drop.append(workingImage);

						checkImageSizes();

						workingImage.fadeIn("slow");

						// Update API to track which images are added
						active_drop_id = active_drop.attr('id').replace(new RegExp("drop"), "");
						if(active_drop_id==1) {
							image1_id = active_image_id;
							$('<span id="image1_id" class="hidden imageid">' + image1_id + '</span>').appendTo($('#contain1 p.imagename'));
						} else {
							image2_id = active_image_id;
							$('<span id="image2_id" class="hidden imageid">' + image2_id + '</span>').appendTo($('#contain2 p.imagename'));
						}
						if($('#compareimages').find('.empty').length==0) {
								apiURL = storefront_api + '/set_selected_compare_images/' + image1_id + '/' + image2_id;
								$.get(apiURL, function() {
									enableDrag();
								});
						}
						
						// Update the favorites redirect variable
						if(image1_id=="") { image1_id_tmp = "NULL"; } else { image1_id_tmp = image1_id; }
						if(image2_id=="") { image2_id_tmp = "NULL"; } else { image2_id_tmp = image2_id; }
						$('#favorites_redirect').attr('value','/view_compare_images/index/' + image1_id_tmp + '/' + image2_id_tmp + '/' + $('#current_group').text());
						checkImageSizes();
						enableDrag();
						
						// Stop thievery
						stopThievery();
						
					})
					.attr('src', server_image_path + '/low_res/' + active_image_id);
				}
				
			}
			
		}
	});	
}


/* ------------------------------------
	FUNCTION			disableDrag
	PURPOSE				Disable drag functionality
------------------------------------ */

function disableDrag() {
	loading_compare_image = true;
	//$('.comparesource').draggable('disable');
}


/* ------------------------------------
	FUNCTION			enableDrag
	PURPOSE				Enable drag functionality
------------------------------------ */

function enableDrag() {
	//$('.comparesource').draggable('enable');
	loading_compare_image = false;
}


/* ------------------------------------
	FUNCTION			initScrolling
	PURPOSE				Sets various variables for horizontal scroller
------------------------------------ */

function initScrolling() {
	hookDraggables();
	$("#groupimagelist ul").css("left",0);
	currentLeft = 0;
	$('#groupimagelist ul').width((thumbWidth * $('#groupimagelist ul li').size())+thumbWidth);
	if($('#groupimagelist ul').width()==0) { $('#groupimagelist ul').width(thumbWidth); }
	hookRight();
	disableLeft();
}


/* ------------------------------------
	FUNCTION			checkImageSizes
	PURPOSE				Ensures images in resevoir don't overlap
------------------------------------ */

function checkImageSizes() {
	if($('.droppable img').length!=0) {
		droppable_height = 300;
		$('.droppable img').each(function() {
			target_width = $(this).parent().width();
			if($('#orderimage').length!=0) { 
				target_width = $('.droppable').width();
			}
			if(($(this).height()<$(this).width())) {
				// landscape
				$(this).height('auto');
				$(this).css('height','auto');
				$(this).width(target_width);
				if($(this).height()>droppable_height) {
					// the new height exceeds viewable area, need to double back
					$(this).width('auto');
					$(this).css('width','auto');
					$(this).height(droppable_height);
				}
				if($(this).width()>target_width) {
					// the new width exceeds viewable area, need to double back
					$(this).height('auto');
					$(this).css('height','auto');
					$(this).width(target_width);
				}
			} else {
				// portrait or square
				$(this).width('auto');
				$(this).css('width','auto');
				$(this).height(droppable_height);
				if($(this).width()>target_width) {
					// the new width exceeds viewable area, need to double back
					$(this).height('auto');
					$(this).css('height','auto');
					$(this).width(target_width);
				}
				if($(this).height()>droppable_height) {
					// the new height exceeds viewable area, need to double back
					$(this).width('auto');
					$(this).css('width','auto');
					$(this).height(droppable_height);
				}
			}
		});
	}
}


/* ------------------------------------
	FUNCTION			loadImage
	PURPOSE				Will load an image into a repository
	VARIABLES			jQuery object		image_container
						string				image_url
------------------------------------ */

function loadCompareImage(image_container,image_url,image_id,callback) {
	image_container.empty();
	image_container.removeClass("empty");
	image_container.addClass("loading");
	var img = new Image();
	$(img).load(function () {
		$(this).hide();
		image_container.removeClass('loading');
		workingImage = $(this);
		image_container.append(workingImage);
		checkImageSizes();
		workingImage.fadeIn("slow",function() {
			
			// need to update image ids
			tmp_drop_id = image_container.attr('id').replace(new RegExp("drop"), "");
			if(tmp_drop_id==1) {
				image1_id = image_id;
				$('<span id="image1_id" class="hidden imageid">' + image1_id + '</span>').appendTo($('#contain1 p.imagename'));
			} else {
				image2_id = image_id;
				$('<span id="image2_id" class="hidden imageid">' + image2_id + '</span>').appendTo($('#contain2 p.imagename'));
			}
			
			// need to hit the API to update current images
			if($('#compareimages').find('.empty').length==0) {
					apiURL = storefront_api + '/set_selected_compare_images/' + image1_id + '/' + image2_id;
					$.get(apiURL);
			}
			
			checkImageSizes();
			
			// callback if applicable
			if((typeof callback!='undefined')) { callback(); }
		});
	}).attr('src', image_url);
}


/* ------------------------------------
	FUNCTION			hookBlackWhiteToggle
	PURPOSE				Hooks the B&W toggle buttons
------------------------------------ */

function hookBlackWhiteToggle() {
	$('.compare_view_bw a').click(function(e) {
		e.preventDefault();
		tmp_toggle = $(this);
		tmp_compare = $(this).parent().parent().find('.compare_to_bw a');
		tmp_resevoir_id = $(this).parent().parent().parent().attr('id').replace(new RegExp("controls"), "");
		if(tmp_resevoir_id==1) {
			tmp_image_id = image1_id;
			tmp_resevoir_id = 'drop1';
			tmp_controls_id = 'controls1';
		} else {
			tmp_image_id = image2_id;
			tmp_resevoir_id = 'drop2';
			tmp_controls_id = 'controls2';
		}
		if(tmp_image_id!="") {
			if($(this).hasClass('bw')) {
				apiURL = storefront_api + '/get_image_url/' + tmp_image_id + '/low_res/bw';
				$.get(apiURL, function(data){
					$(data).find('Property').each(function() {
						loadCompareImage($('#'+tmp_resevoir_id),$(this).attr('key','image_url').text(),tmp_image_id);
					});
					tmp_toggle.removeClass('bw');
					tmp_toggle.addClass('color');
					tmp_compare.removeClass('bw');
					tmp_compare.addClass('color');
					$('#'+tmp_controls_id).find('input.colorbw').attr('value','bw');
				});
			} else {
				apiURL = storefront_api + '/get_image_url/' + tmp_image_id + '/low_res/color';
				$.get(apiURL, function(data){
					$(data).find('Property').each(function() {
						loadCompareImage($('#'+tmp_resevoir_id),$(this).attr('key','image_url').text(),tmp_image_id);
					});
					tmp_toggle.removeClass('color');
					tmp_toggle.addClass('bw');
					tmp_compare.removeClass('color');
					tmp_compare.addClass('bw');
					$('#'+tmp_controls_id).find('input.colorbw').attr('value','color');
				});
			}
		}
		return false;
	});
}


/* ------------------------------------
	FUNCTION			hookCompareToggle
	PURPOSE				Hooks the Compare to B&W buttons
------------------------------------ */

function hookCompareToggle() {
	$('.compare_to_bw a').click(function(e) {
		e.preventDefault();
		tmp_toggle = $(this);
		tmp_resevoir_id = $(this).parent().parent().parent().attr('id').replace(new RegExp("controls"), "");
		if(tmp_resevoir_id==1) {
			tmp_image_id = image1_id;
			tmp_resevoir_id = 'drop2';				// need to target the opposite resevoir
			tmp_compare_id = 'controls2';			// opposite again
		} else {
			tmp_image_id = image2_id;
			tmp_resevoir_id = 'drop1';				// need to target the opposite resevoir
			tmp_compare_id = 'controls1';			// opposite again
		}
		
		
		if(tmp_image_id!="") {
			if($(this).hasClass('bw')) {
				apiURL = storefront_api + '/get_image_url/' + tmp_image_id + '/low_res/bw';
				$.get(apiURL, function(data) {
					$(data).find('Property').each(function() {
						loadCompareImage($('#'+tmp_resevoir_id),$(this).attr('key','image_url').text(),tmp_image_id,function() {
						});
					});
					// we need to change the classes of the OPPOSITE controls
					$('#' + tmp_compare_id + ' .compare_to_bw a').removeClass('bw');
					$('#' + tmp_compare_id + ' .compare_to_bw a').addClass('color');
					$('#' + tmp_compare_id + ' .compare_view_bw a').removeClass('bw');
					$('#' + tmp_compare_id + ' .compare_view_bw a').addClass('color');
					
					// need to set proper form variables for OTHER resevoir
					$('#' + tmp_compare_id).find('input.colorbw').attr('value','bw');
					$('#' + tmp_compare_id).find('input.imageid').attr('value',tmp_image_id);
				});
			} else {
				apiURL = storefront_api + '/get_image_url/' + tmp_image_id + '/low_res/color';
				$.get(apiURL, function(data) {
					$(data).find('Property').each(function() {
						loadCompareImage($('#'+tmp_resevoir_id),$(this).attr('key','image_url').text(),tmp_image_id,function() {
						});
					});
					// we need to change the classes of the OPPOSITE controls
					$('#' + tmp_compare_id + ' .compare_to_bw a').removeClass('color');
					$('#' + tmp_compare_id + ' .compare_to_bw a').addClass('bw');
					$('#' + tmp_compare_id + ' .compare_view_bw a').removeClass('color');
					$('#' + tmp_compare_id + ' .compare_view_bw a').addClass('bw');
					
					// need to set proper form variables for OTHER resevoir
					$('#' + tmp_compare_id).find('input.colorbw').attr('value','bw');
					$('#' + tmp_compare_id).find('input.imageid').attr('value',tmp_image_id);
				});
			}
			
			// need to set image ids
			if(tmp_resevoir_id=='drop1') {
				image1_id = image2_id;
				$('#contain1 p.imagename').empty().append(image1_id + '<span id="image1_id" class="hidden imageid">' + image1_id + '</span>');
			} else {
				image2_id = image1_id;
				$('#contain2 p.imagename').empty().append(image2_id + '<span id="image2_id" class="hidden imageid">' + image2_id + '</span>');
			}
			
			// need to update favorites_redirect
			$('#favorites_redirect').attr('value','/view_compare_images/index/' + image1_id + '/' + image2_id + '/' + $('#current_group').text());
			
			if(tmp_resevoir_id=='drop2') {
				current_fav_status = $('#favstatus1 a');
			} else {
				current_fav_status = $('#favstatus2 a');
			}
			
			if(current_fav_status.hasClass('on')) {
				targetFavURL = $('#link_to_remove_favorite').text() + active_image_id;
				targetFavClass = 'on';
			} else {
				targetFavURL = $('#link_to_add_favorite').text() + active_image_id;
				targetFavClass = 'off';
			}
			
			// need to apply the URL to both favorite toggles
			$('.compare_fav a').attr('href',targetFavURL);

			// set proper classes
			if(tmp_resevoir_id=='drop1') {
				targetToggle = $('#favstatus1 a');
			} else {
				targetToggle = $('#favstatus2 a');
			}
			
			if(targetToggle.hasClass('on')&&targetFavClass=='off') {
				targetToggle.removeClass('on').addClass('off');
			}
			
			if(targetToggle.hasClass('off')&&targetFavClass=='on') {
				targetToggle.removeClass('off').addClass('on');
			}
			targetToggle.attr('href',targetFavURL);
			
		}
		return false;
	});
}



/* ------------------------------------
	FUNCTION			initOrderPage
	PURPOSE				Initializes the Order Page
------------------------------------ */

function initOrderPage() {
	checkResevoirImageSize();
	
	// Discount modal
	// Hide it initially
	$('#discount_modal').hide();
	// Make it show up when one of the links is clicked
	$('.discount_modal_trigger').click(function(e) {
		e.preventDefault();
		$('#discount_modal').modal();
		return false;
	});	
	// Make it hidden again
	$('.back_to_images').click( function(e){
		$('.modalClose').click();
	});

	// IE takes what is between the <button>***</button> tags
	// to be the value of the element.  Firefox uses the 
	// <button value="***">.  This solves it by using a seperate field
	$('.hookedbutton').click(function(){
		$('#buttondata').attr('value', $(this).attr('data'));
		return true;		
	});

}


/* ------------------------------------
	FUNCTION			checkResevoirImageSize
	PURPOSE				Reusable function to take care of resevoir resizing adjustments
------------------------------------ */

function checkResevoirImageSize() {
	checkImageSizes();
	$(window).resize(function() { checkImageSizes(); });
	$('.droppable img').load(function() { checkImageSizes(); });
}


/* ------------------------------------
	FUNCTION			initCompare
	PURPOSE				Initializes the Compare Page functions
------------------------------------ */

function initCompare() {
	// set variables
	storefront_api = $('#storefront_api').text();
	server_image_path = $('#server_image_path').text();
	thumbWidth = $('#groupimagelist ul li').width();
	if(thumbWidth==null||thumbWidth==0) { thumbWidth = 145; }
	thumbWidth = 145;				// temporarily hard coded, should check
	hiddenArea = $('#groupimagelist').width()-$('#groupimagelist ul').width();
	image1_id = $('#image1_id').text();
	image2_id = $('#image2_id').text();
	droppable_height = $('.droppable').height();
	
	hookGroups( 0 );
	initScrolling();
	hookAltFavToggle();
	hookBlackWhiteToggle();
	hookCompareToggle();
	checkResevoirImageSize();
	checkImageSizes();
	$('.droppable img').load(function() { setTimeout('checkImageSizes()',100); });
	
	// Prevent adding nothing to cart
	$('li.compare_add_cart form').submit(function() {
		if(typeof $(this).find('input.imageid').attr('value') != 'undefined') {
			return true;
		} else {
			return false;
		}
	});
}






//***********************************************************
//***********************************************************
// experiment below

/* ------------------------------------
	FUNCTION			initScrolling
	PURPOSE				Sets various variables for horizontal scroller
------------------------------------ */
function initScrollingPackageContents() {
	// Contents of initScrolling() with compare page's hookDraggables() removed
	//hookDraggables();
	$("#groupimagelist ul").css("left",0);
	currentLeft = 0;
	$('#groupimagelist ul').width((thumbWidth * $('#groupimagelist ul li').size())+thumbWidth);
	if($('#groupimagelist ul').width()==0) { $('#groupimagelist ul').width(thumbWidth); }
	hookRight();
	disableLeft();

	if( multipose ){
		$("#large_scroller_list ul").css("left",0);
		currentLargeLeft = 0;
		$('#large_scroller_list ul').width((largeThumbWidth * $('#large_scroller_list ul li').size())+largeThumbWidth);
		if($('#large_scroller_list ul').width()==0) { $('#large_scroller_list ul').width(largeThumbWidth); }
		hookRightLarge();
		disableLeftLarge();	
	
	}


	hookPackageDraggables();
	$("#packageimagelist ul").css("left",0);
//	packCurrentLeft = 0;
	$('#packageimagelist ul').width((thumbWidth * $('#packageimagelist ul li').size())+thumbWidth);
	if($('#packageimagelist ul').width()==0) { $('#packageimagelist ul').width(thumbWidth); }

if( isScrollerAtLeft('pose') ){
	hookRightPackageContents();
	disableLeftPackageContents();
} else {
	hookRightPackageContents();
	hookLeftPackageContents();
}

}

function isScrollerAtLeft( which_scroller ){
	if( which_scroller == 'pack' ){
		fullListWidth  = $('#packageimagelist ul').width();
		listContainerWidth = $('#packageimagelist').width();
		scrollerCurrentLeft = packCurrentLeft;
	} else if( which_scroller == 'pose' ){
		fullListWidth  = $('#large_scroller_list ul').width();
		listContainerWidth = $('#large_scroller_list').width();
		scrollerCurrentLeft = largeCurrentLeft
	}

	return !( scrollerCurrentLeft>(listContainerWidth-fullListWidth) );
}

/* ------------------------------------
	PURPOSE				Hook the left scroller
------------------------------------ */

function hookLeftLarge() {

	large_left_disabled = false;
	$('#large_left a').removeClass('inactive');
	$('#large_left a').unbind('click');
	$('#large_left a').unbind('mouseup');
	$('#large_left a').unbind('mousedown');
	$('#large_left a').unbind('mouseout');
	
	
	$('#largelefthop').click(function(e) {
		e.preventDefault();
		if(largeCurrentLeft<0) {
			//o = largeCurrentLeft;
			largeCurrentLeft = largeCurrentLeft + ($('#large_scroller_list').width() - (largeThumbWidth));
			//o = o + '|' + largeCurrentLeft;
			//alert(o);
			// check to make sure we don't go too far, and disable the button
			if(largeCurrentLeft>=0) {
				largeCurrentLeft = 1;
				disableLeftLarge();
			}

			// need to enable right button
			if(large_right_disabled) { hookRightLarge(); }

			$('#large_scroller_list ul').animate({ left:largeCurrentLeft }, {
				duration: 1300,
				easing: 'easeInOutQuart'
			});
		}
		return false;
	});
	
	// left scrub -- hooks mousedown to continually slide
	$('#largeleftscrub').mousedown(function() {
		if(large_right_disabled) { hookRightLarge(); }
		largeScrubInterval = setInterval('scrubLarge("left")',5);
	})
	.mouseup(function() {
		clearInterval(largeScrubInterval);
		return false;
	})
	.mouseout(function() {
		clearInterval(largeScrubInterval);
		return false;
	});
	
	$('#large_left').fadeTo(150, 0.99);
}


/* ------------------------------------
	FUNCTION			hookRight
	PURPOSE				Hook the right scroller
------------------------------------ */

function hookRightLarge() {

	if($('#large_scroller_list ul').width()>$('#large_scroller_list').width()){
		large_right_disabled = false;
		$('#large_right a').removeClass('inactive');
		$('#large_right a').unbind('click');
		$('#large_right a').unbind('mouseup');
		$('#large_right a').unbind('mousedown');
		$('#large_right a').unbind('mouseout');

		// right hop -- slide over an entire visible section automatically
		$('#largerighthop').click(function(e) {
			e.preventDefault();

			fullListWidth 			= $('#large_scroller_list ul').width();
			listContainerWidth 		= $('#large_scroller_list').width();

			if(largeCurrentLeft>(listContainerWidth-fullListWidth)) {
				adjustment = listContainerWidth - (largeThumbWidth);
				largeCurrentLeft = largeCurrentLeft - (listContainerWidth - (largeThumbWidth));
				// check to see if we're going to create too much whitespace on the right
				if(largeCurrentLeft<(listContainerWidth-fullListWidth)) {
					largeCurrentLeft = 0-(fullListWidth-listContainerWidth);
					disableRightLarge();
				}
				
				// need to enable left button
				if(large_left_disabled) { hookLeftLarge(); }

				$('#large_scroller_list ul').animate({ left:largeCurrentLeft }, {
					duration: 1300,
					easing: 'easeInOutQuart'
				});
			}
			return false;
		});

		// right scrub -- hooks mousedown to continually slide
		$('#largerightscrub').mousedown(function() {
			if(large_left_disabled) { hookLeftLarge(); }
			largeScrubInterval = setInterval('scrubLarge("right")',5);
		})
		.mouseup(function() {
			clearInterval(largeScrubInterval);
			return false;
		})
		.mouseout(function() {
			clearInterval(largeScrubInterval);
			return false;
		});
	
		$('#large_right').fadeTo(150, 0.99);
	} else {
		disableRightLarge();
	}
}


/* ------------------------------------
	FUNCTION			disableRight
	PURPOSE				Disable right scroller if no more images are available
------------------------------------ */

function disableLeftLarge() {

	$('#large_left a').unbind('click');
	$('#large_left a').click(function() { return false; });
	$('#large_left a').addClass('inactive');
	$('#large_left').fadeTo(150, 0.3);
	large_left_disabled = true;
}


/* ------------------------------------
	FUNCTION			disableRight
	PURPOSE				Disable right scroller if no more images are available
------------------------------------ */

function disableRightLarge() {
	$('#large_right a').unbind('click');
	$('#large_right a').click(function() { return false; });
	$('#large_right a').addClass('inactive');
	$('#large_right').fadeTo(150, 0.3);
	
	large_right_disabled = true;
}

/* ------------------------------------
	FUNCTION			scrub
	PURPOSE				Provides a constant animation for the images
------------------------------------ */

function scrubLarge(direction) {
//newLeft = packCurrentLeft;
	change = 30;
	
	if(direction=='right') {
		fullListWidth 			= $('#large_scroller_list ul').width();
		listContainerWidth 		= $('#large_scroller_list').width();

		if( !isScrollerAtLeft('pose') ) {
			newLeft = largeCurrentLeft-change;
		} else {
			$('#largerightscrub').mouseup();
			disableRightLarge();
		}
	} else {
		if(largeCurrentLeft<0) {
			newLeft = largeCurrentLeft+change;
		} else {
			$('#largeleftscrub').mouseup();
			disableLeftLarge();
		}
	}
	largeCurrentLeft = newLeft;

	$('#large_scroller_list ul').css('left',newLeft);
}




/* ------------------------------------
	FUNCTION			hookLeft
	PURPOSE				Hook the left scroller
------------------------------------ */

function hookLeftPackageContents() {
	pack_left_disabled = false;
	$('#packleft a').removeClass('inactive');
	$('#packleft a').unbind('click');
	$('#packleft a').unbind('mouseup');
	$('#packleft a').unbind('mousedown');
	$('#packleft a').unbind('mouseout');
	
	
	$('#packlefthop').click(function(e) {
		e.preventDefault();
		if(packCurrentLeft<0) {
			packCurrentLeft = packCurrentLeft + ($('#packageimagelist').width() - (thumbWidth));

			// check to make sure we don't go too far, and disable the button
			if(packCurrentLeft>=0) {
				packCurrentLeft = 1;
				disableLeftPackageContents();
			}

			// need to enable right button
			if(pack_right_disabled) { hookRightPackageContents(); }

			$('#packageimagelist ul').animate({ left:packCurrentLeft }, {
				duration: 1300,
				easing: 'easeInOutQuart'
			});
		}
		return false;
	});
	
	// left scrub -- hooks mousedown to continually slide
	$('#packleftscrub').mousedown(function() {
		if(pack_right_disabled) { hookRightPackageContents(); }
		packScrubInterval = setInterval('scrubPack("left")',5);
	})
	.mouseup(function() {
		clearInterval(packScrubInterval);
		return false;
	})
	.mouseout(function() {
		clearInterval(packScrubInterval);
		return false;
	});
	
	$('#packleft').fadeTo(150, 0.99);
}


/* ------------------------------------
	FUNCTION			hookRight
	PURPOSE				Hook the right scroller
------------------------------------ */

function hookRightPackageContents() {
	if($('#packageimagelist ul').width()>$('#packageimagelist').width()){
		pack_right_disabled = false;
		$('#packright a').removeClass('inactive');
		$('#packright a').unbind('click');
		$('#packright a').unbind('mouseup');
		$('#packright a').unbind('mousedown');
		$('#packright a').unbind('mouseout');

		// right hop -- slide over an entire visible section automatically
		$('#packrighthop').click(function(e) {
			e.preventDefault();
			
			fullListWidth 			= $('#packageimagelist ul').width();
			listContainerWidth 		= $('#packageimagelist').width();

			if(packCurrentLeft>(listContainerWidth-fullListWidth)) {
				adjustment = listContainerWidth - (thumbWidth);
				packCurrentLeft = packCurrentLeft - (listContainerWidth - (thumbWidth));

				// check to see if we're going to create too much whitespace on the right
				if(packCurrentLeft<(listContainerWidth-fullListWidth)) {
					packCurrentLeft = 0-(fullListWidth-listContainerWidth);
					disableRightPackageContents();
				}
				
				// need to enable left button
				if(pack_left_disabled) { hookLeftPackageContents(); }
				
				$('#packageimagelist ul').animate({ left:packCurrentLeft }, {
					duration: 1300,
					easing: 'easeInOutQuart'
				});
			}
			return false;
		});

		// right scrub -- hooks mousedown to continually slide
		$('#packrightscrub').mousedown(function() {
			if(pack_left_disabled) { hookLeftPackageContents(); }
			packScrubInterval = setInterval('scrubPack("right")',5);
		})
		.mouseup(function() {
			clearInterval(packScrubInterval);
			return false;
		})
		.mouseout(function() {
			clearInterval(packScrubInterval);
			return false;
		});
	
		$('#packright').fadeTo(150, 0.99);
	} else {
		disableRightPackageContents();
	}
}






function disableLeftPackageContents() {
	$('#packleft a').unbind('click');
	$('#packleft a').click(function() { return false; });
	$('#packleft a').addClass('inactive');
	$('#packleft').fadeTo(150, 0.3);
	pack_left_disabled = true;
}


/* ------------------------------------
	FUNCTION			disableRight
	PURPOSE				Disable right scroller if no more images are available
------------------------------------ */

function disableRightPackageContents() {
	$('#packright a').unbind('click');
	$('#packright a').click(function() { return false; });
	$('#packright a').addClass('inactive');
	$('#packright').fadeTo(150, 0.3);
	
	pack_right_disabled = true;
}




/* ------------------------------------
	FUNCTION			scrub
	PURPOSE				Provides a constant animation for the images
------------------------------------ */
function scrubPack(direction) {
newLeft = packCurrentLeft;
	if(direction=='right') {


		if( !isScrollerAtLeft('pack') ) {
			newLeft = packCurrentLeft-15;
		} else {
			$('#packrightscrub').mouseup();
			disableRightPackageContents();
		}

	} else {
		if(packCurrentLeft<0) {
			newLeft = packCurrentLeft+15;
		} else {
			$('#packleftscrub').mouseup();
			disableLeftPackageContents();
		}
	}
	packCurrentLeft = newLeft;
	$('#packageimagelist ul').css('left',newLeft);
}




/* ------------------------------------
	FUNCTION			checkImageSizesPackages
	PURPOSE				Ensures images in resevoir don't overlap
------------------------------------ */

function checkImageSizesPackages() {
	if($('.packdrop img').length!=0) {
		images_resized = 0;
		//pack_droppable_height = 100;
		$('.packdrop img').each(function() {

			pack_droppable_height = 100;
			//target_width = $(this).parent().width();
			target_width=125;
			//alert(target_width + "|" + pack_droppable_height);
			//if($('#orderimage').length!=0) { 
			//	target_width = $('.packdrop').width();
			//}
			//alert($(this).height() + "|" + $(this).width());
			if(($(this).height()<$(this).width())) {
				// landscape
				$(this).height('auto');
				$(this).css('height','auto');
				$(this).width(target_width);
				if($(this).height()>pack_droppable_height) {
					// the new height exceeds viewable area, need to double back
					$(this).width('auto');
					$(this).css('width','auto');
					$(this).height(pack_droppable_height);
				}
				if($(this).width()>target_width) {
					// the new width exceeds viewable area, need to double back
					$(this).height('auto');
					$(this).css('height','auto');
					$(this).width(target_width);
				}
			} else {
				// portrait or square
				$(this).width('auto');
				$(this).css('width','auto');
				$(this).height(pack_droppable_height);
				if($(this).width()>target_width) {
					// the new width exceeds viewable area, need to double back
					$(this).height('auto');
					$(this).css('height','auto');
					$(this).width(target_width);
				}
				if($(this).height()>pack_droppable_height) {
					// the new height exceeds viewable area, need to double back
					$(this).width('auto');
					$(this).css('width','auto');
					$(this).height(pack_droppable_height);
				}
			}
		
			images_resized++;
			if( images_resized == $('.packdrop img').length ){
				recordLocations('checkimagesizes-1');
			}
		});
		
		// On photo album page, the reservoir:
		$('#packdrop-1 img').each(function() {
			
			target_width = $(this).parent().parent().width();
			
			//alert(target_width);
			//if($('#orderimage').length!=0) { 
			//	target_width = $('.packdrop').width();
			//}
			if(($(this).height()<$(this).width())) {
				// landscape
				$(this).height('auto');
				$(this).css('height','auto');
				$(this).width(target_width);
				if($(this).height()>res_droppable_height) {
					// the new height exceeds viewable area, need to double back
					$(this).width('auto');
					$(this).css('width','auto');
					$(this).height(res_droppable_height);
				}
				if($(this).width()>target_width) {
					// the new width exceeds viewable area, need to double back
					$(this).height('auto');
					$(this).css('height','auto');
					$(this).width(target_width);
				}
			} else {
				// portrait or square
				$(this).width('auto');
				$(this).css('width','auto');
				$(this).height(res_droppable_height);
				if($(this).width()>target_width) {
					// the new width exceeds viewable area, need to double back
					$(this).height('auto');
					$(this).css('height','auto');
					$(this).width(target_width);
				}
				if($(this).height()>res_droppable_height) {
					// the new height exceeds viewable area, need to double back
					$(this).width('auto');
					$(this).css('width','auto');
					$(this).height(res_droppable_height);
				}
			}
		});
	}
	
	
	if( $('.posedrop img').length != 0){
		images_resized = 0;
		$('.posedrop img').each(function() {
			
			//target_width = $(this).parent().parent().parent().width();
			target_width = 295;
			//alert(target_width);

			//alert(target_width);
			//if($('#orderimage').length!=0) { 
			//	target_width = $('.packdrop').width();
			//}
			if(($(this).height()<$(this).width())) {
				// landscape
				$(this).height('auto');
				$(this).css('height','auto');
				$(this).width(target_width);
				if($(this).height()>res_droppable_height) {
					// the new height exceeds viewable area, need to double back
					$(this).width('auto');
					$(this).css('width','auto');
					$(this).height(res_droppable_height);
				}
				if($(this).width()>target_width) {
					// the new width exceeds viewable area, need to double back
					$(this).height('auto');
					$(this).css('height','auto');
					$(this).width(target_width);
				}
			} else {
				// portrait or square
				$(this).width('auto');
				$(this).css('width','auto');
				$(this).height(res_droppable_height);
				if($(this).width()>target_width) {
					// the new width exceeds viewable area, need to double back
					$(this).height('auto');
					$(this).css('height','auto');
					$(this).width(target_width);
				}
				if($(this).height()>res_droppable_height) {
					// the new height exceeds viewable area, need to double back
					$(this).width('auto');
					$(this).css('width','auto');
					$(this).height(res_droppable_height);
				}
			}
			images_resized++;
			if( images_resized == $('.posedrop img').length ){
				recordLocations('checkimagesizes-1');
			}

		});
		
	}

}



/* ------------------------------------
	FUNCTION			loadImage
	PURPOSE				Will load an image into a repository
	VARIABLES			jQuery object		image_container
						string				image_url
------------------------------------ */

function loadCompareImagePackages(image_container,image_url,image_id,callback) {
	image_container.empty();
	//image_container.removeClass("empty");
	//image_container.addClass("loading");
	if( multipose ){
	image_container.parent().parent().addClass('loading');
	}
	
	var img = new Image();
	$(img).load(function () {
		//$(this).hide();
		//image_container.removeClass('loading');
		if( multipose ){
			image_container.parent().parent().removeClass('loading');
		}
		$(this).addClass('ui-draggable');
		if( multipose ){
			$(this).addClass('largedragsource');
		}
		
		workingImage = $(this);
		workingImage.attr('title', image_id);

		if( multipose ){
			this_id = image_container.attr("id").replace('posedrop','');
			image_container.append('<span class="hidden source_image_id" id="image' + this_id + '_id">' + image_id + '</span>');
		} else if( photo_album ){
			image_container.append('<span class="hidden source_image_id" id="image1_id">' + image_id + '</span>');
		}
		image_container.append(workingImage);
		
		//checkImageSizes();
		//workingImage.fadeIn("slow",function() {
			
			// need to update image ids
			//tmp_drop_id = image_container.attr('id').replace(new RegExp("drop"), "");
			//if(tmp_drop_id==1) {
				//image1_id = image_id;
				//$('<span id="image1_id" class="hidden imageid">' + image1_id + '</span>').appendTo($('#contain1 p.imagename'));
			//} else {
			//	image2_id = image_id;
			//	$('<span id="image2_id" class="hidden imageid">' + image2_id + '</span>').appendTo($('#contain2 p.imagename'));
			//}
			
			// need to hit the API to update current images
			//if($('#compareimages').find('.empty').length==0) {
			//		apiURL = storefront_api + '/set_selected_compare_images/' + image1_id + '/' + image2_id;
			//		$.get(apiURL);
			//}
			
			checkImageSizesPackages();
			hookPackageDraggables();
			
			// callback if applicable
			//if((typeof callback!='undefined')) { callback(); }
		//});
	}).attr('src', image_url);
}



/* ------------------------------------
	FUNCTION			hookBlackWhiteTogglePackages
	PURPOSE				Makes the 'View in BW' work
------------------------------------ */

function hookBlackWhiteTogglePackages() {

	if( multipose ){

			$('a.togglebtn').click(function(e) {
			
				e.preventDefault();

				this_id = $(this).attr('id').replace("view","");
				tmp_image_id = $('#image' + this_id + '_id').text();
				current_tone  =$('#reservoirtone' + this_id).text();
				if( current_tone == "color"){
					new_tone = "bw";
				} else if( current_tone == "bw" ){
					new_tone = "color";
				}

				
				if( tmp_image_id!="") {

					//alert(storefront_api + '/mp_overwrite_pose/' + package_id + '/' + tmp_image_id + '/' + current_tone + '/' + tmp_image_id + '/' + new_tone);
					// Switch existing poses to this new tone
					if( !bw_color_count_as_1 ){
						$.get(storefront_api + '/mp_overwrite_pose/' + package_id + '/' + tmp_image_id + '/' + current_tone + '/' + tmp_image_id + '/' + new_tone, function(data){
						
							refreshPackageContents();
						 
						});
					}
									
					
					//if($(this).hasClass('bwtoggle')) {
					if( current_tone == "color" ){
						// Clicked 'View In BW'

						$(this).removeClass('bwtoggle');
						$(this).addClass('colortoggle');

						apiURL = storefront_api + '/get_image_url/' + tmp_image_id + '/low_res/bw';
						$.get(apiURL, function(data){
								$(data).find('Property').each(function() {
									loadCompareImagePackages($('#posedrop' + this_id),$(this).attr('key','image_url').text(),tmp_image_id);					
								});
							$('#reservoirtone' + this_id).text('bw');
						});
				 
					} else if( current_tone == "bw" ){
						// Clicked 'View In Color'

						$(this).removeClass('colortoggle');
						$(this).addClass('bwtoggle');
					
						apiURL = storefront_api + '/get_image_url/' + tmp_image_id + '/low_res/color';
						$.get(apiURL, function(data){
	
							$(data).find('Property').each(function() {
								loadCompareImagePackages($('#posedrop' + this_id),$(this).attr('key','image_url').text(),tmp_image_id);
							});
					
					
							$('#reservoirtone' + this_id).text('color');
						});
					}// end --has class 'bw'
				} // end -- image!=""
			return false;
			});
		
		
	} else if( photo_album ){
	
		$('.compare_view_bw a').click(function(e) {
			e.preventDefault();
			tmp_image_id = $('#image1_id').html();
		
			if( tmp_image_id!="") {
			
				if($(this).hasClass('bw')) {
					// Clicked 'View In BW'
					
					$(this).removeClass('bw');
					$(this).addClass('color');

					apiURL = storefront_api + '/get_image_url/' + tmp_image_id + '/low_res/bw';
					$.get(apiURL, function(data){
							$(data).find('Property').each(function() {
								loadCompareImagePackages($('#packdrop-1'),$(this).attr('key','image_url').text(),tmp_image_id);					
							});
						$('#reservoirtone').text('bw');
					});
				 
				} else {
					// Clicked 'View In Color'

					$(this).removeClass('color');
					$(this).addClass('bw');
					
					apiURL = storefront_api + '/get_image_url/' + tmp_image_id + '/low_res/color';
					$.get(apiURL, function(data){

						$(data).find('Property').each(function() {
							loadCompareImagePackages($('#packdrop-1'),$(this).attr('key','image_url').text(),tmp_image_id);
						});
					
					
						$('#reservoirtone').text('color');
					});
				}// end --has class 'bw'
			} // end -- image!=""
			return false;
		});
		
	} // end multipose / photo_album page
}

/* ------------------------------------
	FUNCTION			recordLocations
	PURPOSE				Records initial placement of droppable areas
------------------------------------ */
function recordLocations( fromwhere){
failed = false;
//do{
				pose_offsets = new Array();
				pose_lefts = new Array();
				pose_tops = new Array();
				pose_widths = new Array();
				pose_heights = new Array();
				pose_bottoms = new Array();
				pose_rights = new Array();
				
				ct = 0;
					o = "";
				// Record coordinates of all dropzones
				$('.posedrop').each(function(){
													
					//offsets[ct] = $('#packdrop' + ct).offset();
					offset =  $('#posedrop' + ct).offset();
					pose_lefts[ct] = offset.left; 
					pose_tops[ct] = offset.top;
					pose_widths[ct] = $('#posedrop' + ct).width();
					pose_heights[ct] = $('#posedrop' + ct).height();
	
					pose_bottoms[ct] = pose_tops[ct] + pose_heights[ct];
					pose_rights[ct] = pose_lefts[ct] + pose_widths[ct]; 

if( pose_lefts[ct] == pose_rights[ct] ){ failed = true; }
if( pose_tops[ct] == pose_bottoms[ct] ){ failed = true; }
if( pose_rights[ct] - pose_lefts[ct] > 1000 ){ failed = true; }
					o = o + pose_lefts[ct] + ":" + pose_rights[ct] + "||" + pose_tops[ct] + ":" + pose_bottoms[ct] + "\n";
					ct++;
				});
				//alert(o);
				
				

				print_offsets = new Array();
				print_lefts = new Array();
				print_tops = new Array();
				print_widths = new Array();
				print_heights = new Array();
				print_bottoms = new Array();
				print_rights = new Array();
				
				if( multipose ){
					ct = 0; 
				} else if( photo_album ){
					ct = -1;
				}
				o = o + "\n\n";
				// Record coordinates of all dropzones
				$('.packdrop').each(function(){
					
					//offsets[ct] = $('#packdrop' + ct).offset();
					offset =  $('#packdrop' + ct).offset();
					print_lefts[ct] = offset.left; 
					print_tops[ct] = offset.top;
					print_widths[ct] = $('#packdrop' + ct).width();
					print_heights[ct] = $('#packdrop' + ct).height();
					print_bottoms[ct] = print_tops[ct] + print_heights[ct];
					print_rights[ct] = print_lefts[ct] + print_widths[ct]; 
o = o + print_lefts[ct] + ":" + print_rights[ct] + "||" + print_tops[ct] + ":" + print_bottoms[ct] + "\n";

if( print_lefts[ct] == print_rights[ct] ){ failed = true; }
if( print_tops[ct] == print_bottoms[ct] ){ failed = true; }
if( print_rights[ct] - print_lefts[ct] > 1000 ){ failed = true; }

					ct++;
				});
				//if( fromwhere != 'checkimagesizes-2' )
				//alert(fromwhere + '\n\n' + o + '\n\n' + failed);

if( failed ){
	//alert('failed - ' + fromwhere);
	setTimeout('recordLocations("failed-before")',100);
}

}

function dragEnabled( val ){
//$('.comparesource').draggable('disable');
loading_compare_image = !val;
}


function isDragEnabled(){
return !loading_compare_image;
}

function hookPackageDraggables() {
recordLocations('hookPackageDraggables()');


	if( multipose ){
		// MP Page
		// Drag from Group Sccroller to Pose Scroller
		$('.comparesource').draggable({
			zIndex:1000,
			helper:'clone',
			appendTo:'#clonehelper',
			scroll:false,
			containment:'#comparecontainer',
			opacity:0.75,
			start: function() { 


					$('#groupimages img.comparesource').draggable( "disable" );

					error_val = -1;
					lowest = 0;
					
					//$('.comparesource').addClass('.comparesource-disabled').removeClass('.comparesource');
					//$().unbind('draggable');
					
					//$('img.comparesource').draggable( "disable" );
					//$(this).draggable('disable');
					//$(this).draggable('disable');
					//$('#packageimages').fadeTo(10, 0.3);
					//if( isDraggingEnabled() ){
					//if( isDragEnabled() ){
						active_image_id = $(this).parent().find("span.source_image_id").text();
					//} 
			
					ct = pose_tops.length;
						offset =  $('#posedrop0').offset();
						new_left = offset.left; 
						new_top = offset.top;
						
						old_left = pose_lefts[0];
						old_top = pose_tops[0];
						
						change_left = new_left - old_left;
						change_top = new_top - old_top;
						
						for( i = 0; i < ct; i++ ){
							pose_tops[i] += change_top;
							pose_bottoms[i] += change_top;
							pose_lefts[i] += change_left;
							pose_rights[i] += change_left;
						}
	
	 
					$().mousemove(function(e){
		      			$('#clonehelper img').css('left', e.pageX - ($('#clonehelper img').width() / 2));
		      			$('#clonehelper img').css('top', e.pageY - ($('#clonehelper img').height() / 2));
		   			});	
					
			},
			drag: function(e) {
			
				helperright = helperleft = e.pageX;
				helpertop = helperbottom = e.pageY;
	
				target = error_val;
	

				// Loop through all droppable areas and find which ones we're touching
				for( i = 0; i < ct && target == error_val; i++){
	
						if( helperleft > pose_lefts[i] && helperright < pose_rights[i] &&
						helpertop > pose_tops[i] && helperbottom < pose_bottoms[i]){
								target = i
						} 
				
				}

				// Make the correct image transparent
				for( i = lowest; i < ct; i++){	
					if( i == target ){
						$('#posedrop' + i).addClass('droppable-hover');
					} else {
						$('#posedrop' + i).removeClass('droppable-hover');
					}
				}

			},
			stop: function(e) {

				//$('#packageimages').fadeTo(10, 1);
				//$('.comparesource').draggable('disable');
				if( target != error_val) {
					//if( isDraggingEnabled() ){
						active_drop = $('#posedrop' + target);
					//}
					
					// load the new image
					//if(loading_compare_image==false){
					//if( isDragEnabled() ){
						//draggingEnabled( false );
						//dragEnabled( false );

						helper = $('#clonehelper img');
						//disableDrag();
						active_drop.parent().find('.imagename').text(helper.attr('alt'));

						old_image_id = $('#image' + target + '_id').text();
						old_image_tone = $('#reservoirtone' + target).text();
						// When it is dragged in, it's color by default
						active_image_tone = "color";

						// See if this pose is already in the pose scroller
						already_selected_poses = getScrollerContentsArray( 'pose' );
						if( bw_color_count_as_1 ){
							pose_ident = active_image_id;
						} else {
							pose_ident = active_image_id + "|*|" + active_image_tone;
						}
						this_already_selected = false;
						for( i = 0; i < already_selected_poses.length && !this_already_selected; i++){
							if( already_selected_poses[i] == pose_ident ){
								this_already_selected = true;
							}
						}
						
						if( this_already_selected ){
							alert($('#pose_already_used').html());
							$('#groupimages img.comparesource').draggable( "enable" );
						} else {

						
							if( bw_color_count_as_1 ){
								pose_ident = old_image_id;
							} else {
								pose_ident = old_image_id + "|*|" + old_image_tone;
							}

							// See if the pose being overwritten has been used
							has_been_used = false;
							used_poses = getScrollerContentsArray( 'pack' );
							for( i = 0; i < used_poses.length && !has_been_used; i++){
								if( used_poses[i] == pose_ident ){
									has_been_used = true;
								}
							}


							refresh_package_contents = false;
							ok_to_proceed = true;

							if( old_image_id != "" && has_been_used ){
								ok_to_proceed = confirm("This slot already has an image in it.  By dropping another image into this slot, all prints of the old image will be replaced with the new image");

								if( ok_to_proceed ){
									refresh_package_contents = true;
									$.get( storefront_api + "/mp_overwrite_pose/" + package_id + "/" + old_image_id + "/" + old_image_tone + "/" + active_image_id + "/" + active_image_tone , function(data){});
								}
							
							}
						
							for( i = lowest; i < ct; i++){	
								$('#posedrop' + i).removeClass('droppable-hover');
							}
						
							
							if( ok_to_proceed ){
								storefront_api = $('#storefront_api').text();
								tone = "color";	
		
								// Update the buttons, because we're loading a color image
								$('#view' + target).removeClass('colortoggle');
								$('#view' + target).addClass('bwtoggle');						
								$('#reservoirtone' + target).text('color');
							
								// $(this).css('backgroundImage','none');
								active_drop.parent().parent().addClass("loading");
								active_drop.height(pack_droppable_height);
								active_drop.empty();
								active_drop.removeClass("empty");
								
								/*
								fullListWidth 			= $('#large_scroller_list ul').width();
								listContainerWidth 		= $('#large_scroller_list').width();
								oldCurrentLeft = largeCurrentLeft;

								container_middle = (-1 * largeCurrentLeft) + (listContainerWidth  / 2);
								
								active_drop_left = (active_drop.offset().left - $('#large_scroller_list ul').offset().left )  + largeCurrentLeft;
								active_drop_middle = (active_drop_left + (active_drop.width() / 2) ); 
								scrollAmt = container_middle - active_drop_middle ;
								largeCurrentLeft = largeCurrentLeft - scrollAmt;
								
								alert(
								"Fulllistwidth:" + fullListWidth + 
								"\n\nContainerWidth:" + listContainerWidth + 
								
								"\nLargeCurrentLeft:" + oldCurrentLeft +  
								"\nContainerMid:" + container_middle + 
								
								"\n\nActiveDropLeft:" + active_drop_left + 
								"\nActiveDropMid:" + active_drop_middle +
								
								"\n\nScrollAmt:" + scrollAmt + 
								"\nCurLeft:" + oldCurrentLeft + 
								"\nNuCurLeft:" + largeCurrentLeft  ); 

								$('#large_scroller_list ul').animate({ left:largeCurrentLeft }, {
									duration: 1000,
									easing: 'easeInOutQuart'
								});*/

								
															
								var img = new Image();
								$(img).load(function () {
									
		
									$('view' + target).addClass('colortoggle');
									$('view' + target).removeClass('bwtoggle');
									$('reservoirtone' + target).text('color');
	

									
									$(this).hide();
									active_drop.parent().parent().removeClass('loading');
									$(this).attr('style', 'float: center; text-align: center');
									workingImage = $(this);
									//workingImage.attr('title', active_image_id );
	
									workingImage.addClass('largedragsource');
									active_drop.append('<span class="hidden source_image_id" id="image' + target + '_id">' + active_image_id + '</span>');
									active_drop.append(workingImage);
									//tone = active_drop.
									//active_drop.append("</center>");
		
									$('#reservoirtone' + target).text('color');
									//alert(active_drop.html());
									//active_drop.addClass('comparesource');
									checkImageSizesPackages();
									hookPackageDraggables();
		
	
								
								
								
									//workingImage.fadeIn("slow");
									workingImage.show("slow");
									//workingImage.
		
									// Update API to track which images are added
									active_drop_id = active_drop.attr('id').replace(new RegExp("drop"), "");
									/* if(active_drop_id==1) {
									image1_id = active_image_id;
									$('<span id="image1_id" class="hidden imageid">' + image1_id + '</span>').appendTo($('#contain1 p.imagename'));
									} else {
									image2_id = active_image_id;
									$('<span id="image2_id" class="hidden imageid">' + image2_id + '</span>').appendTo($('#contain2 p.imagename'));
									} */
			
									/*
									if($('#compareimages').find('.empty').length==0) {
									apiURL = storefront_api + '/set_selected_compare_images/' + image1_id + '/' + image2_id;
									$.get(apiURL, function() {
										enableDrag();
									});
									}
									*/
								
									// Update the favorites redirect variable
									/*
									if(image1_id=="") { image1_id_tmp = "NULL"; } else { image1_id_tmp = image1_id; }
									if(image2_id=="") { image2_id_tmp = "NULL"; } else { image2_id_tmp = image2_id; }
									$('#favorites_redirect').attr('value','/view_compare_images/index/' + image1_id_tmp + '/' + image2_id_tmp + '/' + $('#current_group').text());
									*/
									updateMultiposeMessages();
									if( refresh_package_contents ){
										refreshPackageContents();
									}
									//checkImageSizes();
									//dragEnabled( true );
									$('#groupimages img.comparesource').draggable( "enable" );
									// Stop thievery
									stopThievery();
									//alert('enable');
									//$('.comparesource').draggable("enable");
								
								
								}).attr('src', server_image_path + '/low_res/' + active_image_id);
							
							} else { $('#groupimages img.comparesource').draggable( "enable" );	 }  // end -- user OKed the overwrite--

						}  // end -- pose hasn't been used				
				
				} // end --target != error_val);

				$('#groupimages img.comparesource').draggable( "enable" );
				
				for( i = 0; i < $('.posedrop').length; i++){	
					$('#posedrop' + i).removeClass('droppable-hover');
				}
			} // end stop()
		});
		
		
		
		// Large ScrollBar
		// Drag from Large Scrollbar to Package Scrollbar
		$('.posedrop img.largedragsource').draggable({
		zIndex:500,
		helper:'clone',
		appendTo:'#clonehelper',
		scroll:false,
		containment:'body',
		opacity:0.75,
		start: function(e) {
			$('#clonehelper img').css('left', e.pageX - ($('#clonehelper img').width() / 2));
	      	$('#clonehelper img').css('top', e.pageY - ($('#clonehelper img').height() / 2));
			$('.posedrop img.largedragsource').draggable( "disable" );
			
				active_image_id = $(this).parent().find("span.source_image_id").text();
				drag_source_id = $(this).parent().attr('id').replace('posedrop','');
				
				$('#clonehelper img').width( 75 );
				$('#clonehelper img').height('auto');
				error_val = -1;
				lowest = 0;
				 
				
					ct = print_tops.length;
						offset =  $('#packdrop0').offset();
						
						new_left = offset.left; 
						new_top = offset.top;
						
						old_left = print_lefts[0];
						old_top = print_tops[0];
						
						change_left = new_left - old_left;
						change_top = new_top - old_top;
						
						for( i = 0; i < ct; i++ ){
							print_tops[i] += change_top;
							print_bottoms[i] += change_top;
							print_lefts[i] += change_left;
							print_rights[i] += change_left;
						}
		
	
				
				$().mousemove(function(e){
	      			$('#clonehelper img').css('left', e.pageX - ($('#clonehelper img').width() / 2));
	      			$('#clonehelper img').css('top', e.pageY - ($('#clonehelper img').height() / 2));
	      			
	   			});
						

		},
		drag: function(e) {
				
				helperright = helperleft = e.pageX;
				helpertop = helperbottom = e.pageY;


				target = error_val;
	
				// Loop through all droppable areas and find which ones we're touching
				for( i = lowest; (i < ct) && (target == error_val); i++){
	
					// If we're in the same horizontal row
					if( helperbottom > print_tops[i] && helpertop < print_bottoms[i] &&
						helperleft > print_lefts[i] && helperright < print_rights[i] ){
							target = i;
						}	
				}				
		
				for( i = lowest; i < ct; i++){	
					if( i == target ){
						$('#packdrop' + i).addClass('droppable-hover');
					} else {
						$('#packdrop' + i).removeClass('droppable-hover');
					}
				}			
		},
		stop: function() {

			for( i = lowest; i < ct; i++){	
					$('#packdrop' + i).removeClass('droppable-hover');
			}

			if( target != error_val) {
				active_drop = $('#packdrop' + target);
				active_drop.parent().parent().addClass('loading');
				// load the new image
				//if(loading_compare_image==false)
				//if( isDragEnabled() ){
					//draggingEnabled( false );
					//loading_compare_image = true;
					//drag_in_progress = true;
					helper = $('#clonehelper img');
					//disableDrag();
					active_drop.parent().find('.imagename').text(helper.attr('alt'));

					// Save the information before we empty the div
					print_id = $('#slot_id_' + target).text();
					size_desc = $('#size_' + target).text();

					tone = $('#reservoirtone' + drag_source_id).text();
					storefront_api = $('#storefront_api').text();
					image_id = active_image_id;

					$.get( storefront_api + "/mp_add_pose_to_package/" + package_id + "/" + print_id + "/" + tone + "/" + image_id , function(data){
						// Format: success?|num_slots_used|num_poses_used
						tmp_data = data.split("|");
						success = tmp_data[0];
						$('#pagesused').text(tmp_data[1]);
						$('#posesused').text(tmp_data[2]);
						updateMultiposeMessages();
						package_scroller_has_changed = true;
					
					
			
						if( success == '0' ){
							active_drop.parent().parent().removeClass('loading');
							alert(pose_limit_message);
						} else {

					
							active_drop.height(pack_droppable_height);
							active_drop.empty();
							//active_drop.parent().parent().addClass('loading');
							active_drop.removeClass("empty");
					
							// $(this).css('backgroundImage','none');
							//active_drop.addClass("loading");
					
					
							$('#tempimageholder').text('');
					


							// Get the url of the image to load
							$.get( storefront_api + "/get_image_url/"  + active_image_id + "/low_res/" + tone, function(data){

								image_url =  ($(data).find('Property').attr('key', 'image_url').text());
					
					
								var img = new Image();
								$(img).load(function () {
									$(this).hide();
									active_drop.parent().parent().removeClass('loading');
									$(this).attr('style', 'float: center; text-align: center');
									workingImage = $(this);

									//active_drop.append(workingImage);
									//active_drop.append("<br>8x10");

						
									//active_drop.append("<center>");
									active_drop.append('<span class="hidden" id="pack_image_id_' + target + '">' + active_image_id + '</span>');
									active_drop.append('<span class="hidden" id="slot_id_' + target + '">' + print_id + '</span>');
									active_drop.append(workingImage);
									active_drop.append('<br><span id="size_' + target + '">' + size_desc + '</span>');
									//active_drop.append("</center>");
						
									checkImageSizesPackages();
									hookPackageDraggables();
						
									
									workingImage.fadeIn("slow");

									// Update API to track which images are added
									active_drop_id = active_drop.attr('id').replace(new RegExp("drop"), "");

									$('.posedrop img.largedragsource').draggable( "enable" );

									// Stop thievery
									stopThievery();
						
								}).attr('src', image_url);

					
							}); // End -- get image url --
						}// End --we can add--
					});	// End --ajax--can we add?
					//loading_compare_image = false;
					//drag_in_progress = false;
				//}
				
			} else { $('.posedrop img.largedragsource').draggable( "enable" ); }
			
		}
	});
		
		

	} else {
	// Photo album page


	$('.comparesource').draggable({
		zIndex:1000,
		helper:'clone',
		appendTo:'#clonehelper',
		scroll:false,
		containment:'#comparecontainer',
		opacity:0.75,
		start: function() { 
			$('.compareinner .comparesource').draggable( "disable" );
			error_val = -2;
			lowest = -1;
			active_image_id = $(this).parent().find("span.source_image_id").text();
				
			// Record coordinates of all dropzones
			//ct = print_tops.length - 1;
			ct = print_tops.length;
			offset =  $('#packdrop0').offset();
						
			new_left = offset.left; 
			new_top = offset.top;			
			old_left = print_lefts[0];
			old_top = print_tops[0];
			change_left = new_left - old_left;
			change_top = new_top - old_top;
						
			for( i = 0; i < ct; i++ ){
				print_tops[i] += change_top;
				print_bottoms[i] += change_top;
				print_lefts[i] += change_left;
				print_rights[i] += change_left;
			}
			
						
			$().mousemove(function(e){
      			$('#clonehelper img').css('left', e.pageX - ($('#clonehelper img').width() / 2));
      			$('#clonehelper img').css('top', e.pageY - ($('#clonehelper img').height() / 2));
   			});
			
			
		},
		drag: function(e) {

			target = error_val;

			// Loop through all droppable areas and find which ones we're touching
			for( i = lowest; i < ct && target==error_val; i++){
	
				if( e.pageY > print_tops[i] && e.pageY  < print_bottoms[i] &&
					e.pageX > print_lefts[i] && e.pageX < print_rights[i] ){
							target = i;
				}

			}
	
			// Make the correct image transparent
			for( i = lowest; i < ct; i++){	
				if( i == target ){
					$('#packdrop' + i).addClass('droppable-hover');
				} else {
					$('#packdrop' + i).removeClass('droppable-hover');
				}
			}
			
		},
		stop: function() {
			for( i = lowest; i < ct; i++){	
					$('#packdrop' + i).removeClass('droppable-hover');
			}

			if( target != error_val) {
				active_drop = $('#packdrop' + target);
				

				helper = $('#clonehelper img');
				active_drop.parent().find('.imagename').text(helper.attr('alt'));

					// We are dropping to the reservoir
				if( target == -1 ){

					storefront_api = $('#storefront_api').text();
					tone = "color";	

					// we'are always loading the color version, take out any bw classes
					active_drop.parent().parent().find('li a.color').each(function() {
						$(this).removeClass('color');
						$(this).addClass('bw');
					});
					
					// $(this).css('backgroundImage','none');
					active_drop.parent().parent().addClass("loading");
					active_drop.height(pack_droppable_height);
					active_drop.empty();
					active_drop.removeClass("empty");
													
					var img = new Image();
					$(img).load(function () {
								
						$(this).hide();
						active_drop.parent().parent().removeClass('loading');
						$(this).attr('style', 'float: center; text-align: center');
						workingImage = $(this);

						active_drop.append('<span class="hidden source_image_id" id="image1_id">' + active_image_id + '</span>');							active_drop.append(workingImage);

						$('#reservoirtone').text('color');

						hookPackageDraggables();
						checkImageSizesPackages();
						workingImage.fadeIn("slow");

						// Update API to track which images are added
						active_drop_id = active_drop.attr('id').replace(new RegExp("drop"), "");
						
						$('.compareinner .comparesource').draggable( "enable" );
						// Stop thievery
						stopThievery();
						
					}).attr('src', server_image_path + '/low_res/' + active_image_id);
						
				} else {
				// We aren't dropping into the reservoir
				
					// Save the information before we empty the div
					print_id = $('#slot_id_' + target).text();
					size_desc = $('#size_' + target).text();
	
					storefront_api = $('#storefront_api').text();
					tone = "color";
					image_id = active_image_id;	
							
					$.get( storefront_api + "/mp_add_pose_to_package/" + package_id + "/" + print_id + "/" + tone + "/" + image_id , function(data){
							
						// Format: success?|num_slots_used|num_poses_used
						tmp_data = data.split("|");
						success = tmp_data[0];
						$('#pagesused').text(tmp_data[1]);
						$('#posesused').text(tmp_data[2]);
						updateMultiposeMessages();
	
						if( success == '0' ){
							alert(pose_limit_message);
							$('img.comparesource').draggable( "enable" );
						} else {
							active_drop.parent().parent().addClass("loading");
							active_drop.height(pack_droppable_height);
							active_drop.empty();
							active_drop.removeClass("empty");

							var img = new Image();
							$(img).load(function () {
											
								$(this).hide();
								$(this).attr('title', active_image_id );
								
								active_drop.parent().parent().removeClass('loading');
								$(this).attr('style', 'float: center; text-align: center');
								workingImage = $(this);
							
								active_drop.append('<span class="hidden" id="slot_id_' + target + '">' + print_id + '</span>');
								active_drop.append(workingImage);
								active_drop.append('<br><span id="size_' + target + '">' + size_desc + '</span>');
	
								checkImageSizesPackages();						
								workingImage.fadeIn("slow");
	
								// Update API to track which images are added
								active_drop_id = active_drop.attr('id').replace(new RegExp("drop"), "");
								// Stop thievery
								$('.compareinner .comparesource').draggable( "enable" );
								stopThievery();
							
							}).attr('src', server_image_path + '/low_res/' + active_image_id);
							
						} // end --we can add--
						
					}); // end --see if we can add
					
				} // End -- dropping into reservoir? --
			
			} else { $('.compareinner .comparesource').draggable( "enable" ); } // end -- target != errorval --
		} // end stop()
	});
	
	
	
	
	
	
	
		// Resevoir
		$('#packdrop-1 img').draggable({
		zIndex:500,
		helper:'clone',
		appendTo:'#clonehelper',
		scroll:false,
		containment:'body',
		opacity:0.75,
		start: function() { 
			$('#clonehelper img').width( 75 );
			$('#clonehelper img').height('auto');
			$('#packdrop-1 img').draggable( "disable" );
			error_val = -1;
			lowest = 0;

			active_image_id = $(this).parent().find("span.source_image_id").text(); 
	
			// Record coordinates of all dropzones
			ct = print_tops.length;
			offset =  $('#packdrop0').offset();
						
			new_left = offset.left; 
			new_top = offset.top;			
			old_left = print_lefts[0];
			old_top = print_tops[0];
			change_left = new_left - old_left;
			change_top = new_top - old_top;
						
			for( i = 0; i < ct; i++ ){
				print_tops[i] += change_top;
				print_bottoms[i] += change_top;
				print_lefts[i] += change_left;
				print_rights[i] += change_left;
			}			
			
			$().mousemove(function(e){
      			$('#clonehelper img').css('left', e.pageX - ($('#clonehelper img').width() / 2));
      			$('#clonehelper img').css('top', e.pageY - ($('#clonehelper img').height() / 2));
      			
   			});			

			},
		drag: function(e) {

			target = error_val;


			// Loop through all droppable areas and find which ones we're touching
			for( i = lowest; i < ct && target==error_val; i++){
	
				if( e.pageY > print_tops[i] && e.pageY  < print_bottoms[i] &&
					e.pageX > print_lefts[i] && e.pageX < print_rights[i] ){
							target = i;
				}

			}			
//	window.status=target;
//window.status = print_tops[5] + "|" + print_rights[5] + "|" + print_bottoms[5] + "|" + print_lefts[5] + " -- " + e.pageX + ", " + e.pageY + " -- " + target;
			for( i = lowest; i < ct; i++){	
				if( i == target ){
					$('#packdrop' + i).addClass('droppable-hover');
				} else {
					$('#packdrop' + i).removeClass('droppable-hover');
				}
			}
			
		},
		stop: function() {
		
			for( i = lowest; i < ct; i++){	
					$('#packdrop' + i).removeClass('droppable-hover');
			}

			if( target != error_val) {
				active_drop = $('#packdrop' + target);
				helper = $('#clonehelper img');
				active_drop.parent().find('.imagename').text(helper.attr('alt'));

				// Save the information before we empty the div
				print_id = $('#slot_id_' + target).text();
				size_desc = $('#size_' + target).text();

				tone = $('#reservoirtone').text();
				storefront_api = $('#storefront_api').text();
				image_id = active_image_id;	
				$.get( storefront_api + "/mp_add_pose_to_package/" + package_id + "/" + print_id + "/" + tone + "/" + image_id , function(data){
					// Format: success?|num_slots_used|num_poses_used
					tmp_data = data.split("|");
					success = tmp_data[0];
					$('#pagesused').text(tmp_data[1]);
					$('#posesused').text(tmp_data[2]);
					updateMultiposeMessages();

					if( success == '0' ){
						alert(pose_limit_message);
					} else {
						active_drop.height(pack_droppable_height);
						active_drop.empty();
						active_drop.removeClass("empty");
						active_drop.parent().parent().addClass("loading");
					
						$('#tempimageholder').text('');

						// Get the url of the image to load
						$.get( storefront_api + "/get_image_url/"  + active_image_id + "/low_res/" + tone, function(data){
							image_url =  ($(data).find('Property').attr('key', 'image_url').text());

							var img = new Image();
							$(img).load(function () {
								$(this).hide();
								active_drop.parent().parent().removeClass('loading');
								$(this).attr('style', 'float: center; text-align: center');
								$(this).attr('title', active_image_id );
								workingImage = $(this);
															
								active_drop.append('<span class="hidden" id="slot_id_' + target + '">' + print_id + '</span>');
								active_drop.append(workingImage);
								active_drop.append('<br><span id="size_' + target + '">' + size_desc + '</span>');
						
								hookPackageDraggables();
								checkImageSizesPackages();
								workingImage.fadeIn("slow");

								// Update API to track which images are added
								active_drop_id = active_drop.attr('id').replace(new RegExp("drop"), "");
						
								$('#packdrop-1 img').draggable( "enable" );
								stopThievery();
						
							}).attr('src', image_url);

					
						}); // End -- get image url --
					}// End --we can add--
				});	// End --ajax--can we add?
			} else {$('#packdrop-1 img').draggable( "enable" ); }	// target== errorval
		}
	});
	
	
	} // end photo album page
	
	
	
	

}


/* ------------------------------------
	FUNCTION			hookChangeName
	PURPOSE				Gives the change name link functionality
------------------------------------ */ 	
function hookChangeName(){

	// Hooks the 'change name' button
	$('#mp_change').click(function( e ){
			e.preventDefault();
				$(this).hide();
				$('#mp_name').hide();
				
				$('#mp_input').attr("value", $('#mp_name').text());
				
				$('#mp_input').show();
				$('#mp_cancel').show();
				$('#mp_save').show();
			return false;
		});
		
	// Hooks the 'save' button
	$('#mp_save').click(function( e ){
			e.preventDefault();
				$(this).hide();
				$('#mp_input').hide();
				$('#mp_cancel').hide();

				storefront_api = $('#storefront_api').html();
				package_name = $('#mp_input').attr('value');
				package_name = base64_encode( package_name );

				$.get(storefront_api + "/set_mp_package_name/" + package_id + "/" + package_name ,function(){});

				$('#mp_name').text( $('#mp_input').attr('value') );
				$('#mp_name').show();
				$('#mp_change').show();

			return false;
		});
		
	// Hooks the 'cancel' button
	$('#mp_cancel').click(function( e ){
			e.preventDefault();
				$(this).hide();
				$('#mp_input').hide();
				$('#mp_save').hide();

				$('#mp_name').show();
				$('#mp_change').show();

			return false;
		});		


}

/* ------------------------------------
	FUNCTION			getNumSliderSlotsFilled()
	PURPOSE				Returns the number of slots in the big scroller that are filled
------------------------------------ */
function getNumSliderSlotsFilled(){
	empty_count = 0;
	ct = $('.posedrop').length;
	for( i = 0; i < ct; i++){
		if( $('#image' + i + '_id').text() != "" && $('#image' + i + '_id').text() != "&nbsp;"){
			empty_count++;
		}
	}
	return empty_count;
}

/* ------------------------------------
	FUNCTION			getScrollerContentsArray()
	PURPOSE			Returns an array of the contents of a scroller (either 'pose' or 'package')
------------------------------------ */
function getScrollerContentsArray( which_scroller ){
	ret = new Array();
	ct = 0;
	if( which_scroller == 'pose' ){
		for( i = 0; i < $('.posedrop').length; i++){
			this_pose = $('#image' + i + '_id').text();

			if( this_pose != "" && this_pose != "&nbsp;"){

				if( !bw_color_count_as_1 ){
					this_pose =  this_pose + "|*|" + $('#reservoirtone' + i).text();
				}

				ret[ct] = this_pose;
				ct++;
			}

		}
	} else if( which_scroller == 'pack' ){
		if( package_scroller_has_changed || package_scroller_contents.length == 0 ){
			for( i = 0; i < $('.packdrop').length; i++){
				this_pack = $('#pack_image_id_' + i ).text();
				
				if( this_pack != "" && this_pack != "&nbsp;"){
	
					if( !bw_color_count_as_1 ){
						this_pack = this_pack + "|*|" + $('pack_image_tone_' + i).text();
					}
					
					ret[ct] = this_pack;
					ct++;
				}
			}
		
			package_scroller_has_changed = false;
			package_scroller_contents = ret;
		} else {
			return package_scroller_contents;
		}

	}
	return ret;

}

/* ------------------------------------
	FUNCTION			updateMultiposeMessages
	PURPOSE				Keeps number values of messages up to date
------------------------------------ */
function updateMultiposeMessages( caller ){
	pages_used = $('#pagesused').text();
	pages_total = $('#pagestotal').text();
	
	
	if( multipose ){
		poses_used = getNumSliderSlotsFilled();	// Generated from the scroller
	} else if( photo_album ){
		poses_used = $('#posesused').text();	// According to the API
	}
	
	poses_total = $('#posestotal').text();
	

// Step1
	
	if( poses_used != 1 ){ 
		poses_used_text = "poses";
	} else {
		poses_used_text = "pose";
	}
	
	if( poses_total != 1 ){
		poses_total_text = "poses";
	} else {
		poses_total_text = "pose";
	}
	
	template = $('#step1template').html();
	template = template.replace("%1%", poses_used + " " + poses_used_text);
	template = template.replace("%2%", poses_total + " " + poses_total_text);
	$('#step1message').text( template );
	
	
// Step 2
	if( multipose ){
		word = "print";
	} else if( photo_album ){
		word = "page";
	}
		
	if( pages_used != 1 ){ 
		pages_used_text = word + 's';
	} else {
		pages_used_text = word;
	}
	
	if( pages_total != 1 ){
		pages_total_text = word + 's';
	} else {
		pages_total_text = word;
	}
	
	template = $('#step2template').text();
	template = template.replace("%1%", pages_used + " " + pages_used_text);
	template = template.replace("%2%", pages_total + " " + pages_total_text);
	$('#step2message').text( template );
// End Step 2


	if( (pages_used == pages_total) ){
		//$('#lowerbuttons').show('slow');
		if( !complete_message_has_been_shown ){
			if( caller != 'first_time' ){
				alert($('#complete_message').html());
			}
			complete_message_has_been_shown = true;
		}
	}
}


function base64_encode(input) {
		var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            keyStr.charAt(enc1) + keyStr.charAt(enc2) +
            keyStr.charAt(enc3) + keyStr.charAt(enc4);
        }

        return output;
}

/* ------------------------------------
	FUNCTION			refreshPackageContents
	PURPOSE				Reloads the images in the lower scroller
------------------------------------ */

function refreshPackageContents( ) {

		
		// need to reset the scrolling functionality
		disableLeftPackageContents();
		disableRightPackageContents();
		
		
		$('#packageimagelist ul').fadeOut(500, function() {

			apiURL = storefront_api + '/mp_get_package_contents/' + package_id;
			
			$('#packageimagelist ul').empty();
			$('#packageimagelist div').addClass("loading");

			// MAKE AJAX REQUEST
			$.get(apiURL, function(data){
				$('#packageimagelist div').removeClass("loading");
				lines = data.split('\n');
				to_write = '';
				for( i = 0; i < lines.length; i++){
					if( lines[i] != '' ){
						parts = lines[i].split('|*|');
						slot = parts[0];
						image_url = parts[1];
						size_text = parts[2];
						image_id = parts[3];
						tone = parts[4];
						//slot|*|image_url|*|display_text|*|image_name|*|tone
					
						to_write += '<li><div class="outer"><div class="middle comparemiddle">';
						to_write += '<div style="height: 100px;" class="inner compareinner packdrop" id="packdrop' + i + '">';
to_write += '<span class="hidden" id="pack_image_id_' + i + '">' + image_id + '</span>';
to_write += '<span class="hidden" id="pack_image_tone_' + i + '">' + tone + '</span>';
						to_write += '<span class="hidden" id="slot_id_' + i + '">' + slot + '</span>';
						to_write += '<img style="text-align: center; height: auto; width: 125px;" src="' + image_url + '">';
						to_write += '<br><span id="size_' + i + '">' + size_text + '</span></div></div></div></li>';
					}
				}
				
				$('#packageimagelist ul').append(to_write);
				
			//enableLeftPackageContents();
		//enableRightPackageContents();
				//initScrollingPackageContents();
hookLeftPackageContents();
hookRightPackageContents();
				checkImageSizesPackages();
				
				$("#packageimagelist ul").fadeIn(1000, function(){recordLocations('refresh');});
			});
		});
		


}


// experiment above
//***********************************************************

/* ------------------------------------
	FUNCTION			initMultipose
	PURPOSE				Initializes the Compare Page functions
------------------------------------ */


function initMultipose() {
	// set variables
	if( $('#photoalbumpage').length != 0 ){
		photo_album = true;
		multipose = false;
	} else {
		photo_album = false;
		multipose = true;
	}
	
	if( $('#bw_color_count_as_1').html() == '1' ){
		bw_color_count_as_1 = true;
	} else {
		bw_color_count_as_1 = false;
	}

	if( multipose ){
		res_droppable_height = $('#posedrop0').height();
		res_droppable_height = 250;
		largeThumbWidth = $('#large_scroller_list ul li').width();
		if( largeThumbWidth > 300 ){
			largeThumbWidth = 300;
		}
	} else if( photo_album ){
		res_droppable_height = $('#packdrop-1').height();
	}
	
	storefront_api = $('#storefront_api').text();
	server_image_path = $('#server_image_path').text();
	thumbWidth = $('#groupimagelist ul li').width();
	if(thumbWidth==null||thumbWidth==0) { thumbWidth = 145; }
	thumbWidth = 145;				// temporarily hard coded, should check
	hiddenArea = $('#groupimagelist').width()-$('#groupimagelist ul').width();
	image1_id = $('#image1_id').text();
	image2_id = $('#image2_id').text();
	package_id = $('#package_id').html();
	
	pack_droppable_height = Math.max($('#packdrop0 img').height(), $('#packdrop0').height()) - $('#size_0').height();
	if( pack_droppable_height < 50 ){ pack_droppable_height=100;}
	if( res_droppable_height == 0 ){res_droppable_height = 200; }
	pose_limit_message = "You have already reached the limit of poses (" + $('#posestotal').text() + ") for this package.  Please use the already chosen poses to fill the remaining prints.";

	
	
	$('.cancelpackage').click( function(e){
		return confirm($('#deletemsg').html());;
	});
	
	
	loading_compare_image = false;
	complete_message_has_been_shown = false;
	
	hookGroups( 1 );
	initScrollingPackageContents( );
	hookBlackWhiteTogglePackages();
	checkImageSizesPackages();
	hookChangeName();
	updateMultiposeMessages( 'first_time' );
	checkSidebarHeight();
	
	if( !safari ){
		$.scrollTo( '#multiposepage', 100);
	} else {
		$.scrollTo( '#',0);
	}
	
	getScrollerContentsArray('pack');
	
}



























/* CHECK OUT
************************************************************************** */


/* ------------------------------------
	FUNCTION			initCheckOut
	PURPOSE				Initializes functionality
------------------------------------ */

function initCheckOut() {
	if(ie==false){
		if(!$('#new_shipping_fields').hasClass('force')) {
			$('#new_shipping_fields').hide();
			$('#new_shipping_fields').height(180);
			$('#yes').click();

			// hook the shipping address toggle
			$("input[@type='radio']").change( function() {
				if($('#no').attr('checked')==true) {
					$('#new_shipping_fields').slideDown({
						duration: 800,
						easing: 'easeInOutCirc'
					});
				}
				if($('#yes').attr('checked')==true) {
					$('#new_shipping_fields').slideUp({
						duration: 800,
						easing: 'easeInOutCirc'
					});
				}
			});
		}
	}
	
	if($('#no').attr('checked')==true) { $('#no').click(); }
	
	// if shipping information is the same we need to populate the form
	$('#checkout_form').submit(function() {
		

	$('#place_order button').attr("disabled", "true");
    $('#processing').modal();
    width = 150;
    height = 450;
    $('#processing').parent().height( width );
    $('#processing').parent().width( height );
    $('#processing').parent().css('left', ($(window).width() - width) / 2 );
    $('#processing').parent().css('top', ($(window).height() - height) / 2 );    
    $('#modalContainer a.modalCloseImg').hide();
		
		if($('#yes').attr('checked')==true) {
			$('#ship_firstname').attr('value',$('#bill_firstname').attr('value'));
			$('#ship_lastname').attr('value',$('#bill_lastname').attr('value'));
			$('#ship_address').attr('value',$('#bill_address').attr('value'));
			$('#ship_city').attr('value',$('#bill_city').attr('value'));
			$('#ship_zip').attr('value',$('#bill_zip').attr('value'));
			$('#shipping .geo1 select option:selected').attr('value',$('#billing .geo1 select option:selected').attr('value'));
			$('#shipping .geo2 select option:selected').attr('value',$('#billing .geo2 select option:selected').attr('value'));
		}
	});
	
	// calculate sales tax via AJAX request on keyup
	$('#bill_zip').keyup(function() {
		if((this.value.length==5)&&(/^\d{5}$/.test(this.value))) {
			targetURL = $('#storefront_api').text() + '/get_sales_tax/' + this.value;
			$.get(targetURL, function(data){
				tmp_data = data.split("|");
				//sales_tax = tmp_data[1];
				//final_total = tmp_data[0];
				$('#salestax').text('Sales Tax: $' + tmp_data[1]);
				$('li#salestax').removeClass('hidden');
				$('#final_total').text('Total: $' + tmp_data[0]);
				
			});
		} else {
			$('li#salestax').addClass('hidden');
		}
	});

	//$('#cc1 div select option').click( function() { // Firefox
	//$('#cc1 div select').click( function() { // Firefox IE
	$('#cardtype select[name=card_type]').change( function(){
		if( $(this).val() == "Check"  || $ (this).val() == "--"){
			$('#expire,#cc_a,#cc_b,#cc_note').hide();
		} else {
			$('#expire,#cc_a,#cc_b,#cc_note').show();
		}
	
	});

	
	// force tax calculation if available
	$(document).ready(function() {
		$('#bill_zip').keyup();		
		$('#cardtype select[name=card_type]').change();
	});
}



























/* THIEVERY PREVENTION
************************************************************************** */


/* ------------------------------------
	FUNCTION			stopImageDrag
	PURPOSE				Prevent the browser from allowing user to drag
						images to their destop (or anywhere)
------------------------------------ */

function stopImageDrag() {
	// hook all applicable images
	$('#enlargedImageContainer a img').addClass('nodrag');
	$('#lightbox-image').addClass('nodrag');
	$('.droppable img').addClass('nodrag');
	$('#slideshowinner img').addClass('nodrag');
	$('#eventphoto img').addClass('nodrag');
	$('.thumbcontainer img').addClass('nodrag');
	$('#thumbnailPagination img').addClass('nodrag');
	$('.thumbnail img').addClass('nodrag');
	
	$('a.lightbox').addClass('nodrag');
	
	// prevent functionality
	$('.nodrag').mousedown(function(e){
		e.preventDefault();
	});
}



/* ------------------------------------
	FUNCTION			stopThievery
	PURPOSE				Initializes functionality
------------------------------------ */

function stopThievery() {
	stopImageDrag();
}











function initSequence(){



//return;
	if($('.sequence_page_pair').length!=0) {
		var tallest = 100;
		
		$('.sequence_page_pair').each(function() {
			if($(this).height()>tallest) { tallest = $(this).height(); }
		});
		
		
		$('.sequence_page_pair').each(function() {
			$(this).height(tallest);
		});
	}
	
	/*
	
		$('.sequence_page_pair').each(function() {
			highest_top = 0;
			o = '';
			prev_top = 0;
			
			$(this).find('.sequence_page input[type=text]').each( function(){
			
				offset = $(this).offset();
				if( prev_top != 0 && prev_top != offset.top ){
				
				} 
			
				highest_top = Math.max( highest_top, $(this).offset().top);
				o = o + $(this).offset().top + "|";
				$(this).append( $(this).offset().top); 
			});
			
			$(this).append( highest_top);
			//alert(highest_top);
			//alert(o + '\n\n' + highest_top);
			$(this).find('.sequence_page input[type=text]').each( function(){
				//$(this).top( highest_top ); 
				$(this).attr('value', highest_top );
			});			
			
			
		});
*/





		var thumbsPerRow = 0;									// placeholder
			var firstThumbOffset = $('.sequence_page').offset();
			var firstOffseTop = firstThumbOffset.top;
			$('.sequence_page').each(function() {
				var currentOffset = $(this).offset();
				var currentTop = currentOffset.top;
				if(currentTop==firstOffseTop) {
					thumbsPerRow++;
				}
			});



//alert(thumbsPerRow);



		ct = 0;
		row = 0;
		highest_top = 0;
		
			$('.sequence_info .textfield input[type=text]').each( function(){

				highest_top = Math.max( highest_top, $(this).offset().top);
				$(this).addClass('row' + row );

				ct++;
				if( ct == thumbsPerRow ){
					//$('.row' + row ).attr('style', 'position: absolute; top: ' + highest_top);
					$('.row' + row).each( function(){
						l = $(this).offset().left;

//						$(this).parent().attr('style', 'position: absolute');
//						$(this).parent().parent().attr('style', 'position: absolute');

//						$(this).attr('style', 'position: absolute; top: ' + highest_top + '; left: ' + l);						
					});
					
					highest_top = 0;
					ct = 0;
					row++;
				}

			});
			



}



function initCart(){


	// Hide it initially
	$('#discount_modal').hide();

	// Make it show up when one of the links is clicked
	$('.discount_modal_trigger').click(function(e) {
		e.preventDefault();
		$('#discount_modal').modal();
		return false;
	});
	
	// Make it hidden again
	$('.back_to_images').click( function(e){
		$('.modalClose').click();
	});


}











/* INIT
************************************************************************** */

function initStorefront() {

	// IE check
	if (jQuery.browser.msie) {
		ie=true;
		ieVersion = jQuery.browser.version;
		ieVersion = parseInt(ieVersion,10);
		if(ieVersion==6) { ie6=true; }
		if(ieVersion==7) { ie7=true; }
	}
	if( jQuery.browser.safari){
		safari = true;
	}

	checkSidebarHeight();
	hookFavToggle();
	hookFavoritesLink();
	hookLightboxLinks();
	checkLogoSize();
	hookPagination();
	hookBackToTop();
	hookPrintLinks();
	stopThievery();
	
	$('#logo img').load(function() { checkLogoSize(); });
	
	if($('#eventthumbs').length!=0) { fixEventImageHeights(); }				// Storefront homepage
	if($('#eventimages').length!=0) { initImagesPage(); }				// Event images page
	if($('#slideshow').length!=0) { initSlideshow(); }						// SLIDESHOW
	if($('#compareimages').length!=0 && $('#multiposepage').length == 0) { initCompare(); }					// COMPARE PAGE
	if($('#multiposepage').length!=0) { initMultipose(); }					// Multipose
	if($('#ordercontainer').length!=0) { initOrderPage(); }		// ORDER PAGE
	if($('#summary_check_out').length!=0) { initCheckOut(); }				// CHECK OUT
	if($('#sequence').length!=0) { initSequence(); }				// SEQUENCE
	if($('#cart').length!=0){ initCart(); }							// SHOPPING CART
	
	// takes care of right click
	$('*').bind('contextmenu', function(e) { e.preventDefault(); });
	
	// Stop thieves from dragging images out of the browser.  Ha!
	$('*').bind('dragstart', function(e) { e.preventDefault(); return false; });
	$('*').bind('selectstart', function(e) { e.preventDefault(); return false; });
	$('*').css('MozUserSelect', 'none');
	
	// hook window resize
	$(window).resize(function(){ addEmpties(); checkLogoSize(); });
	
	// focus the first input
	//$("input:first").focus();
	if( $("input[type!=hidden]:first").size() != 0 ){
		$("input[type!=hidden]:first").focus();
	} else {
		$("button:first").focus();
	}

	// Allow users to change the number of images per page
	// without having to click on the submit button
	$("#perpage1").change( function () {
		// Note: The value of the select menu contains the complete url
		window.location.href = $(this).val();
	})
}

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