//TODO: Find the correct way to document javascript code.
//TODO: Remove hard coded references to external systems.

// gets the json data set during the call to setupPage( data )
// later used by the getImageData(image) method to retrieve JSON data
var jsonData

var locationForImages 

// the parent container for the 4 selected images
var selectedPhotosId = "my-phto-sel"

// the prefix of the id for the frameID container
var frameDropId = "drop_text"

// the prefix of the id for the selected Image container
var imageDropId = "drop_image"

// the prefix of the id for the remove image link 
var removeImageId = "remove_image"

var removeLinkId = "remove_link"

var watermarkId = "watermark"

// the prefix for the id of the delete image link
var deleteImageLinkId = "close_control"

// the prefix for the available images container
var availableImagesId = "my-phto-avail-phs"

// the prefix for the specific image slot inside the available images
var availableImageSlotId = "container"

var deleteDialogId = "dialog"

var dragCompleted = false

var imagesByPosition = new Array()
var imagesToSave = [' ', ' ', ' ', ' '] // fixed should never be more then four, position matters
var otherImages = new Array()
var positionsToSave = new Array()


var deleteCallback = function(){
    alert("delete callback!")
}

var imageDropCallback = function(){
    alert("image drop callback!")
}

var imageRemoveCallback = function(){
    alert("image remove callback")
}

var saveCallback = function(){
    alert("save callback")
}

function getSelectedPhotosId(){  return "#"+selectedPhotosId }
function getImageData( image ){ var idx = image.attr("photoDetailIdx"); return jsonData.photoDetails[idx] }
function getFrameDropId(  location ){ return "#" + frameDropId + "_" + location   }
function getImageDropId(  location ){ return "#" + imageDropId + "_" + location   }
function getRemoveLinkId( location ){ return "#" + removeLinkId + "_" + location }
function getRemoveImageId( location ){ return "#" + removeImageId + "_" + location }
function getWatermarkId( location ){ return "#" + watermarkId + "_" + location }
function getDeleteLinkId( imageId ){ return "#" + deleteImageLinkId + "_" + imageId }
function getAvailableImagesId( location ){ return "#" + availableImagesId }
function getAvailableImageSlotId( imageId ){ return "#" + availableImageSlotId + "_" + imageId }
function getDeleteDialogId(){ return "#"+deleteDialogId }
function setLocationForImages(path){ locationForImages = path }
/**
* An attempt to pull up some of the sript dependencies to control how the image
* src path gets created.
* param: filename, the name of the image file to use.
*/
function getUrl( filename ){
    
	return locationForImages + filename
}

function setupPhotoOnMyAccountPage( data ){
 
    var url = ""
    var highVote = 0

    $.each( data.photoDetails, function(i,item){
        
        if( item.numRatings > highVote ){
            highVote = item.numRatings
            url = item.url
        }
        
    } )
	
	if(highVote == 1) {
		voteText = "&nbsp;vote";
	} else {
		voteText = "&nbsp;votes";
	}
	
    if( url ){
        // there is a high rated photo
        $("#top-photo-id").html(  $("<img style='width:169px;height:148px;padding-left:7px;padding-top:7px;'/>").attr("src",getUrl( url ) ) )        
        $("#vote-count-id").html( highVote + voteText )
        $("#sticker_1").css("visibility","visible")
    }else{ // if not high vote then pick the first one
        
        // no photo is considered high rated, just pick the first one
        $("#top-photo-id").html(  $("<img style='width:169px;height:148px;padding-left:7px;padding-top:7px;'/>").attr("src",getUrl( data.photoDetails[0].url ) ) )        
        $("#vote-count-id").html( highVote + voteText )        
    }

}


/********************************************************************************************************************************************************************************
 ** Start of the voting gallery functions **
 *******************************************************************************************************************************************************************************/
/* Determines how many images need to be displayed, and then populates the HTML with the appropriate number of divs to accomodate the images */
function setupGalleryDivs(size) {
	var htmlContentBuffer = "";
	for(var rowIndex = 0; rowIndex < (size / 4); rowIndex++) {
		htmlContentBuffer = htmlContentBuffer + '<div id="gallery-photo-sel-con">';

		for(var photoIndex = 1; photoIndex <= 4; photoIndex++) { 
			htmlContentBuffer = htmlContentBuffer + 
				'<div class="gallery-photo-opt" style="visibility:hidden;"  id="photo_' + (photoIndex + (4*rowIndex)) + '">' +
				'<div class="my-phto-img-bk-top"></div>' +
				'<div class="vote-phto-img-bk">' +
					'<div class="vote-phto-img"  id="drop_image_' + (photoIndex + (4*rowIndex)) + '">' +
						'<img src="/images/common/spacer.gif" alt="" >' +
					'</div>' +
				'</div>' +
				'<div class="my-phto-img-bk-bottom">' +
					'<div class="gallery-vote-btn">' +
						'<a href="/eyewear/vote.action" id="vote_link_' + (photoIndex + (4*rowIndex)) + '"  style="text-decoration:none;">' +
							'<img width="48" height="19" alt="Click Here to Vote" src="/images/eyewear/voting/gallery/bt_vote.gif"/>' +
						'</a>' +
					'</div>' +
					'<div class="my-phto-img-votes-txt-gal" id="vote_text_' + (photoIndex + (4*rowIndex)) + '"></div>' +
					'<div class="gallery-phto-img-frame-txt" id="drop_text_' +(photoIndex + (4*rowIndex)) + '"></div>' +
				'</div>' +
			'</div>';
		} 

	htmlContentBuffer = htmlContentBuffer + '</div>';
	}
	$("#gallery-outside-container").html(htmlContentBuffer);
}

/* Figures out the pagination, then replaces the content of the pagination container div with the necessary pages */
function setupPagination( page, totalImages, size, column, sort ) {
	var numOptions = 5;
	var paginationContentBuffer = "";
	var totalPages = Math.ceil(totalImages / size);
	
	paginationContentBuffer = paginationContentBuffer + '<a href="/eyewear/pick-my-pair-gallery.action?sort=' + sort + '&page=1' + '&column=' + column + '&size=' + size + '" class="tot_pagination_link" onclick="setupGalleryPageWithAjax(1, ' + size + ', \'yes\', \'' + sort + '\', \'' + column + '\'); return false;">First</a>' + " ";
	
	//Previous button (if not on the first page)
	if(page != 1) {
		paginationContentBuffer = paginationContentBuffer + '<a href="/eyewear/pick-my-pair-gallery.action?sort=' + sort + '&page=' + (page-1) + '&column=' + column + '&size=' + size + '" class="tot_pagination_link" onclick="setupGalleryPageWithAjax('+ (page-1) + ', ' + size + ', \'yes\', \'' + sort + '\', \'' + column + '\'); return false;"><img src="/images/eyewear/pick-my-pair/arrow_left.gif" alt="Previous" onmouseover="this.src=\'/images/eyewear/pick-my-pair/arrow_left_orange.gif\'" onmouseout="this.src=\'/images/eyewear/pick-my-pair/arrow_left.gif\'" /></a>' + " ";
	}
	// First or second page case
	if(page == 1 || page == 2) {  
		for (var i = 1; i <= 5; i++) {
			if(page == i) {
				paginationContentBuffer = paginationContentBuffer + '<a href="/eyewear/pick-my-pair-gallery.action?sort=' + sort + '&page=' + i + '&column=' + column + '&size=' + size + '" class="tot_pagination_link_selected" onclick="setupGalleryPageWithAjax('+ i + ', ' + size + ', \'yes\', \'' + sort + '\', \'' + column + '\'); return false;">' + i + '</a>' + " ";
			} else {
				paginationContentBuffer = paginationContentBuffer + '<a href="/eyewear/pick-my-pair-gallery.action?sort=' + sort + '&page=' + i + '&column=' + column + '&size=' + size + '" class="tot_pagination_link" onclick="setupGalleryPageWithAjax('+ i + ', ' + size + ', \'yes\', \'' + sort + '\', \'' + column + '\'); return false;">' + i + '</a>' + " ";
			}
		}
		paginationContentBuffer = paginationContentBuffer + " ... " + '<a href="/eyewear/pick-my-pair-gallery.action?sort=' + sort + '&page=' + totalPages + '&column=' + column + '&size=' + size + '" class="tot_pagination_link" onclick="setupGalleryPageWithAjax('+ totalPages + ', ' + size + ', \'yes\', \'' + sort + '\', \'' + column + '\'); return false;">' + totalPages + '</a>' + " ";;
	} 
	
	// Last or second to last page case
	else if(page > (totalPages - 3)) { 
		for (var i = (totalPages - 4); i <= totalPages; i++) {
			if(page == i) {
				paginationContentBuffer = paginationContentBuffer + '<a href="/eyewear/pick-my-pair-gallery.action?sort=' + sort + '&page=' + i + '&column=' + column + '&size=' + size + '" class="tot_pagination_link_selected" onclick="setupGalleryPageWithAjax('+ i + ', ' + size + ', \'yes\', \'' + sort + '\', \'' + column + '\'); return false;">' + i + '</a>' + " ";
			} else {
				paginationContentBuffer = paginationContentBuffer + '<a href="/eyewear/pick-my-pair-gallery.action?sort=' + sort + '&page=' + i + '&column=' + column + '&size=' + size + '" class="tot_pagination_link" onclick="setupGalleryPageWithAjax('+ i + ', ' + size + ', \'yes\', \'' + sort + '\', \'' + column + '\'); return false;">' + i + '</a>' + " ";			
			}
		}
	} 
	
	else {
		page = parseInt(page);
		for (var i = (page - 2); i <= (page + 2); i++) {
			if(page == i) {
				paginationContentBuffer = paginationContentBuffer + '<a href="/eyewear/pick-my-pair-gallery.action?sort=' + sort + '&page=' + i + '&column=' + column + '&size=' + size + '" class="tot_pagination_link_selected" onclick="setupGalleryPageWithAjax('+ i + ', ' + size + ', \'yes\', \'' + sort + '\', \'' + column + '\'); return false;">' + i + '</a>' + " ";
			} else {
				paginationContentBuffer = paginationContentBuffer + '<a href="/eyewear/pick-my-pair-gallery.action?sort=' + sort + '&page=' + i + '&column=' + column + '&size=' + size + '" class="tot_pagination_link" onclick="setupGalleryPageWithAjax('+ i + ', ' + size + ', \'yes\', \'' + sort + '\', \'' + column + '\'); return false;">' + i + '</a>' + " ";		
			}
		}
		paginationContentBuffer = paginationContentBuffer + " ... " + '<a href="/eyewear/pick-my-pair-gallery.action?sort=' + sort + '&page=' + totalPages + '&column=' + column + '&size=' + size + '" class="tot_pagination_link" onclick="setupGalleryPageWithAjax('+ totalPages + ', ' + size + ', \'yes\', \'' + sort + '\', \'' + column + '\'); return false;">' + totalPages + '</a>' + " ";;
	}

	//Next button (if not on the last page)
	if(page != totalPages) {
		paginationContentBuffer = paginationContentBuffer + '<a href="/eyewear/pick-my-pair-gallery.action?sort=' + sort + '&page=' + (page+1) + '&column=' + column + '&size=' + size + '" class="tot_pagination_link" onclick="setupGalleryPageWithAjax('+ (page+1) + ', ' + size + ', \'yes\', \'' + sort + '\', \'' + column + '\'); return false;"><img src="/images/eyewear/pick-my-pair/arrow_right.gif" alt="Next" onmouseover="this.src=\'/images/eyewear/pick-my-pair/arrow_right_orange.gif\'" onmouseout="this.src=\'/images/eyewear/pick-my-pair/arrow_right.gif\'" /></a>' + " ";
	}
	paginationContentBuffer = paginationContentBuffer + '<a href="/eyewear/pick-my-pair-gallery.action?sort=' + sort + '&page=' + totalPages + '&column=' + column + '&size=' + size + '" class="tot_pagination_link" onclick="setupGalleryPageWithAjax('+ totalPages + ', ' + size + ', \'yes\', \'' + sort + '\', \'' + column + '\'); return false;">Last</a>';

	$('#pagination-controls-container').html(paginationContentBuffer);
	$('#pagination-controls-container-btm').html(paginationContentBuffer);
}

function setupGalleryPage( data, page, size, column, sort ){
	
	setupGalleryDivs(size);
	
    jsonData = data; 
	
	// Extract the number of galleries from the json
	var metaJson = data.meta;
	var totalImages = 0;
	$.each( metaJson, function(i,item){
		totalImages = item.TotalImages;
	})
	
	setupPagination(page, totalImages, size, column, sort);
	
	var count = 1
    
    for(var i=0;i<size;i++){
        $("#photo_"+(i+1)).css("visibility","hidden")
    }
	var photoPosition = 1;
	var numValidPhotos = 0;
	
    $.each( data.data, function(i,item){
        
        count = (i+1)
		var image;
		var imageIsValid = false;
		var validImageUrls = "";
				
		$.each(item.publicPhotos, function(j, photo){
			if(photo.sequence!=""){
				image = $("<img width='172' height='151' />").attr("src", getUrl( photo.url ) ).attr("photoDetailIdx", i ).attr("id","image_" + i);
				imageIsValid = true;
				validImageUrls = validImageUrls + photo.url + ",";
			}
		})          
        
		if(imageIsValid){
			// set image in place
			$( getImageDropId( photoPosition ) ).html( image ) 
			
			// setup the link to allow voting for this image
			var href = "/eyewear/vote.action"
			$( "#vote_link_"+(photoPosition) ).attr("href", href+"?userId="+ item.userId + "&validUrls=" + validImageUrls + "&galleryPage=" + page + "&size=" + size + "&column=" + column  + "&sort=" + sort )
			// Commented out for the Try on Tool job
			//$("#drop_text_"+(i+1)).html( item.publicPhotos[0].storeCity   + ", "  + item.publicPhotos[0].storeState )
			
			var voteCount = 0;
			$.each(item.publicPhotos, function(j, photo){
				if(photo.sequence!=""){
					voteCount += photo.numRatings;
				}
			})
			$("#vote_text_"+(photoPosition)).html( voteCount + " votes" ) 
			
			photoPosition++;
			numValidPhotos++;
		}
		
    })
	
	 // make it visible
	for(vp = 0; vp < numValidPhotos; vp ++) {
		$( "#photo_"+ (vp+1) ).css('visibility','visible');
	}
    
    // if this is the first page disable previous
    if( page==1 ){
        $(".gallery-prev-button-id").each(function(i){toggleDisplay($(this))})
    }
    
    // ok its not the first page but is the button on or off, check the class t
    if( page > 1 ){
        if( $(".gallery-prev-button-id:last").css("display")=="none" ){
            $(".gallery-prev-button-id").each(function(i){toggleDisplay($(this))})
        }
    }
    
    // less then 8 images disable next 
    if( data.length < 8 ){
        $(".gallery-next-button-id").each(function(i){toggleDisplay($(this))})
    }
    
    if( data.length == 8 ){
    	
    	$.getJSON( "/eyewear/pick-my-pair-gallery.action?type=json&page="+(parseInt(page) + 1),function(data){
    		if(data.success && data.success == "false"){
    			if( $(".gallery-next-button-id:last").css("display")=="block" ){
    	            $(".gallery-next-button-id").each(function(i){toggleDisplay($(this))})
    	        }   
    		}else{
    			if( $(".gallery-next-button-id:last").css("display")=="none" ){
    	            $(".gallery-next-button-id").each(function(i){toggleDisplay($(this))})
    	        }   
    		}
		})	
		
             
    }
}

/* Sets up the gallery without refreshing the page */
function setupGalleryPageWithAjax(page, size, showTotals, sort, column){
	var publicPhotosUrl = "/eyewear/pick-my-pair-gallery.action?type=json&showTotals=" + showTotals	+ "&sort=" + sort + "&size=" + size + "&column=" + column	+ "&page="+page;
	$.getJSON(publicPhotosUrl, function(data) {
		setupGalleryPage(eval(data), page, size, column, sort);
	});
}

/* Updates the control forms so that when the user makes a selection, both controls forms are changed to the selection they made */
function updateGalleryFormSelections(sizeSelection, sortSelection) {
	document.getElementById("topControlForm").size.selectedIndex = sizeSelection;
	document.getElementById("topControlForm").sortBy.selectedIndex = sortSelection;
	document.getElementById("bottomControlForm").size.selectedIndex = sizeSelection;
	document.getElementById("bottomControlForm").sortBy.selectedIndex = sortSelection;
}

/* Called when the user makes a selection in the Voting gallery controls */
/* Reads in the selections they made, then calls setupGalleryPageWithAjax to refresh the form with their selections made. */
function updateGallerySettings(form, page) {
	var size = form.size[form.size.selectedIndex].value;
	var sort = "desc";
	var column = "time";
	switch(form.sortBy[form.sortBy.selectedIndex].value) {
		case "MR":
			sort = "desc";
			column = "time";
			break;
		case "LR":
			sort = "asc";
			column = "time";
			break;
		case "MV":
			sort = "desc";
			column = "votes";
			break;
		case "LV":
			sort = "asc";
			column = "votes";
			break;
		default:
			sort = "desc";
			column = "time";
			break;
	}
	var showTotals = "yes";
	updateGalleryFormSelections(form.size.selectedIndex, form.sortBy.selectedIndex);
	setupGalleryPageWithAjax(page, size, showTotals, sort, column);
	return false;
}

/*** Legacy method for setting up the gallery page without pagination ***/
function setupOldGalleryPage( data, page ){

    jsonData = data 
	    
    var count = 1
    
    for(var i=0;i<8;i++){
        $("#photo_"+(i+1)).css("visibility","hidden")
    }
	var photoPosition = 1;
	var numValidPhotos = 0;
        
    $.each( data, function(i,item){
        
        count = (i+1)
		var image;
		var imageIsValid = false;
		var validImageUrls = "";
				
		$.each(item.publicPhotos, function(j, photo){
			if(photo.sequence!=""){
				image = $("<img width='172' height='151' />").attr("src", getUrl( photo.url ) ).attr("photoDetailIdx", i ).attr("id","image_" + i);
				imageIsValid = true;
				validImageUrls = validImageUrls + photo.url + ",";
			}
		})          
        
		if(imageIsValid){
			// set image in place
			$( getImageDropId( photoPosition ) ).html( image ) 
			
			// setup the link to allow voting for this image
			var href = "/eyewear/vote.action"
			$( "#vote_link_"+(photoPosition) ).attr("href", href+"?userId="+ item.userId + "&validUrls=" + validImageUrls + "&galleryPage=" + page )
			// Commented out for the Try on Tool job
			//$("#drop_text_"+(i+1)).html( item.publicPhotos[0].storeCity   + ", "  + item.publicPhotos[0].storeState )
			
			var voteCount = 0;
			$.each(item.publicPhotos, function(j, photo){
				if(photo.sequence!=""){
					voteCount += photo.numRatings;
				}
			})
			$("#vote_text_"+(photoPosition)).html( voteCount + " votes" ) 
			
			photoPosition++;
			numValidPhotos++;
		}
		
    })
	
	 // make it visible
	for(vp = 0; vp < numValidPhotos; vp ++) {
		$( "#photo_"+ (vp+1) ).css('visibility','visible');
	}
    
    // if this is the first page disable previous
    if( page==1 ){
        $(".gallery-prev-button-id").each(function(i){toggleDisplay($(this))})
    }
    
    // ok its not the first page but is the button on or off, check the class t
    if( page > 1 ){
        if( $(".gallery-prev-button-id:last").css("display")=="none" ){
            $(".gallery-prev-button-id").each(function(i){toggleDisplay($(this))})
        }
    }
    
    // less then 8 images disable next 
    if( data.length < 8 ){
        $(".gallery-next-button-id").each(function(i){toggleDisplay($(this))})
    }
    
    if( data.length == 8 ){
    	
    	$.getJSON( "/eyewear/pick-my-pair-gallery.action?type=json&page="+(parseInt(page) + 1),function(data){
    		if(data.success && data.success == "false"){
    			if( $(".gallery-next-button-id:last").css("display")=="block" ){
    	            $(".gallery-next-button-id").each(function(i){toggleDisplay($(this))})
    	        }   
    		}else{
    			if( $(".gallery-next-button-id:last").css("display")=="none" ){
    	            $(".gallery-next-button-id").each(function(i){toggleDisplay($(this))})
    	        }   
    		}
		})	
		
             
    }
}

/** End of the voting gallery functions
 ******************************************************************************************************************************************************************************
 ********************************************************************************************************************************************************************************
 *******************************************************************************************************************************************************************************/
/*
 * This method is used over toggle(), because in IE6, 
 * when toggling an element with an image, it may 
 * cause other images to disappear
 */
function toggleDisplay(elem){
	if($(elem).css("display") == "none"){
		$(elem).css("display", "block") 
	}else{
		$(elem).css("display", "none") 
	}
}

function setupVotingPage( data ){
   
    jsonData = data 

    var highVote = 0
    var imageSequence = 0
    
    $.each(data.photoDetails, function(i,item){
       
        var image = $("<img />").attr("src", getUrl( item.url ) ).attr("photoDetailIdx", i ).attr("id","image_" + i);

    	if( item.sequence!="" ){
    	    
    	    if( item.votable == true ){
        	    
        	    if( item.numRatings > highVote ){
        	        highVote = item.numRatings
        	        imageSequence = item.sequence
        	    }    	
        	    
        	    $("#vote_text_"+item.sequence).html( item.numRatings + " votes")        	        	                
    	    }
    	    
    	    addToPosition( image );
    	    $("#url_"+item.sequence+"_id").val( item.url )
    	    $("#photo_"+item.sequence).css('visibility','visible')
    	    //alert( item.numRatings )
    	    
    	    $("#drop_text_"+item.sequence).html( "Style Code: " + item.frameInfo )
    	}
    })
    
    
    if( imageSequence > 0 ){
        $("#my-phto-img-bk-top_"+imageSequence).addClass("top-phto-img-bk-top")
        $("#my-phto-img-bk_"+imageSequence).addClass("top-phto-img-bk")
        $("#my-phto-img-bk-bottom_"+imageSequence).addClass("top-phto-img-bk-bottom")
        $("#my-phto-img-bk-top_"+imageSequence).removeClass("my-phto-img-bk-top")
        $("#my-phto-img-bk_"+imageSequence).removeClass("vote-phto-img-bk")
        $("#my-phto-img-bk-bottom_"+imageSequence).removeClass("my-phto-img-bk-bottom")
        $("#sticker_"+imageSequence).css("visibility","visible")     
    }
    
}

/**
* First method that should be called to set up the image data on the page.
* param: data, the JSON data from the server.
*/
function setupPage( data ){

    // keep the data around for later
    jsonData =  data

    // an array to hold the selected images 
    var selected = new Array()

    // register the drop zones on the page
    registerEvents()

    // run through all the data in the JSON array and find selected photos
    // and add the other photos  to the available location on the page.
    $.each(data.photoDetails, function(i,item){

        var image = $("<img />").attr("src", getUrl( item.url ) ).attr("photoDetailIdx", i ).attr("id","image_" + i);

    	if( item.sequence!="" ){
    		selected[ selected.length ] = image
    	}else{
    		addImageToAvailableImages( image )				
    	}

    })

    $.each( selected, function(i,image){
    	addToPosition( image )
    })
    
    // initialize the dialog but don't show it
    createDeleteDialogBox()	
    	
}

function savePage(){
    saveCallback( imagesToSave, otherImages )
    return true;
}


function addImageToAvailableImages( image ){


	var imageData = getImageData( image )
			
	markImageAsOther( imageData )

    // Don't think I want to do this anymore since we will control this a different way.
	//imageData.sequence = "" // clear the sequence so that it will not be selected if it was
	
	// make the image draggable
	image.draggable({revert:'invalid',appendTo:'body',helper:'clone',zIndex:'2700',
        
		start:function(event,ui){
			dragCompleted=false 
			//$(  getDeleteLinkId( image.attr("id") )  ).hide()
			//$( getAvailableImageSlotId( image.attr("id") )  ).hide()  
		},
		stop: function(event,ui){
			
			if( dragCompleted){
				$( getDeleteLinkId( image.attr("id") )  ).remove()
				$( getAvailableImageSlotId( image.attr("id") )  ).remove()
			}else{
				$( getDeleteLinkId( image.attr("id") )  ).fadeIn('slow')
				$( getAvailableImageSlotId( image.attr("id") )  ).fadeIn('slow')  
			}
		}
		
	})
	
	// the image may have been set to absolute so reset it.
	//image.css('position','relative')
	//image.css('left','')
	//image.css('top','')
	
	//  look up the image container
	var container =  $( getAvailableImageSlotId( image.attr("id") ) )
	
	
	// if the image container doesn't exist create it
	if(  container.length <= 0    ){
		container = $("<div class='my_available_photo_border' height='20px;'></div>").attr("id", availableImageSlotId + "_" + image.attr("id") )   
		$( getAvailableImagesId()  ).append( container )			
	}

    // prepend to the image to the image container, prepend
    // to make sure the link is on the bottom. I had and issue with that.
	//$( getAvailableImageSlotId( image.attr("id") ) ).append( image )
	container.prepend( image )


    // look up the delete control container
	var control = $( getDeleteLinkId( image.attr("id") ) )
	
	
    // add the delete control if not there.
	if( control.length <= 0 ){
		control = $("<div class='my_available_photo_delete'></div>").attr("id", deleteImageLinkId + "_" + image.attr("id") )  
		control.click(function(){
		    $( getDeleteDialogId() ).attr("photoDetailIdx", image.attr("photoDetailIdx") )		    
		    $( getDeleteDialogId() ).attr("imageId", image.attr("id") )		    
			$( getDeleteDialogId() ).dialog("open")
		})
		control.append( "<img src='/images/eyewear/create-photo-page/bt_xdelete.gif'/>" ).append(" Frame ID: " + imageData.frameInfo ).appendTo( $(getAvailableImagesId() ) )
	}

    
}


function addToPosition( image ){

	var imageData = getImageData( image )
	
	//setPrivacyOption( imageData )

    // add this to the surrounding div for the selected images
	$( getImageDropId( imageData.sequence ) ).html( image )

    // get the elements
	var imageElement = $( getImageDropId( imageData.sequence ) )
	var frameElement = $( getFrameDropId( imageData.sequence ) )
	
	// set the frame data
	setFrameId ( frameElement , image ,imageData.sequence )	
	
	// set the vote count
	$( "#drop_vote_" +  imageData.sequence).html( imageData.numRatings + " votes" )

	markImageToSave( imageData, imageData.sequence )
	
	// set the image location based on image Element 
	//setPosition( imageElement , image )
	
	// turn the drop target off
	$( imageElement ).droppable('option','accept','')    
}

function markImageAsOther( imageData ){
    
    // get the index inside the save array
    var index = $.inArray(imageData.url,imagesToSave )

    if( index >=0 ){
        // remove from images to save
        imagesToSave.splice(index,1,' ') //preservce the spot using empty string
    }

    // see if it already exist in the other images
    index = $.inArray(imageData.url,otherImages )
    
    if( index < 0){ // if not add to the array of other images
        otherImages.push( imageData.url )
    }
    

    
}

function markImageToSave( imageData, location ){
        
    var index = $.inArray(imageData.url, otherImages )
    
    if( index >= 0 ){
        // remove from imagesToRemove
        otherImages.splice (index,1)
    }
    
    index = $.inArray(imageData.url, imagesToSave )
    
    if( index>=0 ){
        // remove from the images to save list
        imagesToSave.splice (index,1,' ' ) // preserve the spot using empty string
    }
    
    // put the image in the right location
    imagesToSave.splice( (location-1), 1 , imageData.url )
}

function setFrameId( frameElement, image, dropLocation ){
	
	// added to make visible the invisible slots on the
	// share page.
	if( $("#photo_"+dropLocation) ){
	    $("#photo_"+dropLocation).css("visibility","visible")
	}

	var imageData = getImageData( image )
	
	// get the frame ID data
	var frameId = imageData.frameInfo
	
	// enforce a 14 character limit on displaying frameIds
	if( frameId && frameId.length>14 ){
		frameId = frameId.substring(0,14)
	}

    // set the location on the JSON to the new location
	//imageData.sequence = dropLocation
	
	// set the id on the frame element 
	$( frameElement ).html( "Style Code: " + frameId )	
	
	$( getWatermarkId( dropLocation ) ).css("visibility", "visible")
	$( getRemoveImageId(dropLocation) ).css("visibility", "visible" )
	
	// set up the remove image link, and make it visible
	$(  getRemoveLinkId( dropLocation ) ).css('visibility','visible').click(function(){

        var imageTag = $( "#"+image.attr('id') )

		// remove image from the DOM
		imageTag.remove() 
		
		markImageAsOther( imageData )
		
		// add a clone back to the available list
		addImageToAvailableImages( image.clone() ) 
		
		resetSlot(dropLocation)
		
		$(this).unbind('click')
	})

}

function resetSlot( dropLocation ){
	
	// clear the frame id
	$( getFrameDropId( dropLocation ) ).html('') 

    // hide the remove link
    $( getWatermarkId( dropLocation ) ).css("visibility","hidden")
    $( getRemoveImageId( dropLocation ) ).css('visibility','hidden')
	$( getRemoveLinkId( dropLocation ) ).css('visibility','hidden') 
	
	// make the zone droppable again
	$(  getImageDropId( dropLocation ) ).droppable('option','accept','*') 
}

function createDeleteDialogBox(){
	$( getDeleteDialogId()  ).dialog({
			bgiframe: true,
			modal: true,
			autoOpen:false,
			title: "Delete Photo",
			buttons: {
				Delete: function() {
                    // get the id to get the json data for the callback
				    var idx = $(this).attr("photoDetailIdx")
				    // get the image id to remove from the available strip
				    var imageId = $(this).attr("imageId")
				    
				    // call the callback method to take care of the server side
				    deleteCallback( jsonData.photoDetails[idx]  )
				    
				    // remove from the available strip
    				$( getDeleteLinkId( imageId )  ).remove()
    				$( getAvailableImageSlotId( imageId )  ).remove()				    
				    
				    
					$(this).dialog('close');
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			}
	});    
}



function registerEvents(){
	
	$( getImageDropId( 1 )  ).droppable({
		
		drop:function(event,ui){
			dragCompleted = true
			//$( getSelectedPhotosId() ).append( ui.draggable )
			$( getImageDropId( 1 ) ).html( ui.draggable )			
			setFrameId ( $( getFrameDropId( 1 ) ), ui.draggable, 1 )
			
			markImageToSave( getImageData( ui.draggable ), 1)
			
			//setPosition( this, ui.draggable )
			$( this ).droppable('option','accept','')
			
			// prevent dragging to a new cell
			$(ui.draggable).draggable('option', 'cancel', '*');
		}
	})
	
	$( getImageDropId( 2 )  ).droppable({
		drop:function(event, ui){
			dragCompleted = true
			//$( getSelectedPhotosId() ).append( ui.draggable )
			$( getImageDropId( 2 ) ).html( ui.draggable )			

			setFrameId ( $( getFrameDropId( 2 ) ), ui.draggable, 2 )
			
			markImageToSave( getImageData( ui.draggable ), 2)
            
			
			//setPosition( this, ui.draggable )
			$( this ).droppable('option','accept','')
			
			// prevent dragging to a new cell
			$(ui.draggable).draggable('option', 'cancel', '*');
		}
	})
	
	$( getImageDropId( 3 )  ).droppable({
		drop:function(event,ui){
			dragCompleted = true
			$( getImageDropId( 3 ) ).html( ui.draggable )
			setFrameId ( $( getFrameDropId( 3 ) ), ui.draggable, 3 )
			
			markImageToSave( getImageData( ui.draggable ), 3)
			//setPosition( this, ui.draggable )
			$( this ).droppable('option','accept','')
			
			// prevent dragging to a new cell
			$(ui.draggable).draggable('option', 'cancel', '*');
		}
	})						
	
	$( getImageDropId( 4 )  ).droppable({
		drop:function(event,ui){
			dragCompleted = true
			//$( getSelectedPhotosId() ).append( ui.draggable )
			$( getImageDropId( 4 ) ).html( ui.draggable )
			setFrameId ( $( getFrameDropId( 4 ) ), ui.draggable, 4 )
			markImageToSave( getImageData( ui.draggable ), 4)
			//setPosition( this, ui.draggable )
			$( this ).droppable('option','accept','')
			
			// prevent dragging to a new cell
			$(ui.draggable).draggable('option', 'cancel', '*');
		}
	})    
}

function sendEmail(){

	$.post('/voting/emailFriends.action', $("#emailFriendsForm").serialize(), function(data){
		if( data.success == "true" ){
		
			$("<div>Your email has been sent! Would you like to send another one?</div>").dialog({
					buttons: {
							No: function() {
								$(this).dialog('close');
								$( '#emailDialog' ).dialog('close')
							},
							Yes: function() {
								$(this).dialog('close');
								$("#to").val("")
								$("#to").focus()										
							}
					}						
			})
		
		}else{
		
			var message = "";
			
			if(data.error){
				message = data.error;
			}else{
				message = "Sending your email failed."
			}
			$("<div>" + message + " Would you like to try again?</div>").dialog({
				buttons: {
						No: function() {
							$(this).dialog('close');
							$( '#emailDialog' ).dialog('close')
						},
						Yes: function() {
							$(this).dialog('close');
						}
				}	
							
			})
		}
		
	},"json")	
	
}


function sendAbuseEmail(){
	
	if($("#emailAddress").val() == '' || $("#comment").val() == ''){
		$("<div>Please enter all required fields.</div>").dialog({
			buttons: {
					OK: function() {
						$(this).dialog('close');
					}
			}						
		})
		return;
	}
	
	$.post('/email/reportAbuse.action', $("#reportAbuseForm").serialize(), function(data){
		if( data.success == "true" ){
		
			$("<div>Your email has been sent.</div>").dialog({
					buttons: {
							OK: function() {
								$(this).dialog('close');
								$( '#emailDialog' ).dialog('close')
							}
					}						
			})
		
		}else{
			var message = "";
			
			if(data.error){
				message = data.error;
			}else{
				message = "Sending your email failed."
			}
			
			$("<div>" + message + " Would you like to try again?</div>").dialog({
				buttons: {
						No: function() {
							$(this).dialog('close');
							$( '#emailDialog' ).dialog('close')
						},
						Yes: function() {
							$(this).dialog('close');
							sendEmail();
						}
				}	
							
			})
		}
		
	},"json")	
	
}



