//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( 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 )
        $("#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 )        
    }

}

function setupGalleryPage( data, page ){
    
    jsonData = data 
    
    var count = 1
    
    for(var i=0;i<8;i++){
        $("#photo_"+(i+1)).css("visibility","hidden")
    }

    $.each( data, function(i,item){
        
        count = (i+1)

        // make it visible
        $( "#photo_"+ (i+1) ).css('visibility','visible')
        
        var image;
		$.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);
				return;
			}
		})          
        
        // set image in place
        $( getImageDropId( i+1 ) ).html( image ) 
        
        // setup the link to allow voting for this image
        var href = "/eyewear/vote.action"
        $( "#vote_link_"+(i+1) ).attr("href", href+"?userId="+ item.userId )
        $("#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_"+(i+1)).html( voteCount + " votes" ) 
    })
    
    // 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="+(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))})
    	        }   
    		}
		})	
		
             
    }
}

/*
 * 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( "Frame ID: " + 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( "Frame ID: " + 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")	
	
}


