var rotateAngle = 0;
var zoom = 100;

var editingPhotoID = '0';
var uploadSelected = '';
var currentEditButton = null;
    var PLACEHOLDER_SMALL;
var PLACEHOLDER_LARGE;

var DRAGGABLE_TOP = 'top';
var DRAGGABLE_MIDDLE = 'middle';

var theImages = new Array('#PlaceHolder1','#PlaceHolder2','#PlaceHolder3','#PlaceHolder4','#PlaceHolder5','#PlaceHolder6','#PlaceHolder7','#PlaceHolder8');
var theImagesSB = new Array('#ip1','#ip2','#ip3','#ip4','#ip5','#ip6','#ip7','#ip8');
var theImagesFive = new Array('#fiveip1','#fiveip2','#fiveip3','#fiveip4','#fiveip5');
var theImagesTree = new Array('#treeip1','#treeip2','#treeip3');
var theImagesTwo = new Array('#twoip1','#twoip2');
var theImagesOne = new Array('#oneip1');

$(function() {
  PLACEHOLDER_SMALL=document.getElementById('imgPlaceHolder1').value;
  PLACEHOLDER_LARGE=document.getElementById('imgPlaceHolder2').value;
	SetTopDraggables();
	InitMiddleSection();
});

function showhidex(imgid, bshow){
  var thePlaceholderDiv = null;
  if(imgid.indexOf('PlaceHolder') === 0){
    thePlaceholderDiv  = document.getElementById('btnRemoveFromPlaceholder_' + selectedDesign.id + '_' + imgid.substring(11));
  }else if(imgid.indexOf('ip') === 0){
    thePlaceholderDiv  = document.getElementById('btnRemoveFromPlaceholder_' + selectedDesign.id + '_' + imgid.substring(2));
  }else if(imgid.indexOf('fiveip') === 0){
    thePlaceholderDiv  = document.getElementById('btnRemoveFromPlaceholder_' + selectedDesign.id + '_' + imgid.substring(6));
  }else if(imgid.indexOf('treeip') === 0){
    thePlaceholderDiv  = document.getElementById('btnRemoveFromPlaceholder_' + selectedDesign.id + '_' + imgid.substring(6));
  }else if(imgid.indexOf('twoip') === 0){
    thePlaceholderDiv  = document.getElementById('btnRemoveFromPlaceholder_' + selectedDesign.id + '_' + imgid.substring(5));
  }else if(imgid.indexOf('oneip') === 0){
    thePlaceholderDiv  = document.getElementById('btnRemoveFromPlaceholder_' + selectedDesign.id + '_' + imgid.substring(5));
  }
  if(bshow){
    if(thePlaceholderDiv.className.indexOf('btnRemoveFromPlaceholderSmall') === 0){
      thePlaceholderDiv.className='btnRemoveFromPlaceholderSmall';
    }else if(thePlaceholderDiv.className.indexOf('btnRemoveFromPlaceholderLarge') === 0){
      thePlaceholderDiv.className='btnRemoveFromPlaceholderLarge';
    }else if(thePlaceholderDiv.className.indexOf('btnRemoveFromPlaceholderFive') === 0){
      thePlaceholderDiv.className='btnRemoveFromPlaceholderFive';
    }
  }else{
    if(thePlaceholderDiv.className.indexOf('btnRemoveFromPlaceholderSmall') === 0){
      thePlaceholderDiv.className='btnRemoveFromPlaceholderSmallH';
    }else if(thePlaceholderDiv.className.indexOf('btnRemoveFromPlaceholderLarge') === 0){
      thePlaceholderDiv.className='btnRemoveFromPlaceholderLargeH';
    }else if(thePlaceholderDiv.className.indexOf('btnRemoveFromPlaceholderFive') === 0){
      thePlaceholderDiv.className='btnRemoveFromPlaceholderFiveH';
    }
  }
}

function InitMiddleSection(){
	SetMiddleDraggables();
	UpdateMiddleDraggables();
	SetMiddleDroppables();
	UpdateMiddleDroppables();

	$('.imgPlaceholderSmall').hover(
		function(){
			// only add hover "x" over non droppable placeholders (those that already have an image dropped on them)
			var fimg = $(this).find('img:first');
			if ((fimg.hasClass('ui-droppable-disabled'))
				&& (fimg.attr('src').indexOf(PLACEHOLDER_SMALL) == -1)
				&& (fimg.attr('src').indexOf(PLACEHOLDER_LARGE) == -1))
			{
                showhidex(fimg[0].id, true);
			}
		},
		function(){	 
			// remove the hover "x" only if needed
			var fimg = $(this).find('img:first');
			if ((fimg.hasClass('ui-droppable-disabled'))
				&& (fimg.attr('src').indexOf(PLACEHOLDER_SMALL) == -1)
				&& (fimg.attr('src').indexOf(PLACEHOLDER_LARGE) == -1))
			{
                showhidex(fimg[0].id, false);
			}
		}
	);

	$('.imgPlaceholderLarge').hover(
		function(){
			// only add hover "x" over non droppable placeholders (those that already have an image dropped on them)
			var fimg = $(this).find('img:first');
			if ((fimg.hasClass('ui-droppable-disabled'))
				&& (fimg.attr('src').indexOf(PLACEHOLDER_SMALL) == -1)
				&& (fimg.attr('src').indexOf(PLACEHOLDER_LARGE) == -1))
			{
                showhidex(fimg[0].id, true);
			}
		},
		function(){
			// remove the hover "x" only if needed
			var fimg = $(this).find('img:first');
			if ((fimg.hasClass('ui-droppable-disabled'))
				&& (fimg.attr('src').indexOf(PLACEHOLDER_SMALL) == -1)
				&& (fimg.attr('src').indexOf(PLACEHOLDER_LARGE) == -1))
			{
                showhidex(fimg[0].id, false);
			}
		}
	);
	$('.imgPlaceholderFive').hover(
		function(){
			// only add hover "x" over non droppable placeholders (those that already have an image dropped on them)
			var fimg = $(this).find('img:first');
			if ((fimg.hasClass('ui-droppable-disabled'))
				&& (fimg.attr('src').indexOf(PLACEHOLDER_SMALL) == -1)
				&& (fimg.attr('src').indexOf(PLACEHOLDER_LARGE) == -1))
			{
                showhidex(fimg[0].id, true);
			}
		},
		function(){
			// remove the hover "x" only if needed
			var fimg = $(this).find('img:first');
			if ((fimg.hasClass('ui-droppable-disabled'))
				&& (fimg.attr('src').indexOf(PLACEHOLDER_SMALL) == -1)
				&& (fimg.attr('src').indexOf(PLACEHOLDER_LARGE) == -1))
			{
                showhidex(fimg[0].id, false);
			}
		}
	);
}

var topDraggables = null;
var draggingD = DRAGGABLE_TOP;
var draggindCurID = '';

function SetTopDraggables(){
	topDraggables = $("#imgCollectionImages .PicturePhoto").draggable({ 
		revert: 'invalid',
		snap: $('#arrangePhotosWrapper .imgSmall,#arrangePhotosWrapper .imgLarge'),
		snapMode: 'inner',
		snapTolerance: '20',
		cursor: 'move',
		zIndex: 1000,
		appendTo: '#container',
		helper: 'clone',
		start: function(event,ui){
			draggingD = DRAGGABLE_TOP;
		},
		stop: function(event,ui){
			$('body').css('cursor', 'default');
		}
	});
}

var middleDraggables = null;

function SetMiddleDraggables(){

	middleDraggables = $("#arrangePhotosWrapper .imgSmall,#arrangePhotosWrapper .imgLarge").draggable({
		revert: 'invalid',
		snap: '.imgLarge,.imgSmall',
		snapMode: 'inner',
		snapTolerance: '40',
		cursor: 'move',
		zIndex: 1000,
		appendTo: '#container',
		helper: 'clone',		
		start: function(event,ui){
			draggingD = DRAGGABLE_MIDDLE;
			draggingCurID = $(this).attr('id');	
			if (selectedDesign.id==3 || selectedDesign.id==4 || selectedDesign.id==5 || selectedDesign.id==6 ){	    
      $(ui.helper).css('width','125px').css('height','125px');      
      }
		},		
		stop: function(event,ui){
			$('body').css('cursor', 'default');
		}
	});

}

function UpdateMiddleDraggables(){
    $("#arrangePhotosWrapper .imgSmall:not([src*='" + PLACEHOLDER_SMALL + "']) ,#arrangePhotosWrapper .imgLarge:not([src*='" + PLACEHOLDER_LARGE + "'])").draggable('enable');
    $("#arrangePhotosWrapper .imgSmall[src*='" + PLACEHOLDER_SMALL + "'],#arrangePhotosWrapper .imgLarge[src*='" + PLACEHOLDER_LARGE + "']").draggable('disable');
}

function SetMiddleDroppables(droppables) {
    $("#arrangePhotosWrapper .imgSmall,#arrangePhotosWrapper .imgLarge").droppable({  
		drop: function(event, ui) {
		    // make sure we snap the object to its placehoder edges
		    var newX = ui.position.left - ($(ui.helper).offset().left - $(this).offset().left);
		    var newY = ui.position.top - ($(ui.helper).offset().top - $(this).offset().top);
		    //$(ui.helper).animate({left: newX, top: newY}, 300);		    
		    if (DRAGGABLE_TOP == draggingD){
		        // zoom the image as needed
		        $(ui.helper).animate( {width: $(this).css('width'), height: $(this).css('height')}, {queue:false, duration:300});
		    }			
		    // replace the images.
		    //$(this)[0].src = $(ui.draggable)[0].src;
		    $('body').css('cursor', 'default');
		    // do the resize magic for the scrap book layout.
			var theThisSB = null;var theThisSQ = null;var theThisFive = null;var theThisTree = null;var theThisTwo = null;var theThisOne = null;
			if ($(this)[0].id.indexOf('ip') === 0){
				theThisSB = $(this);
				theThisSQ = $('#PlaceHolder' + $(this)[0].id.replace('ip',''));				
			}else if ($(this)[0].id.indexOf('PlaceHolder') === 0){
				theThisSB = $('#ip' + $(this)[0].id.replace('PlaceHolder',''));
				theThisSQ = $(this);
			}else if ($(this)[0].id.indexOf('fiveip') === 0){			
			  theThisFive = $(this);
			}else if ($(this)[0].id.indexOf('treeip') === 0){			
			  theThisTree = $(this);
			}else if ($(this)[0].id.indexOf('twoip') === 0){
			  theThisTwo = $(this);
			}else if ($(this)[0].id.indexOf('oneip') === 0){
			  theThisOne = $(this);
			}

			if (theThisSB != null && theThisSQ != null){			
			  theThisSB[0].src = $(ui.draggable)[0].src;
			  theThisSQ[0].src = $(ui.draggable)[0].src;
			  ResizeDroppedImage(theThisSB);
			}else if (theThisFive != null){			
			  theThisFive[0].src = $(ui.draggable)[0].src;			  
			  ResizeDroppedImage(theThisFive);			
			}else if (theThisTree != null){			
			  theThisTree[0].src = $(ui.draggable)[0].src;			  
			  ResizeDroppedImage(theThisTree);
			}else if (theThisTwo != null){			
			  theThisTwo[0].src = $(ui.draggable)[0].src;			  
			  ResizeDroppedImage(theThisTwo);
			}else if (theThisOne != null){			
			  theThisOne[0].src = $(ui.draggable)[0].src;			  
			  ResizeDroppedImage(theThisOne);
			}
			// recreate the draggable; after the image has settled in its place.
			$(this).draggable('enable');
			$(this).droppable('disable');
			
			if (DRAGGABLE_MIDDLE == draggingD){
				var oldD = $('#' + draggingCurID);
				if (oldD.hasClass('imgLarge')){
					oldD.attr('src', PLACEHOLDER_LARGE);
				}else{
					oldD.attr('src', PLACEHOLDER_SMALL);
					oldD.css('width', '125px').css('height', '125px').css('margin-left', 'auto').css('margin-top', '0px');
				}
				oldD.draggable('disable');
				oldD.droppable('enable');
                showhidex(draggingCurID, false); 
			}
			
			// if we are not in SB or SQ return
			if (theThisSB == null && theThisSQ == null){
			  return;
			 }
			
			// do the same stuff for the twin image
			var theTwinImage; var theTwinOld;
			if ($(this)[0].id.indexOf('ip') === 0){
				theTwinImage = $('#PlaceHolder' + $(this)[0].id.replace('ip',''));
			}else{
				theTwinImage = $('#ip' + $(this)[0].id.replace('PlaceHolder',''));
			}
			theTwinImage.draggable('enable');
			theTwinImage.droppable('disable');
			
			if (DRAGGABLE_MIDDLE == draggingD)
			{
				if ($(this)[0].id.indexOf('ip') === 0){
					theTwinOld = $('#PlaceHolder' + draggingCurID.replace('ip',''));
				}else{
					theTwinOld = $('#ip' + draggingCurID.replace('PlaceHolder',''));
				}
				if (theTwinOld.hasClass('imgLarge')){
					theTwinOld.attr('src', PLACEHOLDER_LARGE);
				}else{
					theTwinOld.attr('src', PLACEHOLDER_SMALL);
					theTwinOld.css('width', '125px').css('height', '125px').css('margin-left', 'auto').css('margin-top', '0px');
				}
				theTwinOld.draggable('disable');
				theTwinOld.droppable('enable');
			}
		},
		over: function(event, ui)
		{
			$(ui.helper).animate( {width: $("#" + this.id).css('width'), height: $("#" + this.id).css('height')}, {queue:false, duration:300});
		},
		out: function(event, ui){}
	});
}

function ResizeDroppedImage(dItem){
	// stretch the image to the parent.
	var a = dItem.parent();
	var imgX = dItem[0].width;
	var imgY = dItem[0].height;
	var divX = 0 + a.css('width').replace('px','');
	var divY = 0 + a.css('height').replace('px','').replace('auto','0');
	
    if(imgX == 0){
      imgX = 0 + dItem.css('width').replace('px','');
    }
    if(imgY == 0){
      imgY = 0 + dItem.css('height').replace('px','').replace('auto','0');
    }
    if(imgX == 0){return;}
    if(imgY == 0){return;}
	var nPercent = 1.0;
	nPercent = Math.max((0.0 + divX) / imgX, (0.0 + divY) / imgY);
	
	var x=0;var y=0;var newX=0; var newY=0;
	newX = imgX*nPercent;
	newY = imgY*nPercent;
	if(divX>imgX){
		x=(divX-newX)/2;
	}
	if (divY>imgY){
		y = (divY-newY)/2;
	}
    // IN IE8, sometimes, x and y are NaN!
    try{
      dItem.css('margin-left', x);
      dItem.css('margin-top', y);	
      dItem.css('width', newX + 'px');
      dItem.css('height', newY + 'px');
    }catch(e){}
	//fbLog(x + ' | ' + y + ' -- ' + newX + ' | ' + newY);
}

function UpdateMiddleDroppables(){
    $("#arrangePhotosWrapper .imgSmall:not([src*='" + PLACEHOLDER_SMALL + "']) ,#arrangePhotosWrapper .imgLarge:not([src*='" + PLACEHOLDER_LARGE + "'])").droppable('disable');
    $("#arrangePhotosWrapper .imgSmall[src*='" + PLACEHOLDER_SMALL + "'],#arrangePhotosWrapper .imgLarge[src*='" + PLACEHOLDER_LARGE + "']").droppable('enable');
}

var slider1 = null;
var slider2 = null;

var modalEdit = null;

function ShowModalEdit(btnEdit, i){
	//setTimeout('_ShowModalEdit(\'' + btnEdit.id + '\', \'' + i + '\');', 200);
	_ShowModalEdit(btnEdit.id, i);
}

function _ShowModalEdit(btnEditID, i)
{
	btnEdit = document.getElementById(btnEditID);
    if (null == modalEdit){
        // set up the modal
        modalEdit = $('#modalEdit').dialog({
            autoOpen: false,
            closeOnEscape: true,
            draggable: false,
            modal: true,
            modal: true,
            position: 'center',
            resizable: false,
            height: 454,
            width: 522,
            close:function(event,ui){
           	    // in order that the canvas is rebuilt remove it and recreate the image.
                // reset the sliders
                $('#imgEditor').remove();
                $('#imgEditorContainer2').html('<img id="imgEditor" alt="Editor" src="/images/spacer.gif"/>');
                rotateAngle = 0;
                zoom = 100;
                slider1.slider('destroy');
                slider2.slider('destroy');
            }
        });
    }
    
    editingPhotoID = i;
    
    var sourceImage;
    sourceImage = $("#" + btnEdit.id).parent().children(":first").children(":first");
    document.getElementById('imgEditor').src = sourceImage[0].src;
    //setTimeout('document.getElementById("imgEditor").src = "' + sourceImage[0].src + '";', 200);

    var nStep = 1;
    if (document.all && !window.opera){
        nStep = 40;    
    }

    slider1 = $("#sliderZoom").slider({
        value:100,
	    min: 0,
	    max: 200,
	    step: nStep,
	    slide: function(event, ui) {
		    zoom = ui.value;		   
		    $("#imgEditor").transform(rotateAngle, 'abs', zoom);
	    },
	    change: function(event, ui) {
		    zoom = ui.value;
		    $("#imgEditor").transform(rotateAngle, 'abs', zoom);
	    }
    });
	
	
	nStep = 1;
    if (document.all && !window.opera){
        nStep = 90;    
    }
    
    slider2 = $("#sliderRotate").slider({
        value:0,
	    min: -180,
	    max: 180,
	    step: nStep,
	    slide: function(event, ui) {
		    rotateAngle = ui.value;
		    $("#imgEditor").transform(rotateAngle, 'abs', zoom);
	    },
	    change: function(event, ui) {
		    rotateAngle = ui.value;
		    $("#imgEditor").transform(rotateAngle, 'abs', zoom);
	    }
    });
    
    currentEditButton = btnEdit;
    
    // required to initialize the translation.
    jQuery.fn.resetTransformData();
    // this is required for our image to be transformed into a canvas.
    $('#imgEditor').transform(rotateAngle, 'abs', zoom);
    
    modalEdit.dialog('open');
}
	
	function ResetEditor()
	{
	    rotateAngle = 0;
        zoom = 100;
        jQuery.fn.resetTransformData();
        $("#imgEditor").transform(rotateAngle, 'abs', zoom);
        $("#sliderZoom").slider('option', 'value', 100);
        $("#sliderRotate").slider('option', 'value', 0);
	}
	
	function DoneEditing()
	{
	    var theX = jQuery.fn.translateX;
	    var theY = jQuery.fn.translateY;
	    // in IE the container is smaller. and we do the reverse calculus from the zoom
	    if (document.all && !window.opera){
	        theX = Math.round((theX - ((240-(240.0*(zoom/100.0)))/2)) * (300.0/242.0));
	        theY = Math.round((theY - ((240-(240.0*(zoom/100.0)))/2)) * (300.0/242.0));
	    }
	
	    //rotateAngle, zoom.
	    $.get('/_api/tattoodle-your-photos-api.aspx?a=doneEditing&p=' + editingPhotoID + '&r=' + rotateAngle + '&z=' + zoom + 
	    '&tx=' + theX + '&ty=' + theY +
	    '&zz=' + (new Date().getTime()), null, function(result){
	        $('#imgCollectionImages').html(result);
	        
            if (currentEditButton){
				updateCloneImages();
            }
            
	        SetTopDraggables();
	    }, null);
	    
	    modalEdit.dialog('close');
	    return false;
	}
	
	var modalUpload = null;
	var modalUploadFlashError = null;
	function ShowModalUpload()
	{
	    if (FlashDetect.versionAtLeast(10))
	    {
	        if (null == modalUpload){
	            // set up the modal
	            modalUpload = $('#modalUpload').dialog({
	                autoOpen: false,
	                closeOnEscape: true,
	                draggable: false,
	                modal: true,
	                position: 'center',
	                resizable: false,
	                height: 454,
	                width: 522
	            });
	        }
	        clearUploadForm();
	        //document.getElementById('hdnUploadSelected').value = 'pc';
	        modalUpload.dialog('open');
	    }
	    else
	    {
	        if (null == modalUploadFlashError){
	            // set up the modal
	            modalUploadFlashError = $('#modalUploadFlashError').dialog({
	                autoOpen: false,
	                closeOnEscape: true,
	                draggable: false,
	                modal: true,
	                position: 'center',
	                resizable: false,
	                height: 242,
	                width: 522
	            });
	            
	            $('#btnFlashErrorClose').click(function(){
                modalUploadFlashError.dialog('close');
                return false;
            });
	          }  
	          modalUploadFlashError.dialog('open');	        
	    }	    
	}
	
	
	function CloseUploadFlashError()
	{
	    if (modalUploadFlashError != null)
	    {
	        modalUploadFlashError.dialog('close');
	    }
	}
	
	function updateCloneImages()
	{
	    // the source image is the right one, cached by the browser.
        var sourceImage = $("#" + currentEditButton.id).parent().children(":first").children(":first").attr('src');
        var indexSlash = sourceImage.lastIndexOf('/');
        var checkImage = sourceImage;
        if (indexSlash > -1){
            checkImage = checkImage.substring(indexSlash);
        }
        if (checkImage.indexOf('?') > -1){
            checkImage = checkImage.substring(0, checkImage.indexOf('?'));
        }
		
        // update all images that for which the src contains sourceImage
        var currImg;
        for (i = 0; i< document.images.length; i++)
        {
            currImg = document.images[i];
            if ((currImg.src.indexOf(checkImage) > 0) && ((currImg.className.indexOf('imgSmall') > -1) || (currImg.className.indexOf('imgLarge') > -1)))
            {
                currImg.src = sourceImage;
            }
        }
	}
	
	function startUpload(){
	    if ('' == document.getElementById('filePhoto').value){return false;}
	    document.getElementById('ui-dialog-title-modalUpload').innerHTML = document.getElementById('intploading').value;
	    //document.getElementById('formUpload').style.display = 'none';
	    document.getElementById('formUploadUploading').style.display = 'block';
	    return true;
	}

    function closeUpload(){
	        modalUpload.dialog('close');
	}

    function clearUploadForm(){
   	    //document.getElementById('ui-dialog-title-modalUpload').innerHTML = 'Upload Photos';
	    //document.getElementById('formUpload').style.display = 'block';
	    document.getElementById('formUploadUploading').style.display = 'none';
	    document.getElementById('modalLoadingAnimation').innerHTML = '<img src="/images/tattoodle-your-photos/Loading-Image-TattoodlePhoto.gif" alt="Loading..." />';
	    document.getElementById('formUploadingButtons').style.display='none';
    }

	function setUploadPhotoValue(){
	    document.getElementById('fileUploadPhotoText').value = document.getElementById('filePhoto').value;
	}
	function uploadCompleted(result, msg){	   
		if(result != 0){
			document.getElementById('modalLoadingAnimation').innerHTML = msg;
			document.getElementById('formUploadingButtons').style.display='block';
		}
		else{
			closeUpload();
			$.get('/_api/tattoodle-your-photos-api.aspx?a=getPhotosUp&zz=' + (new Date().getTime()), null, function(result){
				topDraggables.draggable('destroy');
				$('#imgCollectionImages').html(result);
				SetTopDraggables();
			}, 'html');
		}
	}
	
	function backToUpload(){
	    clearUploadForm();
	    document.getElementById('formUploadUploading').style.display = 'none';
		//document.getElementById('formUpload').style.display='block';
	}
	
	function deletePhoto(objID, iid){
	    // get the src of the photo that was clicked on and remove from the middle sections all the photos that match the src.
	    var a = $('#' + objID);
	    var sourceImage = a.parent().children(":first").children(":first").attr('src');
	    var indexSlash = sourceImage.lastIndexOf('/');
        var checkImage = sourceImage;
        if (indexSlash > -1){
            checkImage = checkImage.substring(indexSlash);
        }
        if (checkImage.indexOf('?') > -1){
            checkImage = checkImage.substring(0, checkImage.indexOf('?'));
        }
	    
	    $.get('/_api/tattoodle-your-photos-api.aspx?a=deletePhoto&p=' + iid + '&zz=' + (new Date().getTime()), null, function(result){
	        topDraggables.draggable('destroy');
	        $('#imgCollectionImages').html(result);
	        SetTopDraggables();
	    }, 'html');
	    
	    var currImg;
	    for (i = 0; i< document.images.length; i++)
        {
            currImg = document.images[i];
            if (currImg.src.indexOf(checkImage) >= 0)
            {
                var bFound = false;
                var bSmall = false;
                // step1: replace image with placeholder
              	if (currImg.className.indexOf('imgSmall') > -1)
	            {
		            currImg.src = PLACEHOLDER_SMALL;
		            bFound = true;
                    bSmall = true;
	            }
	            else if (currImg.className.indexOf('imgLarge') > -1)
	            {
		            currImg.src = PLACEHOLDER_LARGE;
		            bFound = true;
	            }
	            
	            if (bFound)
	            {
	                // step2: recreate droppable on this placeholder
                    $('#' + currImg.id).draggable('destroy');
	                $('#' + currImg.id).droppable('enable');
                    if(bSmall){
                      $('#' + currImg.id).css('width', '125px').css('height', '125px').css('margin-left', 'auto').css('margin-top', '0px');
                    }else{
                      $('#' + currImg.id).css('width', '153px').css('height', '153px').css('margin-left', 'auto').css('margin-top', '0px');
                    }
	             }
            }
        }
	}
	
	function fbLog(obj){
		if(typeof(console) != 'undefined'){
			console.log(obj);
		}
	}
	
	/* top images scrolling */
	var TOP_IMAGES_SIZE = 658;
	var topImagesScrollPosition = 0;
	
	function scrollToStart(){
		if (topImagesScrollPosition == 0){
			return;
		}
		if (topImagesScrollPosition >= TOP_IMAGES_SIZE){
			topImagesScrollPosition -= TOP_IMAGES_SIZE;
		}else{
			topImagesScrollPosition = 0;
		}
		updateTopImageArrows();
		$('#imgCollectionImagesContainer').scrollTo(topImagesScrollPosition, 500, {axis:'x'});
	}
	
	function scrollToEnd(){
		var theWidth = $('#imgCollectionImagesContainer').width();
		if (topImagesScrollPosition >= (theWidth-TOP_IMAGES_SIZE)){
			return;
		}
		if (topImagesScrollPosition < (theWidth-TOP_IMAGES_SIZE)){
			topImagesScrollPosition += TOP_IMAGES_SIZE;
		}else{
			topImagesScrollPosition = (theWidth-TOP_IMAGES_SIZE);
		}
		updateTopImageArrows();
		$('#imgCollectionColorContainer').scrollTo(topImagesScrollPosition ,500, {axis:'x'});
	}
	
	function updateTopImageArrows(){
		var theWidth = $('#imgCollectionImagesContainer').width();
		if(frameColorScrollPosition <= 0){
			document.getElementById('leftArrowFrameColor').src = '/images/tattoodle-your-photos/frameColorArrowLeft_gray.gif';
		}else{
			document.getElementById('leftArrowFrameColor').src = '/images/tattoodle-your-photos/frameColorArrowLeft.gif';
		}
		if(frameColorScrollPosition >= (theWidth-FRAME_COLOR_SIZE)){
			document.getElementById('rightArrowFrameColor').src = '/images/tattoodle-your-photos/frameColorArrowRight_gray.gif';
		}else{
			document.getElementById('rightArrowFrameColor').src = '/images/tattoodle-your-photos/frameColorArrowRight.gif';
		}
	}
	/* --- */
	
	var nStepZoom = 10;
	if (document.all && !window.opera){
		nStepZoom = 20;
	}
	
	function ZoomOut(){
	    //slider1
	    var min = slider1.slider('option', 'min');
	    var a = slider1.slider('value');
	    if (a >= min+nStepZoom){
	        slider1.slider('value', a-nStepZoom);
	    }else{
	        slider1.slider('value', min);
	    }
	}
	
	function ZoomIn(){
	    //slider1
	    var max = slider1.slider('option', 'max');
	    var a = slider1.slider('value');
	    if (a <= max-nStepZoom){
	        slider1.slider('value', a+nStepZoom);
	    }else{
	        slider1.slider('value', max);
	    }
	}
	
	var nStepButton = 10;
	if (document.all && !window.opera){
		nStepButton = 90;
	}
	
	function RotateLeft(){
	    //slider2
	    var min = slider2.slider('option', 'min');
	    var a = slider2.slider('value');
	    if (a >= min+nStepButton){
	        slider2.slider('value', a-nStepButton);
	    }else{
	        slider2.slider('value', min);
	    }
	}
	
	function RotateRight(){
	    //slider2
	    var max = slider2.slider('option', 'max');
	    var a = slider2.slider('value');
	    if (a <= max-nStepButton){
	        slider2.slider('value', a+nStepButton);
	    }else{
	        slider2.slider('value', max);
	    }
	}
	
	function deletePhotoButton(btnDeletePhoto)
	{
	    // step1: get the parent and the twin parent
		//fbLog(btnDeletePhoto);
	    var thei = $(btnDeletePhoto).parent().parent().find('img:first');
		
		var theTwinImage;
		if (thei[0].id.indexOf('ip') === 0){
			theTwinImage = $('#PlaceHolder' + thei[0].id.replace('ip',''));			
		}else  if(thei[0].id.indexOf('PlaceHolder') === 0){
			theTwinImage = $('#ip' + thei[0].id.replace('PlaceHolder',''));			
		}else if(thei[0].id.indexOf('fiveip') === 0){		  
		  theTwinImage = $('#PlaceHolder' + thei[0].id.replace('fiveip',''));			
		}else if(thei[0].id.indexOf('treeip') === 0){		  
		  theTwinImage = $('#PlaceHolder' + thei[0].id.replace('treeip',''));			
		}else if(thei[0].id.indexOf('twoip') === 0){		  
		  theTwinImage = $('#PlaceHolder' + thei[0].id.replace('twoip',''));			
		}else if(thei[0].id.indexOf('oneip') === 0){		  
		  theTwinImage = $('#PlaceHolder' + thei[0].id.replace('oneip',''));			
		}
		
		
		// step 1.2: replace with the placeholder
	    if (thei.attr('class').indexOf('imgSmall') > -1)
	    {
	        document.images[thei.attr('id')].src = PLACEHOLDER_SMALL;
			thei.css('width', '125px').css('height', '125px').css('margin-left', 'auto').css('margin-top', '0px');
	    }
	    else
	    {
	        document.images[thei.attr('id')].src = PLACEHOLDER_LARGE;
	    }
		
		// step 1.2: replace the twin image with the placeholder
		if (theTwinImage.attr('class').indexOf('imgSmall') > -1)
	    {
	        document.images[theTwinImage.attr('id')].src = PLACEHOLDER_SMALL;
			theTwinImage.css('width', '125px').css('height', '125px').css('margin-left', 'auto').css('margin-top', '0px');
	    }
	    else
	    {
	        document.images[theTwinImage.attr('id')].src = PLACEHOLDER_LARGE;
	    }
		
	    // step2: recreate droppable on this placeholder
	    thei.droppable('enable');
	    thei.draggable('disable');

		// step 2.1: recreate droppable on the twin placeholder
		theTwinImage.droppable('enable');
	    theTwinImage.draggable('disable');
		
	    // step5: remove hover "x"
	    //$(btnDeletePhoto).parent().remove();
        showhidex(thei[0].id, false);
	}
	
	function prepareSubmit(){
	   var pictureAdded=0;
	   //var imgplaceholder='/images/tattoodle-your-photos/PhotoPlaceHolder1.jpg';
	   //var imgplaceholder2='/images/tattoodle-your-photos/PhotoPlaceHolder2.jpg';
       
	   var imgplaceholder=document.getElementById('imgPlaceHolder1').value;
	   var imgplaceholder2=document.getElementById('imgPlaceHolder2').value;

	    
		var theFinalImages = new Array();
		var a = '';
		// square layout

		if (selectedDesign.id == 1){		
			for(i=0;i<theImages.length;i++){
				a = $(theImages[i]).attr('src');
				theFinalImages.push(theImages[i]);
				theFinalImages.push(a);
				//alert(a);
				if ( a != imgplaceholder || a != imgplaceholder2 && pictureAdded == 0){
				    pictureAdded=1;
				}		
			}
		}else if (selectedDesign.id == 2){
		// scrap book layout				
			for(i=0;i<theImagesSB.length;i++){
				a=$(theImagesSB[i]).attr('src');
				theFinalImages.push(theImagesSB[i]);
				theFinalImages.push(a);			
				if ( a != imgplaceholder && pictureAdded == 0){
				    pictureAdded=1;
				}							
			}
		}else if (selectedDesign.id == 3){
		    for(i=0;i<theImagesFive.length;i++){
				a=$(theImagesFive[i]).attr('src');
				theFinalImages.push(theImagesFive[i]);
				theFinalImages.push(a);			
				if ( a != imgplaceholder && pictureAdded == 0){
				    pictureAdded=1;
				}							
			}
		}else if (selectedDesign.id == 4){
		    for(i=0;i<theImagesTree.length;i++){
				a=$(theImagesTree[i]).attr('src');
				theFinalImages.push(theImagesTree[i]);
				theFinalImages.push(a);			
				if ( a != imgplaceholder && pictureAdded == 0){
				    pictureAdded=1;
				}							
			}
		}else if (selectedDesign.id == 6){
		    for(i=0;i<theImagesTwo.length;i++){
				a=$(theImagesTwo[i]).attr('src');
				theFinalImages.push(theImagesTwo[i]);
				theFinalImages.push(a);
				if ( a != imgplaceholder && pictureAdded == 0){
				    pictureAdded=1;
				}
			}
		}else if (selectedDesign.id == 5){
		    for(i=0;i<theImagesOne.length;i++){
				a=$(theImagesOne[i]).attr('src');
				theFinalImages.push(theImagesOne[i]);
				theFinalImages.push(a);	
				if ( a != imgplaceholder && pictureAdded == 0){
				    pictureAdded=1;
				}							
			}
		}	
		//alert(pictureAdded);
		if (pictureAdded==1){
		   
		}
		else
		{
			ShowModalPhotoError();
		    return false;
		}
		var strResult = theFinalImages.join('|');		
		$('#hdnMiddlePictures').val(strResult);
		$('#hdnFrameColor').val(frameColorSelected.number);
		$('#hdnBackgroundColor').val(backgroundColorSelected.number);
		$('#hdnDesignID').val(selectedDesign.id);		
	}

	var confirmationDelete = null;
	
	function showConfirmationDelete(objID,iid){
	    if (null == confirmationDelete){
            // set up the modal
            confirmationDelete = $('#confirmationDelete').dialog({
                autoOpen: false,
                closeOnEscape: true,
                draggable: false,
                modal: true,
                position: 'center',
                resizable: false,
                height: 166,
                width: 522,
                dialogClass: 'confirmationDelete'
            });
            $('#btnDeleteNo').click(function(){
                confirmationDelete.dialog('close');
                return false;
            });
        }
        $('#btnDeleteYes').unbind('click');
        $('#btnDeleteYes').click(function(){
                deletePhoto(objID, iid);
	            confirmationDelete.dialog('close');
	            return false;
        });
        confirmationDelete.dialog('open');
	}

// ---------------- frame color -----------------------

var FRAME_COLOR_SIZE = 270; //266;
var frameColorScrollPosition = 0;

function frameColorPrevious(){
    if (frameColorScrollPosition == 0){
        return;
    }
    if (frameColorScrollPosition >= FRAME_COLOR_SIZE){
        frameColorScrollPosition -= FRAME_COLOR_SIZE;
    }else{
        frameColorScrollPosition = 0;
    }
    updateFrameColorArrows();
    $('#imgCollectionColorContainer').scrollTo(frameColorScrollPosition, 500, {axis:'x'});
}
function frameColorNext(){
    var theWidth = $('#ColorCollection').width();
    if (frameColorScrollPosition >= (theWidth-FRAME_COLOR_SIZE)){
        return;
    }
    
    if (frameColorScrollPosition < (theWidth-FRAME_COLOR_SIZE)){
        frameColorScrollPosition += FRAME_COLOR_SIZE;
    }else{
        frameColorScrollPosition = (theWidth-FRAME_COLOR_SIZE);
    }
    updateFrameColorArrows();
    $('#imgCollectionColorContainer').scrollTo(frameColorScrollPosition ,500, {axis:'x'});
}

function updateFrameColorArrows(){
    var theWidth = $('#ColorCollection').width();
    if(frameColorScrollPosition <= 0){
        document.getElementById('leftArrowFrameColor').src = '/images/tattoodle-your-photos/frameColorArrowLeft_gray.gif';
    }else{
        document.getElementById('leftArrowFrameColor').src = '/images/tattoodle-your-photos/frameColorArrowLeft.gif';
    }
    if(frameColorScrollPosition >= (theWidth-FRAME_COLOR_SIZE)){
        document.getElementById('rightArrowFrameColor').src = '/images/tattoodle-your-photos/frameColorArrowRight_gray.gif';
    }else{
        document.getElementById('rightArrowFrameColor').src = '/images/tattoodle-your-photos/frameColorArrowRight.gif';
    }
}

var frameColorSelected = {color: '',obj: null, number: 0};

function setFramecolorBoxOver(obj){
    var a = document.getElementById("OutColorPlaceHolder_" + obj);
    if (a.className && (a.className != 'ColorPlaceHolderSelected')){
        a.className='ColorPlaceHolderOver';
    }
}

function setFramecolorBoxOut(obj){
    var a = document.getElementById("OutColorPlaceHolder_" + obj);
    if (a.className && (a.className != 'ColorPlaceHolderSelected')){
        document.getElementById("OutColorPlaceHolder_" + obj).className='ColorPlaceHolderOut';
    }
}

var setFramecolorBoxSelected = function(obj){
	if (frameColorSelected.obj != null){
		frameColorSelected.obj.className = 'ColorPlaceHolderOut';
	}
	var a = document.getElementById('OutColorPlaceHolder_' + obj);
	a.className = 'ColorPlaceHolderSelected';
	frameColorSelected.obj = a;
	frameColorSelected.number = obj;
	frameColorSelected.color = document.getElementById('ColorPlaceHolder_' + obj).style.backgroundColor;
	// set the border color of the middle photos
	for(i=0;i<theImages.length;i++){
		$(theImages[i]).parent().css('border-color', frameColorSelected.color);
	}
	for(i=0;i<theImagesSB.length;i++){
		$(theImagesSB[i]).parent().css('border-color', frameColorSelected.color);
	}
	for(i=0;i<theImagesFive.length;i++){
		$(theImagesFive[i]).parent().css('border-color', frameColorSelected.color);
	}
	for(i=0;i<theImagesTree.length;i++){
		$(theImagesTree[i]).parent().css('border-color', frameColorSelected.color);
	}
	for(i=0;i<theImagesTwo.length;i++){
		$(theImagesTwo[i]).parent().css('border-color', frameColorSelected.color);
	}
	for(i=0;i<theImagesOne.length;i++){
		$(theImagesOne[i]).parent().css('border-color', frameColorSelected.color);
	}
}

// ------ background color ------

var BACKGROUND_COLOR_SIZE = 270; //266;
var backgroundColorScrollPosition = 0;

function backgroundColorPrevious(){
    if (backgroundColorScrollPosition == 0){
        return;
    }
    if (backgroundColorScrollPosition >= BACKGROUND_COLOR_SIZE){
        backgroundColorScrollPosition -= BACKGROUND_COLOR_SIZE;
    }else{
        backgroundColorScrollPosition = 0;
    }
    updateBackgroundColorArrows();
    $('#imgCollectionBgColorContainer').scrollTo(backgroundColorScrollPosition, 500, {axis:'x'});
}
function backgroundColorNext(){
    var theWidth = $('#BgColorCollection').width();
    if (backgroundColorScrollPosition >= (theWidth-BACKGROUND_COLOR_SIZE)){
        return;
    }
    
    if (backgroundColorScrollPosition < (theWidth-BACKGROUND_COLOR_SIZE)){
        backgroundColorScrollPosition += BACKGROUND_COLOR_SIZE;
    }else{
        backgroundColorScrollPosition = (theWidth-BACKGROUND_COLOR_SIZE);
    }
    updateBackgroundColorArrows();
    $('#imgCollectionBgColorContainer').scrollTo(backgroundColorScrollPosition ,500, {axis:'x'});
}

function updateBackgroundColorArrows(){
    var theWidth = $('#BgColorCollection').width();
    if(backgroundColorScrollPosition <= 0){
        document.getElementById('leftArrowBackgroundColor').src = '/images/tattoodle-your-photos/frameColorArrowLeft_gray.gif';
    }else{
        document.getElementById('leftArrowBackgroundColor').src = '/images/tattoodle-your-photos/frameColorArrowLeft.gif';
    }
    if(backgroundColorScrollPosition >= (theWidth-BACKGROUND_COLOR_SIZE)){
        document.getElementById('rightArrowBackgroundColor').src = '/images/tattoodle-your-photos/frameColorArrowRight_gray.gif';
    }else{
        document.getElementById('rightArrowBackgroundColor').src = '/images/tattoodle-your-photos/frameColorArrowRight.gif';
    }
}

var backgroundColorSelected = {color: '',obj: null, number: 0};

function setBackgroundcolorBoxOver(obj){
    var a = document.getElementById("OutBgColorPlaceHolder_" + obj);
    if (a.className && (a.className != 'ColorPlaceHolderSelected')){
        a.className='ColorPlaceHolderOver';
    }
}

function setBackgroundcolorBoxOut(obj){
    var a = document.getElementById("OutBgColorPlaceHolder_" + obj);
    if (a.className && (a.className != 'ColorPlaceHolderSelected')){
        document.getElementById("OutBgColorPlaceHolder_" + obj).className='ColorPlaceHolderOut';
    }
}

var setBackgroundcolorBoxSelected = function(obj){
    if (backgroundColorSelected.obj != null){
        backgroundColorSelected.obj.className = 'ColorPlaceHolderOut';
    }
    var a = document.getElementById('OutBgColorPlaceHolder_' + obj);
    a.className = 'ColorPlaceHolderSelected';
    backgroundColorSelected.obj = a;
    backgroundColorSelected.number = obj;
    backgroundColorSelected.color = document.getElementById('BgColorPlaceHolder_' + obj).style.backgroundColor;
    // set the background color of the middle photos
	$('#arrangePhotosWrapper').css('background-color', backgroundColorSelected.color);
}

// ------ edit IE move -------

var moveStep = 10;
var moveStepMax = 240;
function editorMoveUp(){
	if (jQuery.fn.translateY>-moveStepMax+moveStep){
		jQuery.fn.translateY -= moveStep;
	}else{
		jQuery.fn.translateY = -moveStepMax;
	}
	$("#imgEditor").transform(rotateAngle, 'abs', zoom);
}
function editorMoveRight(){
	if (jQuery.fn.translateX<moveStepMax - moveStep){
		jQuery.fn.translateX += moveStep;
	}else{
		jQuery.fn.translateX = moveStepMax;
	}
	$("#imgEditor").transform(rotateAngle, 'abs', zoom);
}
function editorMoveDown(){
	if (jQuery.fn.translateY<moveStepMax - moveStep){
		jQuery.fn.translateY += moveStep;
	}else{
		jQuery.fn.translateY = moveStepMax;
	}
	$("#imgEditor").transform(rotateAngle, 'abs', zoom);
}
function editorMoveLeft(){
	if (jQuery.fn.translateX>-moveStepMax+moveStep){
		jQuery.fn.translateX -= moveStep;
	}else{
		jQuery.fn.translateX = -moveStepMax;
	}
	$("#imgEditor").transform(rotateAngle, 'abs', zoom);
}

// ---------------- modal submit no picture ------------------------
var modalPhotoError = null;
function ShowModalPhotoError()
{	
		if (null == modalPhotoError){
			// set up the modal
			modalPhotoError = $('#photoError').dialog({
				autoOpen: false,
				closeOnEscape: true,
				draggable: false,
				modal: true,
				position: ['center',120],
				resizable: false,
				dialogClass: 'photoError',
				width: 521
			});
		}		
		
		modalPhotoError.dialog('open');
		
}
function closemodalPhotoError()
{
modalPhotoError.dialog('close');
}


// ---------------- modal example ------------------------
var modalExample = null;
var modalExampleSB = null;
var modalExampleFive = null;
var modalExampleTree = null;
var modalExampleTwo = null;
var modalExampleOne = null;

function ShowModalExample()
{
	if (selectedDesign.id <=1){
		if (null == modalExample){
			// set up the modal
			modalExample = $('#modalExample').dialog({
				autoOpen: false,
				closeOnEscape: true,
				draggable: false,
				modal: true,
				position: ['center',120],
				resizable: false,
				dialogClass: 'modalExample',
				width: 642
			});
		}		
		$('#modalExampleImage').html('<a href="#" onclick="modalExample.dialog(\'close\');return false;"><img src="/images/tattoodle-your-photos/spacer.gif" class="imgExampleTop" alt="" /><img src="' + document.getElementById('divImageExamplePath' + selectedDesign.id).innerHTML + '" alt="example" /></a>');
		modalExample.dialog('open');
	}else if (selectedDesign.id ===2){
		if (null == modalExampleSB){
			// set up the modal
			modalExampleSB = $('#modalExampleSB').dialog({
				autoOpen: false,
				closeOnEscape: true,
				draggable: false,
				modal: true,
				position: ['center',120],
				resizable: false,
				dialogClass: 'modalExampleSB',
				width: 642
			});
		}		 
		$('#modalExampleImageSB').html('<a href="#" onclick="modalExampleSB.dialog(\'close\');return false;"><img src="/images/tattoodle-your-photos/spacer.gif" class="imgExampleTop" alt="" /><img src="' + document.getElementById('divImageExamplePath' + selectedDesign.id).innerHTML + '" alt="example" /></a>');		
		modalExampleSB.dialog('open');
	}else if (selectedDesign.id ===3 ){
		if (null == modalExampleFive){
			// set up the modal
			
			modalExampleFive = $('#modalExampleFive').dialog({
				autoOpen: false,
				closeOnEscape: true,
				draggable: false,
				modal: true,
				position: ['center',120],
				resizable: false,
				dialogClass: 'modalExampleSB',
				width: 642
			});
		}		 
		$('#modalExampleImageFive').html('<a href="#" onclick="modalExampleFive.dialog(\'close\');return false;"><img src="/images/tattoodle-your-photos/spacer.gif" class="imgExampleTop" alt="" /><img src="' + document.getElementById('divImageExamplePath' + selectedDesign.id).innerHTML + '" alt="example" /></a>');		
		modalExampleFive.dialog('open');	
	}else if (selectedDesign.id ===4 ){
		if (null == modalExampleTree){
			// set up the modal
			
			modalExampleTree = $('#modalExampleTree').dialog({
				autoOpen: false,
				closeOnEscape: true,
				draggable: false,
				modal: true,
				position: ['center',120],
				resizable: false,
				dialogClass: 'modalExampleSB',
				width: 642
			});
		}		 
		$('#modalExampleImageTree').html('<a href="#" onclick="modalExampleTree.dialog(\'close\');return false;"><img src="/images/tattoodle-your-photos/spacer.gif" class="imgExampleTop" alt="" /><img src="' + document.getElementById('divImageExamplePath' + selectedDesign.id).innerHTML + '" alt="example" /></a>');
		modalExampleTree.dialog('open');	
	}else if (selectedDesign.id ===6 ){
		if (null == modalExampleTwo){
			// set up the modal
			
			modalExampleTwo = $('#modalExampleTwo').dialog({
				autoOpen: false,
				closeOnEscape: true,
				draggable: false,
				modal: true,
				position: ['center',120],
				resizable: false,
				dialogClass: 'modalExampleSB',
				width: 642
			});
		}		 
		$('#modalExampleImageTwo').html('<a href="#" onclick="modalExampleTwo.dialog(\'close\');return false;"><img src="/images/tattoodle-your-photos/spacer.gif" class="imgExampleTop" alt="" /><img src="' + document.getElementById('divImageExamplePath' + selectedDesign.id).innerHTML + '" alt="example" /></a>');
		modalExampleTwo.dialog('open');
	}else if (selectedDesign.id ===5 ){
		if (null == modalExampleOne){
			// set up the modal
			
			modalExampleOne = $('#modalExampleOne').dialog({
				autoOpen: false,
				closeOnEscape: true,
				draggable: false,
				modal: true,
				position: ['center',120],
				resizable: false,
				dialogClass: 'modalExampleSB',
				width: 642
			});
		}		 
		$('#modalExampleImageOne').html('<a href="#" onclick="modalExampleOne.dialog(\'close\');return false;"><img src="/images/tattoodle-your-photos/spacer.gif" class="imgExampleTop" alt="" /><img src="' + document.getElementById('divImageExamplePath' + selectedDesign.id).innerHTML + '" alt="example" /></a>');
		modalExampleOne.dialog('open');
	}
}

var selectedDesign = {obj:null, id:0}

function selectDesign(obj, id){
	// do a get for the middle section
	if (obj.src.indexOf('_on') > -1){
		return;
	}else{
		if (selectedDesign.obj != null){
			selectedDesign.obj.src = selectedDesign.obj.src.replace('_on.gif', '.gif');
		}
		var a = obj.src.length;
		obj.src = obj.src.substring(0,obj.src.length-4) + '_on.gif';
		selectedDesign.obj = obj;
		selectedDesign.id = id;
	}	
	var p1 = document.getElementById('middlePhotosSquare');
	var p2 = document.getElementById('middlePhotosSB');
	var p3 = document.getElementById('middle5Photos');
	var p4 = document.getElementById('middle3Photos');
	var p5 = document.getElementById('middle1Photos');	
    var p6 = document.getElementById('middle2Photos');
	if (id == 1){
		if(p1){p1.style.display='block';}
		if(p2){p2.style.display='none';}
		if(p3){p3.style.display='none';}
		if(p4){p4.style.display='none';}
		if(p5){p5.style.display='none';}
		if(p6){p6.style.display='none';}
	}else if(id==2){
		if(p1){p1.style.display='none';}
		if(p2){p2.style.display='block';}
		if(p3){p3.style.display='none';}
		if(p4){p4.style.display='none';}
		if(p5){p5.style.display='none';}
		if(p6){p6.style.display='none';}
	}else if(id==3){	
		if(p1){p1.style.display='none';}
		if(p2){p2.style.display='none';}
		if(p3){p3.style.display='block';}
		if(p4){p4.style.display='none';}
		if(p5){p5.style.display='none';}	
		if(p6){p6.style.display='none';}
	}else if(id==4){
		if(p1){p1.style.display='none';}
		if(p2){p2.style.display='none';}
		if(p3){p3.style.display='none';}
		if(p4){p4.style.display='block';}
		if(p5){p5.style.display='none';}	
		if(p6){p6.style.display='none';}
	}else if(id==5){
		if(p1){p1.style.display='none';}
		if(p2){p2.style.display='none';}
		if(p3){p3.style.display='none';}
		if(p4){p4.style.display='none';}
		if(p5){p5.style.display='block';}
		if(p6){p6.style.display='none';}
	}else if(id==6){
		if(p1){p1.style.display='none';}
		if(p2){p2.style.display='none';}
		if(p3){p3.style.display='none';}
		if(p4){p4.style.display='none';}
		if(p5){p5.style.display='none';}
		if(p6){p6.style.display='block';}
    }
}


function startUploadFlash(obj) {
//
//showprogres();
    document.getElementById('ui-dialog-title-modalUpload').innerHTML = document.getElementById('intploading').value;	    
	document.getElementById('formUploadUploading').style.display = 'block';
	    
  var imageUploader = document.getElementById('imageUploader');

  
}

function js_debug(paramName, paramValue)
{
    //console.log(paramName + ":" + paramValue);
}

/*
//Facebook pop up functions
var modalFacebook = null;
var modalErrors = null;
var FBContentLoadComplete=0;
var aid='';
var UploadedPictures=0;
MAXPHOTO = 8;

var FBShowContent=0;
function loadModalComplete() {
    if (FacbookBTNClick == 1) {
        document.getElementById('formUploadFBcontent').style.display = 'none';
        document.getElementById('albumContainer').style.display = 'block';
         if (UploadedPictures!=MAXPHOTO) {
              clearUploadFormFB();
              }
              
        //if (document.getElementById("modalUploadUploadFB")) {
            
            if (aid != '') {
                document.getElementById("albumContainer").style.display = 'block';
                document.getElementById("picContainer_" + aid).style.display = 'none';
            }
            if (document.getElementById("bottomdivPic")) {
                document.getElementById("bottomdivPic").style.display = 'none';
            }
            //document.getElementById("TopText").style.display='none';
            
            //console.log(document.getElementById("hdnexistingPicture").value);
      //  }
       // else {
       //     showError('Tattoodle Facebook Upload Error', errorFBmessage1)
            // console.log('enter');

       // }
    }
    FBContentLoadComplete = 1;
}

function ShowModalUploadFacebook()
{
//console.log(UploadedPictures);
    if (FacbookBTNClick == 1) {
        //console.log('enter2');
       
            if (null == modalFacebook) {
                // set up the modal
                modalFacebook = $('#popupFacebook').dialog({
                    autoOpen: false,
                    closeOnEscape: true,
                    draggable: false,
                    modal: true,
                    position: ['',155],
                    resizable: false,
                    dialogClass: 'modalExampleFB',
                    width: 725                               
                });
            }            
            //$('#popupFacebook').dialog('option', 'maxHeight', 100);
            document.getElementById('hdnUploadSelectedFB').value = 'fb';
            modalFacebook.dialog('open');
            document.getElementById('albumContainer').style.display = 'none';
            document.getElementById('formUploadFBcontent').style.display = 'block';
    }
}
function showError(title,msg) {
    if (null == modalErrors) {
        // set up the modal
        modalErrors = $('#FBErrors').dialog({
            autoOpen: false,
            closeOnEscape: true,
            draggable: false,
            modal: true,
            position: 'center',
            resizable: false,
            dialogClass: 'modalExample',
            width: 642
        });
    }
    document.getElementById('ui-dialog-title-FBErrors').innerHTML = title;
    document.getElementById('errormessage').innerHTML = msg;
    //clearUploadFormFB();
    //document.getElementById('hdnUploadSelectedFB').value = 'fb';
    modalErrors.dialog('open');
    
    //uploadCompletedFB(result, msg);
}

function closeUploadFB() {
    //clear picture for upload
    selectedPictureForUpload = '';
    modalFacebook.dialog('close');
}
	
    
	
	
	      var userFBFirstName='';
        var userFBLastName='';
	function clearUploadFormFB(){
	    document.getElementById('ui-dialog-title-popupFacebook').innerHTML = userFBFirstName + " "+ userFBLastName +"&nbsp;Facebook Albums";
	    document.getElementById('formFBUpload').style.display = 'block';
	    document.getElementById('formUploadUploadingFB').style.display = 'none';
	}
	function uploadCompletedFB(result, msg){

	    if (result != 0) {
	        //console.log('sdasd');
	        //console.log("sss");
	        document.getElementById('modalLoadingAnimationFB').innerHTML = msg;
	        document.getElementById('formUploadingButtonsFB').style.display='block';
	    }
	    else{
	    
	        closeUploadFB();
	        $.get('/_api/tattoodle-your-photos-api.aspx?a=getPhotosUp&zz=' + (new Date().getTime()), null, function(result){
	            topDraggables.draggable('destroy');
	            $('#imgCollectionImages').html(result);
	            SetTopDraggables();
	        }, 'html');
	        document.getElementById('hdnUploadSelectedFB').value="";
	    }
	}

    function backToUpload(){
	    clearUploadFormFB();
	    document.getElementById('formUploadUploadingFB').style.display = 'none';
	    document.getElementById('formFBUpload').style.display='block';
	    document.getElementById('formUploadingButtonsFB').style.display='none';
	    document.getElementById('modalLoadingAnimationFB').innerHTML = '<img src="/images/tattoodle-your-photos/Loading-Image-TattoodlePhoto.gif" />';
	    document.getElementById('hdnUploadSelectedFB').value="";
	}
    function setBoxBorderOn(obj)
    {
        document.getElementById("OutColorPlaceHolder_" + obj).className='OverColorPlaceHolder';
    }
    function setBoxBorderOff(obj)
    {
        document.getElementById("OutColorPlaceHolder_" + obj).className='OutColorPlaceHolder';
    }

    function FBUploadOnOver(obj)
    {
    document.getElementById("divFBpicture_" + obj).className='divFBpictureOnOver';
    }
    function FBUploadOnOut(obj)
    {
    document.getElementById("divFBpicture_" + obj).className='divFBpictureOnOut';
    }
    var lastchecked=-1;
    function FBUploadClick(obj,obj2)
    {
        //if (lastchecked==obj)
        //{
        //    if (document.getElementById("cboFBpicture_" + obj).checked==true)
         //   {
        //        document.getElementById("cboFBpicture_" + obj).checked=false;
       //         document.getElementById('hdnUploadSelectedFB').value="";
        //        lastchecked=-1;
       //     }
       //     else
       //         {
       //         document.getElementById("cboFBpicture_" + obj).checked=true;                        
                document.getElementById("hdnUploadSelectedFB" ).value=obj2;
                lastchecked=obj;
        //    }
       // }
//        else if (lastchecked==-1)
//        {       
//         document.getElementById("cboFBpicture_" + obj).checked=true; 
//         document.getElementById("hdnUploadSelectedFB" ).value=obj2;
//         lastchecked=obj;
//        }
    }
   
var elementsSelected=''; 
var uploadremaining=0;
var clicuploadRemaining=0;
function showAlbumPictures(obj, obj2) {
    document.getElementById("modalUploadUploadFB").src = "/images/tattoodle-your-photos/FBcontinuebtn.gif"
    //if (document.getElementById('albumPicture_' + obj2).innerHTML === 'No Pictures') {
    //    showError('Tattoodle - Facebook Upload Error', 'Facebook reported that you haven\'t uploaded any photos to your album.')
   // } else {    
        uploadremaining = MAXPHOTO - UploadedPictures;
        clicuploadRemaining = uploadremaining;
        document.getElementById("TopText").innerHTML = 'Tattoodle has a limit of ' + MAXPHOTO + ' photos.You previously uploaded ' + UploadedPictures + ' photos. So, you can remove some<br />of your previous photos or select no more than <div id="moreremaining" style="display:inline;">' + clicuploadRemaining + '</div>&nbsp;photos to upload from Facebook.'

        document.getElementById("albumContainer").style.display = 'none';
        document.getElementById("picContainer_" + obj).style.display = 'block';
        document.getElementById("bottomdivPic").style.display = 'block';
        //document.getElementById("TopText").style.display='block';
        aid = obj;
        //"5893088398792935368","5893088398792933620",
        var picturesSelected = elementsSelected.split(',');
        // console.log( picturesSelected.length);
        for (i = 0; i < picturesSelected.length; i++) {
            if ('' === picturesSelected[i]) { continue; }
            document.getElementById("divPicSelFB_" + picturesSelected[i]).className = 'FBpictures';
            document.getElementById("imgFB_" + picturesSelected[i]).style.display = 'none';
            // console.log ( picturesSelected[i] );
        }
  //  }
}
function ShowAlbums()
{
document.getElementById("modalUploadUploadFB").src="/images/tattoodle-your-photos/FBcontinuebtn.gif"
          //clear picture for upload
	        selectedPictureForUpload='';
	        //
    document.getElementById("albumContainer").style.display = 'block';
	    document.getElementById("picContainer_"+aid).style.display='none';
	    document.getElementById("bottomdivPic").style.display='none';
	    //document.getElementById("TopText").style.display='none';
	    
}

var selectedPictureForUpload='';
//var apicture='';
function selectPictureFB(obj2,obj3)
{
//console.log("enter " +selectedPictureForUpload);
  if (document.getElementById("imgFB_"+obj2).style.display=='none')
  { 
    if (clicuploadRemaining!=0)
    {
      clicuploadRemaining--;
      if (clicuploadRemaining==uploadremaining){
        document.getElementById("modalUploadUploadFB").src="/images/tattoodle-your-photos/FBcontinuebtn.gif" 
      }
      else
      {
        document.getElementById("modalUploadUploadFB").src="/images/tattoodle-your-photos/FBcontinuebtnselected.gif" 
      }
      //document.getElementById("moreremaining").innerHTML=clicuploadRemaining;  
      document.getElementById("divPicSelFB_"+ obj2).className = 'FBpicturesContainerSelected';
      document.getElementById("imgFB_"+obj2).style.display='block';
      elementsSelected+=''+obj2+',';
      selectedPictureForUpload +=''+ obj3+',';   
      selectedPictureForUpload=selectedPictureForUpload;
      
    }
    else if (clicuploadRemaining==0 && UploadedPictures!= MAXPHOTO)
    {
        showError('Tattoodle - Facebook Upload Error', errorFBmessage2)
    }
    else if (UploadedPictures==MAXPHOTO)
    {
        showError('Tattoodle - Facebook Upload Error', errorFBmessage3)
    }
  }
  else
  {
    clicuploadRemaining++;
    if (clicuploadRemaining==uploadremaining){
        document.getElementById("modalUploadUploadFB").src="/images/tattoodle-your-photos/FBcontinuebtn.gif" 
      }
      else
      {
        document.getElementById("modalUploadUploadFB").src="/images/tattoodle-your-photos/FBcontinuebtnselected.gif" 
      }
    //document.getElementById("moreremaining").innerHTML=clicuploadRemaining; 
    document.getElementById("divPicSelFB_"+ obj2).className = 'FBpictures';
    document.getElementById("imgFB_"+obj2).style.display='none';
   selectedPictureForUpload = selectedPictureForUpload.replace(obj3+',', "");
    //console.log("enter" + a);
  }
  //console.log("end "+selectedPictureForUpload);
  //console.log(elementsSelected);
}

function startUploadFB(){
    if (clicuploadRemaining==uploadremaining){ 
           showError('Tattoodle - Facebook Upload Error', errorFBmessage5)
     return false;
	    }
	    else
	    {	    
	     document.getElementById("hdnUploadSelectedFB" ).value=selectedPictureForUpload;    
	    //if ('' == document.getElementById('filePhoto').value){return false;}
	    //document.getElementById('ui-dialog-title-modalUpload').innerHTML = 'Loading Photo';
	    document.getElementById('formUploadingButtonsFB').style.display='none';
	      document.getElementById('modalLoadingAnimationFB').innerHTML = '<img src="/images/tattoodle-your-photos/Loading-Image-TattoodlePhoto.gif" />';
	    document.getElementById('formFBUpload').style.display = 'none';
	    document.getElementById('formUploadUploadingFB').style.display = 'block';
	    return true;
	    
	    }
	}

	var FacbookBTNClick = 0;
	var passGetUser = 0;
	var loadcomplete=0;
	var errorFBmessage1='<img src="/images/tattoodle-your-photos/FB_error.jpg" style="float: left; margin-left: 61px; margin-bottom: 29px; margin-right: 3px;" alt="error"/>Facebook reported that you haven\'t created any albums;<br />please create an album first.';
	var errorFBmessage2='<img src="/images/tattoodle-your-photos/FB_error.jpg" style="margin: -3px 3px 29px 37px; float: left;" alt="error"/><div style="text-align:left;">Oops!  You have already selected the maximum number of photos for upload.</div><div style="clear:both;">Tattoodle allows you to store a maximum of 8 photos at a time to use on our site.<br />  Selecting another photo is not allowed as it would exceed this number.</div>';
	var errorFBmessage3='<img src="/images/tattoodle-your-photos/FB_error.jpg" style="margin: -3px 3px 29px 101px; float: left;" alt="error"/><div style="text-align:left;">Oops!  You have already uploaded 8 photos to Tattoodle;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this is the maximum number allowed.</div><div style="clear:both;">Tattoodle allows you to store a maximum of 8 photos at a time to use on our site.<br />  If you wish to upload more, you must first delete some you have already uploaded.</div>';
	var errorFBmessage4='<img src="/images/tattoodle-your-photos/FB_error.jpg" style="margin: -3px 3px 29px 39px; float: left;" alt="error"/><div style="text-align:left;">Oops!  Facebook reported that there are no photos in your Facebook Albums.</div><div style="clear:both;">Please login to Facebook for more information.</div>';
	var errorFBmessage5='<img src="/images/tattoodle-your-photos/FB_error.jpg" style="margin: -3px 3px 29px 123px; float: left;" alt="error"/><div style="text-align:left;">Oops!  You haven\'t selected any photos to upload. </div><div style="clear:both;">Please select photos by clicking on them, then click the Continue button to upload.</div>';
	//var firstHit = 0;
function FBloginClick(obj) {
UploadedPictures = document.getElementById("hdnexistingPicture").value;
    if (obj == 1) {
       // console.log('aaaa');
        FacbookBTNClick = 1;
    } else {
    //console.log('ddd');
    if (FBContentLoadComplete === 1) {
       //console.log('eee');
            if (noalbum == 1) {
                //closeUploadFB();
                showError('Tattoodle - Facebook Upload Error', errorFBmessage1)
            }
            else {
              if(loadcomplete==1)
              if (UploadedPictures==MAXPHOTO) {
                showError('Tattoodle - Facebook Upload Error', errorFBmessage3)
              }
              else {
               ShowModalUploadFacebook();
                loadModalComplete();
              }               
            }
            
        }
      else if (passGetUser == 2) {
       // console.log('dfff');
            if (noalbum == 1) {
                //closeUploadFB();
                showError('Tattoodle - Facebook Upload Error', errorFBmessage1)
            }
            else {
            if (UploadedPictures==MAXPHOTO) {
                showError('Tattoodle - Facebook Upload Error', errorFBmessage3)
              }
              else {
               FacbookBTNClick = 1;
                ShowModalUploadFacebook();
                loadModalComplete();
              }                             
            }
        
        }
        else if (loadcomplete == 1) {
        //console.log('dfff');
            if (noalbum == 1) {
                //closeUploadFB();
                showError('Tattoodle - Facebook Upload Error', errorFBmessage1)
            }
            else {
            //console.log(UploadedPictures);
             if (UploadedPictures==MAXPHOTO) {
                showError('Tattoodle - Facebook Upload Error', errorFBmessage3)
              }
              else {
                FacbookBTNClick = 1;
                ShowModalUploadFacebook();
                loadModalComplete();
                }
            }
        
        }
        
        else
        {
           // console.log('eewwwwe');
            FacbookBTNClick = 1;
            
            if (noalbum == 1) {
                //closeUploadFB();
                showError('Tattoodle - Facebook Upload Error', errorFBmessage1)
            }
            else {
             if (UploadedPictures==MAXPHOTO) {
                showError('Tattoodle - Facebook Upload Error', errorFBmessage3)
              }
              else {
                ShowModalUploadFacebook();
                }
            }
        }
    }
}
//Facebook functions end
//*/

