// Functionality for showing the popup windows off of the action bar
function getposOffset(overlay, offsettype)
{
	var totaloffset=(offsettype=="left")? overlay.offsetLeft : overlay.offsetTop;
	var parentEl=overlay.offsetParent;
	while (parentEl!=null /*&& parentEl.getStyle('position') != 'relative'*/)
	{
		totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl=parentEl.offsetParent;
	}
	return totaloffset;
}

var ACTION_BAR =
{
  //-----------------------------------------------------------------------------
  // Desc:        Function to delete an item from the actionBar
  deleteItem: function(booth_id, item_id, item_name)
  {
      // If we're given an item, call the new_item_remove_xhr AJAX method to remove it from our items table
      if (item_id > -1)
      {
        titleEl = $j('#itemlist ul#grid_block_item_' + item_id + ' .itemTitle');
        item_title = (titleEl.text() != '' ? titleEl.text() : "this nameless item");
        confirmResult = confirm("You really wanna delete " + item_title + "?");
        if(confirmResult)
        {   
          showWaitPanel('#boothItems');
        
          new Ajax.Updater(
              'itemlist',
              '/booths/' + booth_id + '/items/' + item_id,
              { 
                asynchronous:true, 
                evalScripts:true, 
                method:'delete',
                onComplete: function() { 
                  hideWaitPanel('#boothItems'); 
                }
              });
        }
      }
  },
  
  //-----------------------------------------------------------------------------
  // Desc:        Function to delete an item from the actionBar
  duplicateItem: function(booth_id, item_id)
  {
      // If we're given an item, call the new_item_remove_xhr AJAX method to remove it from our items table
      if (item_id > -1)
      {
        showWaitPanel('#boothItems');
        
        new Ajax.Updater(
            'itemlist',
            '/booths/' + booth_id + '/items/' + item_id + '/duplicate',
            { 
              asynchronous:true, 
              evalScripts:true, 
              method:'post',
              onComplete: function() { 
                hideWaitPanel('#boothItems'); 
              }
            });
      }
  }

  //-----------------------------------------------------------------------------
  // Desc:        Function to make an AJAX request that returns a JSON object used to populate 
  //              the new item form
  // Parameters:  event     Dunno
  /*editItem: function(booth_id, item_id)
  {
    // If we have an item and were given a function to call to populate the new item form with
  	if (item_id > -1)
    {
        showWaitPanel('#itemlist');
        
        new Ajax.Updater(
            'newItemForm',
            '/booths/' + booth_id + '/items/' + item_id + '/edit',
            { 
              // parameters: $H({ item_id: this.item_id }), 
              asynchronous:true, 
              evalScripts:true,
              method:'get',
              onSuccess: function()
              {
    			      closeAllActionPanels();
              },
              onComplete: function()
              {
                StateManager.setState("items/" + item_id + "/main_form");
                displayEditItemWindow();
                captureFormStartingState();
                hideWaitPanel('#itemlist');
              }
            });            
                		  
	   }
  }*/
};

//-----------------------------------------------------------------------------
// open action_layer's action_panel by showing it and hiding the action_bar
function openActionPanel(actionLayerElID)
{
	closeAllActionPanels();
   
  var actionLayerEl = $j('#' + actionLayerElID);

	actionLayerEl.find('.action_panel').addClass('single_show');
	actionLayerEl.find('.action_bar').addClass('panel_hide');
}

//-----------------------------------------------------------------------------
// seeks out action_panels that are shown (using .single_show) and closes them
function closeAllActionPanels()
{
	$j('.action_panel').filter('.single_show').each(
    function() 
    { 
      closeActionPanel($j(this).parents('.action_layer').attr('id')); 
    });
}

//-----------------------------------------------------------------------------
// close action_layer's action_panel by hiding it and allowing the action_bar to be shown
function closeActionPanel(actionLayerElID)
{
  var actionLayerEl = $j('#' + actionLayerElID);
  
	actionLayerEl.find('.action_bar').removeClass('panel_hide');
	actionLayerEl.find('.action_panel').removeClass('single_show');
}



//-----------------------------------------------------------------------------
// Called after an item has been successfully added without killing new item form
function addItemAddedSuccessfully(oldItemName)
{
	$j("#NewItemInfoMessageContainer span#NewItemInfoMessage").text(oldItemName + ' added or saved successfully!');
	$j("#NewItemInfoMessageContainer").show();
	$j("#NewItemInfoMessageContainer span#NewItemInfoMessage").show();

  // Other maintenance to clean up the form and get it back to its original state.
	StateManager.setState("items/" + $j('#stateReturnToID').val() + "/main_form");
  //captureFormStartingState();
  //$('item_title').focus();
}

//-----------------------------------------------------------------------------
function adjustTextarea(textarea, collapsed) {
  var lines = textarea.value.split("\n");
  var count = lines.length;
  lines.each(function(line) { count += parseInt(line.length / 70); });

  var rows = parseInt(collapsed / 20);

  if (count > rows) {
    $j('#wysiwyg_link').fadeIn('fast');
  }

  if (count <= rows) {
    $j('#wysiwyg_link').fadeOut('fast');
  }
};

//-----------------------------------------------------------------------------
// Save the serialized state of the form into a global variable that we'll check against
// if the form is canceled to see if there were any changes.
function captureFormStartingState()
{
  var itemForm = $('item_fields_form');
  if (itemForm)
  {
    // Record values on form when it's opened so we know whether we're going to need to confirm the user's possible cancelation  
    gStartingForm = itemForm.serialize();
  }
  else
  {
    gStartingForm = null;
  }
}

//-----------------------------------------------------------------------------
function hideShowBoothImageGalleryHintArea()
{
	$j('#NewItemInfoMessageContainer').slideToggle("normal", function()
	{
		set_json_subcookie('_it_se', 'sbigha', $j(this).is(":visible"));
	});
}

//-----------------------------------------------------------------------------
// Don't allow naughty keys or decimals in price fields
function restrictPriceInput(e, regExp)
{
	var keyCode = !e.charCode ? e.which : e.charCode;
	var key = String.fromCharCode(keyCode);
	
	if (e.ctrlKey)
	{
		if (key == 'v')
		{	// Prevent pasting
			e.preventDefault();
		}
	}
	else if (keyCode != 0 && !regExp.test(key))	// Not a digit or backspace
	{																													// keyCode 0 is special keys like delete, home, arrows, etc.
		e.preventDefault();
	}
}

//-----------------------------------------------------------------------------
function showShippingFields(shippingOption, shippingFixedArr, shippingCalcArr)
{
  if (shippingOption == shippingFixedArr[0]) {
    $j('#' + shippingFixedArr[1]).show();
    $j('#' + shippingCalcArr[1]).hide();
  }
  else if(shippingOption == shippingCalcArr[0]) {
    $j('#' + shippingCalcArr[1]).show();
    $j('#' + shippingFixedArr[1]).hide();
  }
  else {
    $j('#' + shippingFixedArr[1]).hide();
    $j('#' + shippingCalcArr[1]).hide();
  }
    
}

//-----------------------------------------------------------------------------
function beforeEditItemFormSubmit(text)
{
  document.location.hash = "default";
  $j('a.tooltip').unbind();
  $j('#addItemFooter .bottomButton').attr('disabled', 'disabled'); 
	showItemFormWait(text);
}

//-----------------------------------------------------------------------------
function afterEditItemFormSubmit()
{
	$j('#addItemFooter .bottomButton').attr('disabled', 'enabled'); 
	hideItemFormWait();
}

//-----------------------------------------------------------------------------
function categoryBrowseClicked(){
	$j('#categoryBrowser').slideToggle('slow');
}

//-----------------------------------------------------------------------------
// Give the user some life affirming statistics on how well they're doing posting
function getPostingTimeString(timeItemCreatedString, bestTimeSeconds, yourAverageTimeSeconds)
{
  var returnStr = "";
  try {
	  //var itemStartEditTime = Date.parseDate(timeItemCreatedString, "Y-m-d H:i:s");
	  //var now = new Date();
	  //var diff = now.getTime() - itemStartEditTime.getTime();
	  //diff += 7*60*60*1000; // move forward seven hours, time zone diff between us and slicehost
	  //var oneSecond = 1000;
    //var totalSeconds = diff / oneSecond;
    //var todaysFastest = (!bestTimeSeconds || (totalSeconds < bestTimeSeconds) ? totalSeconds : bestTimeSeconds);
    //var yourAverage = (!yourAverageTimeSeconds ? totalSeconds : yourAverageTimeSeconds);
     
    //if(totalSeconds < bestTimeSeconds) {
    //  returnStr += "<blink>Congratulations!  You are the day's fastest item poster so far!</blink><br />"
    //}
    //returnStr += "Time to create this item: <strong>" + Math.floor(totalSeconds/60) + " minutes " + Math.floor(totalSeconds%60) + " seconds</strong><br />";
    if(yourAverageTimeSeconds) {
      yourAverage = yourAverageTimeSeconds;
      returnStr += "Your average posting time: <strong>" + Math.floor(yourAverage/60) + " minutes " + Math.floor(yourAverage%60) + " seconds</strong><br />";
      if(Math.floor(yourAverage/60) <= 3) { 
        returnStr += "Snappy!";
      }
      else if(Math.floor(yourAverage/60) <= 5) {
        returnStr += "Pretty quick!";
      }
    }
    else {
      returnStr += "Please wait..."
    }
    // returnStr += "Today's fastest: <strong>" + (todaysFastest/oneMinute) + ":" + (todaysFastest%oneMinute) + "</strong>";
  }
  catch(err) {
    returnStr = "Saving item...";
  } 
  return returnStr;
}

//-----------------------------------------------------------------------------
function showItemFormWait(text)
{
  passText = (text ? text : "Please Wait...");
  $j('#item_shipping_id').hide();
  showWaitPanel('#modalItemWindow', passText, 3); // 3 is the hack width adding... the form is somehow 3 pixels wider than its .outerWidth() call purports
}

//-----------------------------------------------------------------------------
function hideItemFormWait()
{
  $j('#item_shipping_id').show();
  hideWaitPanel('#modalItemWindow');
}
	
//-----------------------------------------------------------------------------
function quantityBoxChecked(jqCheckboxElement)
{
  if(jqCheckboxElement && jqCheckboxElement.get(0) && !jqCheckboxElement.get(0).checked) {
    $j('input#item_quantity').val(1);
  }
}

//-----------------------------------------------------------------------------
function bindNIFMovingElements() {
	$j('fieldset#data input.browse, #edit_item_container input.browse').bind('click',function(){
		categoryBrowseClicked();
	});

	$j('#item_shipping_id').bind('change',function(){
		var sp = $j('#ShippingPrice');
		(this.selectedIndex===1)?sp.show():sp.hide();
	});
	$j('#show_quantity').bind('click',function(){ //using vis instead of show so floated fieldsets don't resize and jump
		$j('#QuantitySpanID').css('visibility',(this.checked===true)?'visible':'hidden');
	});
	$j('#item_freebie').bind('click',function(){
		var p = $j('#item_price');
		(this.checked===true)?$j(p).attr('disabled','disabled'):$j(p).attr('disabled','');
	});
}

//-----------------------------------------------------------------------------
// All used by the modal new item form 
function bindStaticModalFunctions(){
	$j('h4 a').bind('click',function(){
		var that = this;
		$j('#advancedOptions').slideFadeToggle(function(){
			$j(that).css('background-position',$j(this).is(':visible')?'0 -14px':'0 -14px');
			set_json_subcookie('_it_se', 'siao', $j(this).is(':visible'));
		});
		return false;
	});


	bindNIFMovingElements();
	bindImageElements();
	bindFileUploadInputs();
	
	$j('#modalCancel').bind('click',function(){
			$j('#modalButtons').hide();
			$j('#modalCancelConfirm').show();
			return false;
		});	    
	$j('#modalNotCancel').bind('click',function(){
			$j('#modalButtons').show();
			$j('#modalCancelConfirm').hide();
			return false;
		});
		
	$j('#modalItemWindow').jqmAddClose($j('#modalAbsCancel'));
}


//-----------------------------------------------------------------------------
function boothGalleryImageParams()
{
	var imgIds = '';
	$j("div#modalGallery ul#pictureslots li img").each(function(){
		if($j(this).attr('src').indexOf('button_upload_picture_85x70.jpg')===-1){
			imgIds+= $j(this).parent()[0].id + "=" + $j(this).attr('id') + "&";
		}
	});
	return imgIds;
}

//-----------------------------------------------------------------------------
function closeItemGuessWindow() 
{
 $j('#itemGrabberContainerDiv').parent().hide().html('Looking up items similar to yours...'); 
}

//-----------------------------------------------------------------------------
function respondToTraitJson(eval_json, category_id) {
  if(eval_json) {
  	$j('#full_category_name_for_traits').html(eval_json["full_category_name"]);
	}

  if(!eval_json || (eval_json["has_traits"] == false)) {
    traitNoneFound();
  } 
  else if(eval_json["has_traits"]) {
    traitHideAll();
    if(elementExists("traitShowTraits")) {
			$j('#traitLookup').show();
			$j.ajax({ type: "POST", url: '/categories/populate_traits',
				data: "id=" + category_id,
				complete: function(response) {
					$j('#traitLookup').hide();
					$j('#trait_container').html(response.responseText);
				}
			}); // ajax request
		}
		else {
			$j('.traitShowElement').show();
			trait_profile_list = eval_json["trait_profiles"];

			// Check if there are trait profiles in this category to populate our select input with...
			if(trait_profile_list && trait_profile_list.length > 0) {
				$j('#traitShowProfile').show();
				$j('#trait_profile_id').find('option').remove(); // Remove any old options from list, then add our new options
				for(i=0;i<trait_profile_list.length;i++) {
					$j('#trait_profile_id').addOption(trait_profile_list[i][0], trait_profile_list[i][1]);
				}
				$j('#trait_profile_id').attr('selectedIndex', 0); // (-1);
			}
		}
  }
}

//-----------------------------------------------------------------------------
function categoryUpdateTraits(category_id, the_url) {
  if(!category_id) { 
    traitNoneFound();
    return;
  }
  
  $j.ajax({
    type: "POST",
    url: the_url,
    data: "id=" + category_id,
    beforeSend: function() {
      traitHideAll();
      $j('#traitLookup').show();
    },
    success: function(json) {
      eval_json = eval(json);
      respondToTraitJson(eval_json, category_id);
    },
    complete: function() {
      $j('#traitLookup').hide();
    }
  }); // ajax request
}  // change 

//-----------------------------------------------------------------------------
// Hide all of the li's that are used to give trait information
function traitHideAll() {
  $j('#traitInitialShowElement, #traitShowTraits, .traitShowElement, #traitShowProfile, #traitNoneFound, #traitLookup').hide();
 }

//-----------------------------------------------------------------------------
function traitNoneFound() {
  traitHideAll();
  $j('#traitNoneFound').show();
}

//-----------------------------------------------------------------------------
function applyTraitComplete(response) {
	eval_json = eval(response);
	$j('#apply_profile_spinner').hide(); 
	$j('#traitShowProfile').html(eval_json["message"]);
	if(eval_json["count"]) {
	  $j('#traitCount').html(eval_json["count"] + " traits");
	}
}


//-----------------------------------------------------------------------------
// For use in future examples only.  
/*function ajaxEditCall(item_id, populateCallback, postPopulateCallback)
{
  // If we have an item and were given a function to call to populate the new item form with
	if (item_id > -1 && populateCallback)
  {
    // Create an AJAX request object that will call the booth's get_item_data method 
    new Ajax.Request('/booths/get_item_data/',
    {
	    // Parameterize said object with item to be populated, and format of AJAX request
		  parameters: $H({ id: item_id }),
		  requestHeaders: { Accept: 'application/json' },
		  onSuccess: function(transport)
		  {
		    // Parse the JSON returned by the AJAX
  			var json = transport.responseText.evalJSON(false);
  
        // Populate new item form with said JSON
  			populateCallback(json);
  
  		  if(postPopulateCallback)
        {
          postPopulateCallback();
        }
	    }
	  });
   }
}
*/

//-----------------------------------------------------------------------------
// Called when a state of the add item page is being revisited, and the add item
// page content needs to be updated for the state that is being revisited.
// Params:
//  state_id => The descriptive ID of the state to revisit (e.g.: "items/3/main_form")
//  remote_call_string => The remote ajax call that should be made to update the 
//                        correct booth, but defaulted to item 0 and going_to as
//                        "UNKNOWN", both of which should be replaced with the 
//                        correct targets.
function handleStateRevisit(state_id, remote_call_string)
{
  // Determine which item_id and going_to destination we are interested in
  var match = /^items\/(\d+)\/([\w_]+)$/.exec(state_id);
  if (match != null && match.length == 3)
  {
    // Replace the going_to param with the appropriate state
    remote_call_string = remote_call_string.replace(/going_to=UNKNOWN/, 'going_to=' + escape(match[2]));

    // Replace the edit_item_id param with the appropriate item id
    remote_call_string = remote_call_string.replace(/edit_item_id=0/, 'edit_item_id=' + match[1]);

    // Replace the escaped HTML stuff
    remote_call_string = remote_call_string.replace(/amp;/, '&');
    
    // If window content is empty, 
    if ( $('modalContent').empty() )
    {
      // Setup the jqModal window to load
      remote_call_string = "$j('#modalItemWindow').jqmSetAjax('" + remote_call_string + "').jqmSetPost('true').jqmShow(); showItemFormWait(); "
    }
    else
    {
      remote_call_string = "showItemFormWait(); new Ajax.Updater('modalContent','" + remote_call_string + "', {asynchronous:true, evalScripts:true, onComplete: function(e) { hideItemFormWait(); } });"
      // 'evalScripts:true, onComplete: function(e) { captureFormStartingState(); displayEditItemWindow(); }');
    }
    
    // TODO:
    // eval is quite expensive, so we will cache off the eval-ed version
    // of the Ajax call JS to avoid evaling it again in the near future
    eval(remote_call_string);
  }
  else
  {
    //closeItemWindow();
  }
}


//-----------------------------------------------------------------------------
function startNewItemPageSwap()
{
	spinNewItemPageTop();
}

//-----------------------------------------------------------------------------
function spinNewItemPageTop()
{
  var spinner = $('page_swap_spinner');
  
  if (spinner != null)
  {
    spinElement(spinner);
  }
}

//-----------------------------------------------------------------------------
function stopNewItemPageSpinner()
{
  var spinner = $('page_swap_spinner');
  
  if (spinner != null)
  {
    stopSpinElement(spinner);
  }
}


function galleryDragDrop(){
	//gallery draggable images
	$j("div#modalGallery div ul li img").each(function(){
		$j(this).draggable({helper:'clone',opacity:0.3,zIndex:99999});
	});
	
	//gallery droppable images
	$j("div#modalGallery ul#pictureslots li").each(function(){
		$j(this).droppable({
			accept: "img",
			hoverClass: 'droppable-hover',
			drop: function(ev, ui) {
				$j(this).children('img').attr('src',$j(ui.draggable).attr('src')).attr('id',$j(ui.draggable).attr('id')).draggable({helper:'clone',opacity:0.3,zIndex:99999});
			}
		});
	});	
	
	$j("div#modalGallery").droppable({
		accept:'img.galleryThumb',
		drop:function(ev, ui){
			$j(ui.draggable).attr('src','/images/button_upload_picture_85x70.jpg');
	}});
	
	
}


// JavaScript Document that is included in Bonanzle/app/views/layouts/booths.rhtml

// Manager functionality for generating and populating booth pickup times in advanced options
BOOTH_PICKUP_TIMES_MANAGER =
{
  // Take care, as pickupTime and pickupDuration are hard-coded into the booth interpretation method
  // so it can decipher these pair o' params
  nextIDToUse : 0,
  hiddenElementDiv : null,
  calendarSpanElement : null,
   
  //-----------------------------------------------------------------------------
  // Function that adds a row containing a calendar to the advanced options page of booths
  addRow : function()
  {
  	// Update the IDs of the newly created elements to be unique
  	var rowID = "newDirRow" + this.nextIDToUse;
    
  	// Create the new row div
		var newdiv = document.createElement('div');
    newdiv.setAttribute('id',rowID);
    newdiv.innerHTML = this.hiddenElementDiv.innerHTML;
    this.calendarSpanElement.appendChild(newdiv);

		// Grab all elements labeled as input fields and append our ID to their name so we know they're part of a group
		var children = $j("#" + rowID + " .inputField");
		for(var i=0;i<children.length;i++)
		{
			element = children[i];
			element.setAttribute('name',element.getAttribute('name') + this.nextIDToUse.toString());
			element.setAttribute('id',element.getAttribute('id') + this.nextIDToUse.toString());
	  }

	  jQuery("#pickupDate_" + this.nextIDToUse).datepicker(	{
			showOn: "both", 
			buttonImage: "/images/calendar-icon.jpg", 
			buttonImageOnly: true,
			currentText: '', 
			yearRange: '2008:2009',
			changeFirstDay: false,
			minDate: new Date(),
			dateFormat: 'MM d, yy',
			initStatus: 'Choose a day',
			dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S']
		});
	  
	  this.nextIDToUse++;    
  },

  //-----------------------------------------------------------------------------
  // Desc:  Get rid of a row
  clearRow : function(rowElement)
  {
    if(rowElement)
    {
      rowElement.remove();
    }
  },
  
  //-----------------------------------------------------------------------------
  // Desc:  Populate the row with the strings specified 
  populatePickupTimeRow : function(rowNum, paramArray)
  {
  	var children = $j("#newDirRow" + rowNum + " .inputField");		
  	
		// Assumption: the paramArray passes in parameterse in the same order that the inputs are
		// laid out in the view
		for(i=0;i<children.length && paramArray[i];i++)
		{
			element = children[i];
			element.value = paramArray[i];
	  }
  },
  
  //-----------------------------------------------------------------------------
  // Desc:  Populate all checkboxes in the row with the parameters specified
  populateCheckboxRow : function(rowNum, paramArray)
  {
  	var children = $j("#newDirRow" + rowNum + " .checkboxField");		
  	
		// Assumption: the paramArray passes in parameterse in the same order that the inputs are
		// laid out in the view
		for(i=0;i<children.length && paramArray[i];i++)
		{
			element = children[i];
			element.checked = paramArray[i];
	  }
  },
  
  //-----------------------------------------------------------------------------
  // Desc:  Provide hookups such that this hashmap can be used like an object 
  createObject : function()
  {
    return this;
  }
};

//----------------------------------------------------------------------------------------------------
// Show/hide the instructions for a particular advanced topic, and set the corresponding cookie
function showHideBoothPropIndividualInstruction(element,show)
{
  if(show) 
  {
    element.show();
  }
  else
  {
    element.hide();
  }
  
	set_json_subcookie('_bo_se', element.id, show);
}

//----------------------------------------------------------------------------------------------------
// Verify the user's intent if they say they don't want to allow pickup
// select_name: id of the select option being confirmed
// container_span_name: name of the span in which this eip is contained
function confirmPickupChange(confirmString, select_name, container_span_name, autoConfirmBoolean)
{
  // If the user is allowing sold items to be picked up (=true) or they confirm our warning, we'll let them proceed
  // Note: if confirmstring is blank, it's cuz there's nothing to confirm, i.e., there were no items in the booth that 
  // would be affected by this change.
  jSelectEl = $j('#' + select_name + ' select');
  selectEl = $j('#' + select_name + ' select').get(0);
  confirmIt = ((jSelectEl.val() == autoConfirmBoolean) || 
          confirmString == '' ||
          confirm(confirmString));
          
  if(confirmIt)
  { // dumb code alert. too late. must stop programming.
    // Grabbing text selected from a select box
    selectedIndex = selectEl.selectedIndex;
    selectOptions = selectEl.options;
    
    // Manually set in place edit span, hide (and thereby save) our selected option, then hide the edit area
    $j('#' + container_span_name + ' #option_text').text(selectOptions[selectedIndex].text);
    $j('#' + container_span_name).show();
    $j('#' + select_name).hide();
  }
  
  return confirmIt;
}

// Keep the status line (and firsttime line, if applicable) up to date with the list of items
function renderStatusAreaString(statusString, targetElementSelector) {
  if(statusString == null) {
    statusString = "";
  }
  
  stringShow = (statusString.length > 0 ? 'display:block;' : 'display:none');
  $j(targetElementSelector).attr('style',stringShow);
	$j(targetElementSelector).html(statusString);
}


/* This was generated through the following:
	<% @categories = Category.find(:all)
	# Possible optimization here is to just check if the parent_id of the category is whatever nil corresponds to (0, I believe),
	# and only add it to the parent list if so
	all_parent_categories = @categories.inject([]) do |list,cat| 
		parent_cat = (cat.ancestors[0] ? cat.ancestors[0] : cat)
		list << parent_cat
	end
	all_parent_categories.uniq!		
	unique_sorted_categories = get_sorted_categories(all_parent_categories,false) %>
	<h3>Unique categories: </h3>
	<% unique_sorted_categories.each do |category| -%>
	<% if category -%> 
		<%= %{["#{category.name}","#{category.id}"],<br />} -%>
		<% end -%>               	 
    
<% unique_sorted_categories.each do |category|
	if category -%>
		<% child_categories = Category.find(:all, :conditions => { :parent_id => category } )
		child_categories.sort! { |a,b| a.name <=> b.name }
		child_categories.collect! { |category| %{["#{category.name}","#{category.id.to_s}"]} } -%>
		<%= "[" + child_categories.join(",") + "]," -%>
		<%= "<br />" %>
	  <% end
end  -%>
*/

/* categories and subcats for the modal dropdowns */
var parentCategories = [["Antiques","20081"],
      ["Art","550"],
      ["Baby","2984"],
      ["Books","267"],
      ["Business & Industrial","12576"],
      ["Cameras & Photo","625"],
      ["Cars & Trucks","6001"],
      ["Cell Phones & PDAs","15032"],
      ["Clothing, Shoes & Accessories","11450"],
      ["Coins & Paper Money","11116"],
      ["Collectibles","1"],
      ["Computers & Networking","58058"],
      ["Crafts","14339"],
      ["DVDs & Movies","11232"],
      ["Dolls & Bears","237"],
      ["Electronics","293"],
      ["Entertainment Memorabilia","45100"],
      ["Everything Else","99"],
      ["Gift Certificates","31411"],
      ["Health & Beauty","26395"],
      ["Home & Garden","11700"],
      ["Jewelry & Watches","281"],
      ["Motorcycles","6024"],
      ["Music","11233"],
      ["Musical Instruments","619"],
      ["Other Vehicles & Trailers","6038"],
      ["Pottery & Glass","870"],
      ["Powersports","66466"],
      ["Real Estate","10542"],
      ["Specialty Services","316"],
      ["Sporting Goods","382"],
      ["Sports Mem, Cards & Fan Shop","64482"],
      ["Stamps","260"],
      ["Tickets","1305"],
      ["Toys & Hobbies","220"],
      ["Travel","3252"],
      ["Vehicle Parts & Accessories","6028"],
      ["Video Games","1249"]];

var childCategories = [
  [["Antiquities (Classical, Amer.)","37903"],["Architectural & Garden","4707"],["Asian Antiques","20082"],["Books, Manuscripts","2195"],["Decorative Arts","20086"],["Ethnographic","2207"],["Furniture","20091"],["Maps, Atlases, Globes","37958"],["Maritime","37965"],["Musical Instruments","37974"],["Other Antiques","12"],["Periods, Styles","100927"],["Primitives","1217"],["Reproduction Antiques","22608"],["Rugs, Carpets","37978"],["Science & Medicine","20094"],["Silver","20096"],["Textiles, Linens","2218"]],
  [["Digital Art","20118"],["Drawings","20119"],["Folk Art","357"],["Mixed Media","20122"],["Other Art","4174"],["Paintings","20125"],["Photographic Images","66465"],["Posters","28009"],["Prints","20140"],["Sculpture, Carvings","553"],["Self-Representing ACEOs","151719"],["Self-Representing Artists","20158"],["Wholesale Lots","52524"]],
  [["Baby Gear","100223"],["Baby Safety & Health","20433"],["Baby Wholesale Lots","48757"],["Bathing & Grooming","20394"],["Car Safety Seats","66692"],["Diapering","45455"],["Feeding","20400"],["Keepsakes & Baby Announcements","117388"],["Nursery Bedding","20416"],["Nursery Decor","66697"],["Nursery Furniture","20422"],["Other Baby Items","1261"],["Potty Training","37631"],["Strollers","66698"],["Toys","19068"]],
  [["Accessories","45110"],["Antiquarian & Collectible","29223"],["Audiobooks","29792"],["Catalogs","118254"],["Children's Books","279"],["Cookbooks","11104"],["Fiction Books","377"],["Magazine Back Issues","280"],["Magazine Subscriptions","29253"],["Nonfiction Books","378"],["Other","268"],["Textbooks, Education","2228"],["Wholesale, Bulk Lots","29399"]],
  [["Agriculture & Forestry","11748"],["Construction","11765"],["Food Service & Retail","11874"],["Healthcare, Lab & Life Science","11815"],["Industrial Electrical & Test","92074"],["Industrial Supply, MRO","1266"],["Manufacturing & Metalworking","11804"],["Office, Printing & Shipping","25298"],["Other Industries","26255"]],
  [["Bags, Cases & Straps","107894"],["Binoculars & Telescopes","28179"],["Camcorder Accessories","11723"],["Camcorders","23781"],["Digital Camera Accessories","3327"],["Digital Cameras","29997"],["Film","4201"],["Film Camera Accessories","43478"],["Film Cameras","15230"],["Film Processing & Darkroom","15224"],["Flashes & Accessories","64353"],["Lenses & Filters","78997"],["Lighting & Studio Equipment","30078"],["Manuals, Guides & Books","4684"],["Photo Albums & Archive Items","29951"],["Printers, Scanners & Supplies","30021"],["Professional Video Equipment","21162"],["Projection Equipment","15250"],["Stock Photography & Footage","21198"],["Tripods, Monopods","30090"],["Vintage","3326"],["Wholesale Lots","45086"]],
  [["AMC","5357"],["Acura","5330"],["Alfa Romeo","5340"],["Aston Martin","157054"],["Audi","6002"],["Austin","6126"],["Austin Healey","6023"],["BMW","6006"],["Bentley","157059"],["Buick","6135"],["Cadillac","5347"],["Chevrolet","5346"],["Chrysler","5351"],["Citroen","6183"],["Cord","6185"],["Daewoo","157064"],["Datsun","6186"],["DeLorean","31830"],["DeSoto","6190"],["Dodge","6191"],["Eagle","6214"],["Edsel","6216"],["Ferrari","6211"],["Fiat","6218"],["Ford","6010"],["GMC","6243"],["Geo","6242"],["Honda","6252"],["Hummer","5342"],["Hyundai","6261"],["Infiniti","6263"],["International Harvester","31845"],["Isuzu","6266"],["Jaguar","6272"],["Jeep","6279"],["Kia","6287"],["Lamborghini","157067"],["Lancia","6292"],["Land Rover","6293"],["Lexus","6297"],["Lincoln","6302"],["Lotus","116480"],["MG","6308"],["Mazda","6310"],["Mercedes-Benz","6311"],["Mercury","5363"],["Mini","31860"],["Mitsubishi","6348"],["Nash","31863"],["Nissan","6371"],["Oldsmobile","6372"],["Opel","6390"],["Other Makes","6472"],["Packard","6389"],["Peugeot","6388"],["Plymouth","6376"],["Pontiac","6377"],["Porsche","6013"],["Renault","6385"],["Replica/Kit Makes","7251"],["Rolls-Royce","157071"],["Saab","6380"],["Saturn","6381"],["Scion","116483"],["Shelby","6465"],["Smart","157077"],["Studebaker","6466"],["Subaru","6452"],["Suzuki","6468"],["Toyota","6016"],["Triumph","6449"],["Volkswagen","6018"],["Volvo","6454"],["Willys","6470"]],
  [["Accessories, Parts","20336"],["Bluetooth Wireless Accessories","133225"],["Cell Phones","146487"],["PDAs & Pocket PCs","38331"],["Phone & SIM Cards","146492"],["Smartphones","32233"],["Wholesale & Large Lots","45065"]],
  [["Boys","11452"],["Dancewear & Dance Shoes","112425"],["Girls","11462"],["Infants & Toddlers","3082"],["Men's Clothing","1059"],["Men's Accessories","4250"],["Men's Shoes","63850"],["Uniforms","28015"],["Vintage","110"],["Wedding Apparel","3259"],["Wholesale, Large & Small Lots","41964"],["Women's Accessories, Handbags","4251"],["Women's Clothing","15724"],["Women's Shoes","63889"]],
  [["Bullion","39482"],["Coins: Ancient","4733"],["Coins: Canada","3377"],["Coins: US","253"],["Coins: World","256"],["Exonumia","3452"],["Paper Money: US","3412"],["Paper Money: World","3411"],["Publications & Supplies","83274"],["Scripophily","3444"]],
  [["Advertising","34"],["Animals","1335"],["Animation Art, Characters","13658"],["Arcade, Jukeboxes & Pinball","66502"],["Autographs","14429"],["Banks, Registers & Vending","66503"],["Barware","3265"],["Bottles & Insulators","29797"],["Breweriana, Beer","562"],["Casino","898"],["Clocks","397"],["Comics","63"],["Cultures, Ethnicities","3913"],["Decorative Collectibles","13777"],["Disneyana","137"],["Fantasy, Mythical & Magic","10860"],["Furniture, Appliances & Fans","39629"],["Historical Memorabilia","13877"],["Holiday, Seasonal","907"],["Housewares & Kitchenware","13905"],["Knives, Swords & Blades","1401"],["Lamps, Lighting","1404"],["Linens, Fabric & Textiles","940"],["Metalware","1430"],["Militaria","13956"],["Pens & Writing Instruments","966"],["Pez, Keychains, Promo Glasses","14005"],["Photographic Images","14277"],["Pinbacks, Nodders, Lunchboxes","39507"],["Postcards & Paper","124"],["Radio, Phonograph, TV, Phone","29832"],["Religions, Spirituality","1446"],["Rocks, Fossils, Minerals","3213"],["Science Fiction","152"],["Science, Medical","412"],["Tobacciana","593"],["Tools, Hardware & Locks","13849"],["Trading Cards","868"],["Transportation","417"],["Vanity, Perfume & Shaving","597"],["Vintage Sewing","113"],["Wholesale Lots","45058"]],
  [["Apple, Macintosh Computers","4599"],["Desktop & Laptop Accessories","31530"],["Desktop & Laptop Components","3667"],["Desktop PCs","3736"],["Drives, Controllers & Storage","165"],["Laptops, Notebooks","51148"],["Monitors & Projectors","3694"],["Networking","11176"],["Other Hardware & Services","58059"],["Printer Supplies & Accessories","11195"],["Printers","1245"],["Scanners","11205"],["Servers","11211"],["Software","18793"],["Technology Books","3516"],["Vintage Computing Products","11189"]],
  [["Basketry","134304"],["Bead Art","31723"],["Candle & Soap Making","28114"],["Ceramics, Pottery","28121"],["Crafts Wholesale Lots","45074"],["Crocheting","3094"],["Cross Stitch","3091"],["Decorative, Tole Painting","28126"],["Drawing","28106"],["Embroidery","28141"],["Fabric","28155"],["Fabric Embellishments","31727"],["Floral Crafts","16491"],["Framing & Matting","37573"],["General Art & Craft Supplies","28102"],["Glass Art Crafts","3100"],["Handcrafted Items","71183"],["Kids Crafts","116652"],["Knitting","3103"],["Lacemaking, Tatting","134590"],["Latch Rug Hooking","28147"],["Leathercraft","28131"],["Macrame","28151"],["Metalworking","41369"],["Mosaic","28134"],["Needlepoint","3104"],["Other Arts & Crafts","75576"],["Painting","28110"],["Paper Crafts","134593"],["Quilting","3111"],["Ribbon","83974"],["Rubber Stamping & Embossing","3122"],["Scrapbooking","11788"],["Sewing","3116"],["Shellcraft","3120"],["Spinning","36600"],["Upholstery","113354"],["Wall Decor, Tatouage","75575"],["Weaving","57739"],["Woodworking","3127"],["Yarn","36589"]],
  [["DVD, HD DVD & Blu-ray","617"],["Film","63821"],["Laserdisc","381"],["Other Formats","41676"],["UMD","132975"],["VHS","309"],["VHS Non-US (PAL)","1508"],["Wholesale Lots","31606"]],
  [["Bear Making Supplies","50253"],["Bears","386"],["Dollhouse Miniatures","1202"],["Dolls","238"],["Paper Dolls","2440"],["Wholesale Lots","52546"]],
  [["A/V Accessories & Cables","14961"],["Apple iPod, MP3 Players","15057"],["Batteries & Chargers","40971"],["Car Electronics","3270"],["DVD & Home Theater","32852"],["GPS Devices","34288"],["Gadgets & Other Electronics","14948"],["Home Audio","14969"],["MP3 Accessories","56169"],["Portable Audio/Video","15052"],["Radios: CB, Ham & Shortwave","1500"],["Satellite Radio","60204"],["Satellite, Cable TV","61383"],["Telephones & Pagers","3286"],["Televisions","11071"],["Vintage Electronics","14998"],["Wholesale Lots","61494"]],
  [["Autographs-Original","57"],["Autographs-Reprints","104412"],["Movie Memorabilia","196"],["Music Memorabilia","2329"],["Other Memorabilia","2312"],["Television Memorabilia","1424"],["Theater Memorabilia","2362"],["Video Game Memorabilia","45101"]],
  [["Advertising Opportunities","102333"],["Education & Learning","16706"],["Funeral & Cemetery","88739"],["Genealogy","20925"],["Gifts & Occasions","16086"],["Information Products","102480"],["Mature Audiences","319"],["Memberships","16709"],["Metaphysical","19266"],["Mystery Auctions","102534"],["Other","88433"],["Personal Security","102535"],["Religious Products & Supplies","102545"],["Reward Pts, Incentive Progs","102553"],["Test Auctions","14112"],["Weird Stuff","1466"],["eBay User Tools","20924"]],
  [],
  [["Bath & Body","11838"],["Coupons","82567"],["Dietary Supplements, Nutrition","19259"],["Fragrances","26396"],["Hair Care","11854"],["Hair Removal","31762"],["Health Care","67588"],["Makeup","31786"],["Massage","36447"],["Medical, Special Needs","11778"],["Nail","11871"],["Natural Therapies","67659"],["Oral Care","31769"],["Other Health & Beauty Items","1277"],["Over-the-Counter Medicine","75036"],["Skin Care","11863"],["Tanning Beds, Lamps","31775"],["Tattoos, Body Art","33914"],["Vision Care","31414"],["Weight Management","31817"],["Wholesale Lots","40965"]],
  [["Bath","20438"],["Bedding","20444"],["Building & Hardware","3187"],["Dining & Bar","71236"],["Electrical & Solar","20595"],["Food & Wine","14308"],["Furniture","3197"],["Gardening & Plants","2032"],["Heating, Cooling & Air","41986"],["Home Decor","10033"],["Home Security","41968"],["Kitchen","20625"],["Lamps, Lighting, Ceiling Fans","20697"],["Major Appliances","20710"],["Outdoor Power Equipment","29518"],["Patio & Grilling","20716"],["Pet Supplies","1281"],["Plumbing & Fixtures","20601"],["Pools & Spas","20727"],["Rugs & Carpets","20584"],["Tools","631"],["Vacuum Cleaners & Housekeeping","299"],["Wholesale Lots","31605"],["Window Treatments","63514"]],
  [["Body Jewelry","10968"],["Bracelets","10975"],["Charms & Charm Bracelets","3835"],["Children's Jewelry","84605"],["Designer Brands","11317"],["Earrings","10985"],["Ethnic, Tribal Jewelry","11312"],["Hair Jewelry","110620"],["Handcrafted, Artisan Jewelry","110633"],["Jewelry Boxes & Supplies","10321"],["Jewelry Sets","43209"],["Loose Beads","488"],["Loose Diamonds & Gemstones","491"],["Men's Jewelry","10290"],["Necklaces & Pendants","10994"],["Other Items","505"],["Pins, Brooches","11008"],["Rings","67725"],["Vintage, Antique","48579"],["Watches","14324"],["Wholesale Lots","40131"]],
  [["American Ironhorse","49973"],["Aprilia","38627"],["BMW","49974"],["BSA","6703"],["Benelli","159586"],["Big Dog","49978"],["Bimota","159587"],["Boss Hoss","49979"],["Bourget","49980"],["Buell","49981"],["Bultaco","6705"],["Can-Am","159588"],["Ciello","159589"],["Cushman","159590"],["Custom Built Motorcycles","147899"],["Desperado","133175"],["Ducati","49987"],["Greeves","159591"],["Harley-Davidson","49992"],["Hodaka","159592"],["Honda","49998"],["Husqvarna","50013"],["Hyosung","159593"],["Indian","6709"],["KTM","50021"],["Kawasaki","50014"],["Kymco","159594"],["Lifan","159595"],["MV Agusta","159596"],["Moto Guzzi","6713"],["Norton","6714"],["Other Makes","6719"],["Royal Enfield","50024"],["Suzuki","50025"],["Titan","6715"],["Triumph","50035"],["Ural","6717"],["Vento","159597"],["Victory","38628"],["Vincent","159598"],["Yamaha","50041"]],
  [["Accessories","52473"],["CDs","307"],["Cassettes","1600"],["DVD Audio","46353"],["Digital Music Downloads","88451"],["Other Formats","618"],["Records","306"],["Super Audio CDs","46354"],["Wholesale Lots","31608"]],
  [["Brass","16212"],["DJ Gear & Lighting","14982"],["Electronic","38068"],["Equipment","41402"],["Guitar","3858"],["Harmonica","47078"],["Instruction Books, CDs, Videos","100228"],["Keyboard, Piano","16217"],["Other Instruments","308"],["Percussion","10172"],["Pro Audio","15197"],["Sheet Music, Song Books","20833"],["String","10176"],["Wholesale Lots","52555"],["Woodwind","10181"]],
  [["Aircraft","63676"],["Boats","26429"],["Buses","6728"],["Commercial Trucks","63732"],["Military Vehicles","80765"],["Other","6737"],["RVs and Campers","50054"],["Race Cars (Not Street Legal)","98060"],["Trailers","66468"]],
  [["Glass","50693"],["Pottery & China","18875"]],
  [["ATVs","6723"],["Dune Buggies / Sand Rails","133220"],["Go Karts: High-performance","46105"],["Other Powersports","66467"],["Personal Watercraft","31273"],["Powersport Vehicles Under 50cc","90983"],["Scooters & Mopeds","6720"],["Snowmobiles","42595"]],
  [["Commercial","15825"],["Land","15841"],["Manufactured Homes","94825"],["Other Real Estate","1607"],["Residential","12605"],["Timeshares for Sale","15897"]],
  [["Advice & Instruction","50337"],["Artistic Services","47126"],["Custom Clothing & Jewelry","50343"],["Graphic & Logo Design","47131"],["Media Editing & Duplication","50355"],["Other Services","317"],["Printing & Personalization","20943"],["Restoration & Repair","47119"],["Web & Computer Services","47104"],["eBay Auction Services","50349"]],
  [["Airsoft","31680"],["Archery","20835"],["Athletic Apparel","137006"],["Athletic Footwear","137010"],["Baseball & Softball","16021"],["Basketball","21194"],["Billiards","21209"],["Bowling","20846"],["Boxing","30100"],["Camping, Hiking, Backpacking","16034"],["Canoes, Kayaks, Rafts","36121"],["Climbing","30105"],["Cycling","7294"],["Disc Golf","79802"],["Equestrian","3153"],["Exercise & Fitness","15273"],["Fishing","14104"],["Football","21214"],["Go-Karts, Recreational","64655"],["Golf","1513"],["Gymnastics","79792"],["Hunting","7301"],["Ice Skating","21225"],["Ice, Roller Hockey","40154"],["Indoor Games","36274"],["Inline, Roller Skating","16258"],["Lacrosse","62163"],["Martial Arts","36279"],["Other Sports","40141"],["Paintball","16045"],["Racquetball & Squash","62166"],["Running","64685"],["Scooters","11330"],["Scuba, Snorkeling","16052"],["Skateboarding","16262"],["Skiing & Snowboarding","36259"],["Snowmobiling","23831"],["Soccer","20862"],["Surfing, Wind Surfing","22709"],["Swimming","74050"],["Tennis","20868"],["Triathlon","64680"],["Wakeboarding, Waterskiing","23806"],["Wholesale Lots","40146"]],
  [["Autographs-Original","51"],["Autographs-Reprints","50115"],["Cards","212"],["Fan Apparel & Souvenirs","24409"],["Game Used Memorabilia","50116"],["Manufacturer Authenticated","60591"],["Vintage Sports Memorabilia","50123"],["Wholesale Lots","56080"]],
  [["Africa","692"],["Asia","47174"],["Australia","3468"],["Br. Comm. Other","263"],["Canada","3478"],["Europe","4742"],["Latin America","4747"],["Middle East","3491"],["Publications & Supplies","704"],["Topical & Specialty","4752"],["UK (Great Britain)","3499"],["United States","261"],["Worldwide","352"]],
  [["Event Tickets","16122"],["Experiences","16071"],["Other Items","1306"]],
  [["Action Figures","246"],["Beanbag Plush, Beanie Babies","49019"],["Building Toys","18991"],["Classic Toys","19016"],["Diecast, Toy Vehicles","222"],["Educational","11731"],["Electronic, Battery, Wind-Up","19071"],["Fast Food, Cereal Premiums","19077"],["Games","233"],["Model RR, Trains","479"],["Models, Kits","1188"],["Outdoor Toys, Structures","11743"],["Pretend Play, Preschool","19169"],["Puzzles","2613"],["Radio Control","2562"],["Ride-ons", "100600"],["Robots, Monsters, Space Toys","19192"],["Slot Cars","2616"],["Stuffed Animals","436"],["TV, Movie, Character Toys","2624"],["Toy Soldiers","2631"],["Trading Card Games","2536"],["Vintage, Antique Toys","717"],["Wholesale Lots","40149"]],
  [["Airline","3253"],["Car Rental","147399"],["Cruises","16078"],["Lodging","16079"],["Luggage","16085"],["Other Travel","1310"],["Vacation Packages","29578"]],
  [["ATV Parts","43962"],["Apparel & Merchandise","6747"],["Automotive Tools","34998"],["Aviation Parts","26435"],["Boat Parts","26443"],["Car & Truck Parts","6030"],["Car Audio, Video","38635"],["Manuals & Literature","6029"],["Motorcycle Parts","10063"],["Other","6755"],["Other Vehicle Parts","34285"],["Personal Watercraft Parts","124107"],["Racing Parts","107057"],["Services & Installation","111098"],["Snowmobile Parts","100448"],["Vintage Car & Truck Parts","10073"],["Wholesale Lots","50467"]],
  [["Accessories","49220"],["Games","62053"],["Internet Games","1654"],["Other","187"],["Systems","62054"],["Vintage Games","4315"],["Wholesale Lots","48749"]]
  ];

function populateCategoryParent(selectElement){
  selectElement.empty();
  selectElement.append( $j("<option>").val(-1).text("No category") );
  for (var i=0; i<parentCategories.length; i++){
	  selectElement.append( $j("<option>").val(parentCategories[i][1]).text(parentCategories[i][0]) );
  }
}
function populateCategoryChild(selectElement, parentIndex){
  selectElement.empty();
  selectElement.append( $j("<option>").val(-1).text("No subcategory") );
  if (parentIndex > 0 && parentIndex < childCategories.length + 1){
	  var childCategorySubset = childCategories[parentIndex-1]; // -1 since the first option is no option at'all
	  for (var i=0; i<childCategorySubset.length; i++){
		  selectElement.append( $j("<option>").val(childCategorySubset[i][1]).text(childCategorySubset[i][0]) );
	  }
  }
}

//-----------------------------------------------------------------------------
function showUploadWaitForm(attachToSelector)
{
  showWaitPanel(attachToSelector,"Now uploading...<br>You may fill out your item in the meantime", 0, -30);
  attachProgressAt = $j(attachToSelector + " > .WaitPanel").children('.WaitElementsContainer');
  //attachProgressAt.append($j("<div id='uploadProgressBG' style='width:200px;height:20px;border:1px solid white;margin-top:5px;text-align:left;background-color:#DDDDDD;position:absolute;left:70px;'>"));
  //    .append($j("<div id='uploadProgressBar' style='background-color:yellow;height:20px;width:1px;'>")));
}

//-----------------------------------------------------------------------------
// Called before performing an operation on right side of new item form
function beforeActOnImageArea(showProgress)
{
  if(showProgress) {
  	showUploadWaitForm('#ItemEntryRightPane');   // Show wait panel
  	$j('#ItemEntryRightPane').progressHandlerInit();
  	$j('#item_title').focus();
	}
	else { // might be better to move this logic inside of showUploadWaitForm...?
	  showWaitPanel('#ItemEntryRightPane');
	}
	$j('#imgPopup').css('display','none');  // Hide image options popup
  $j('#quick_upload_link').css('display','none');  // Hide the absolutely positioned quick upload link
}

//-----------------------------------------------------------------------------
// Called after performing an operation on right side of new item form
function afterActOnImageArea(formEl, showedProgress)
{
  if(showedProgress) {
	 bindFileUploadInputs();  // Rebind the form with the new input element
   $j('#ItemEntryRightPane').progressHandlerStop();
	}
	hideWaitPanel('#ItemEntryRightPane');
  $j('#quick_upload_link').css('display','block');
}

//-----------------------------------------------------------------------------
// Called after an upload AJAX request completes.  As you can see, "successful" is relative here.  The
// AJAX request was a success, but this doesn't necessarily mean the image was successfully created.
function afterSuccessfulUpload(data)
{
  if(data.image_id != -1) {
    $j('#item_image_main').attr('src',data.image_main);
    image_el = $j('li#upload_'+data.image_slot + ' img'); 
    populateImageElement(image_el, data);

    $j('#recently_uploaded_container a:last').remove();
    clone_anchor = $j('#recently_uploaded_container a:first').clone();
    $j('#recently_uploaded_container a:first').before(clone_anchor);
		populateImageElement(clone_anchor.find('img'), data);

    if($j('#NewItemSaveErrors').text() != '') {
      // Give them some encouragement if they erred previously (thereby ensuring sure the old error message isn't there)
      $j('#NewItemSaveErrors').text('Upload success!');
    }
  }
  else {
    $j('#NewItemInfoMessageContainer').show();
    $j('#NewItemInfoMessageContainer span#NewItemSaveErrors').show();
    $j('#NewItemSaveErrors').text("There was an error processing the image you uploaded.  Please ensure that it is 6 megs or less, and that its format is among the allowed types (.jpg, .png, .gif, or .bmp)");
  }
}

//-----------------------------------------------------------------------------
// Create a thumbnail image with the HTML attribute that are expected by the various javascript methods that will
// interact with it.
function populateImageElement(image_el, image_data) {
	image_el.attr('src', image_data.image_thumb155);
	image_el.attr('id', image_data.image_id);
	image_el.attr('name', image_data.image_main);
}

//-----------------------------------------------------------------------------
function bindImageElements() {
	$j('div#ItemEntryRightPane ul li img').each(function(){
		$j(this).hover(function(e) {
			var p = $j(this).parent();
			p.addClass('nif_image_thumb_hovering');
			$j('#imgPopup').css('display','block').find('li.xtraOp').css('display',(this.src.indexOf('upload_thumbnail.jpg')!=-1)?'none':'block' );
			relative_el = $j($j('#imgPopup').parents("div[class~='relative_element']").get(0));  // find the relatively-positioned parent of the imgPopup (which will be different than the parent of the image being moused over) 
			pos = getCumulativeOffsetPos(this, relative_el);
			pos[0] = pos[0] - $j('#imgPopup').width();
			$j('#imgPopup').css('top',pos[1]).css('left',pos[0]);
			$j('#uploadId').attr('value',p[0].id);
			$j('#mouseOverSlotID').attr('value',p[0].id);
			$j('#mouseOverImageID').attr('value',this.id);
		}, function(){
				$j(this).parent().removeClass('nif_image_thumb_hovering');
			}
		).click(function(){
			pimg = (this.src).indexOf('upload_thumbnail.jpg')!=-1?'/images/newitem/big_upload_pic_blank.jpg':(this.name);
			$j('#item_image_main').attr('src',pimg);
		});
	});

	$j('div#ItemEntryRightPane').bind('mouseover',function(e){
			if(e.target.parentNode.className!=='imgThumb' && e.target.id==='ItemEntryRightPane'){
				$j('#imgPopup').css('display','none');
			}
	});
}

//-----------------------------------------------------------------------------
function bindFileUploadInputs()
{
  $j('#uploadForm input').unbind(); // Ensure we don't double-bind
  $j('#uploadForm input').change(function(){
		$j(this).parent().ajaxSubmit({
				beforeSubmit: function(a,f,o) {
			    o.dataType = $j('#uploadResponseType')[0].value;
			    beforeActOnImageArea(true);
        },
        complete: function(XMLHttpRequest, textStatus) {
          afterActOnImageArea($j('#uploadForm'),true);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
			  {
				  $j("#NewItemSaveErrors").show();
				  $j("#NewItemSaveErrors").text("Error in upload, description: " + errorThrown);
			  },
        success: function(data) {
          afterSuccessfulUpload(data);
        }
    });
		return false; // cancel conventional submit
	});

	if(isSafari()) {
	  $j('div#imgPopup ul li#upload_image form .fileUpload').addClass("safariUploadAttrs");
	}

	$j('#quickUploadForm input').unbind(); // Ensure we don't double-bind
	$j('#quickUploadForm input').change(function(){
		$j(this).parent().ajaxSubmit({
      beforeSubmit: function(a,f,o) {
			  o.dataType = "json";
			  beforeActOnImageArea(true);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
				$j("#NewItemSaveErrors").show();
				$j("#NewItemSaveErrors").text("Error in upload, description: " + errorThrown);
			},
      complete: function(XMLHttpRequest, textStatus) {
        afterActOnImageArea($j('#quickUploadForm'),true);
      },
      success: function(data) {
        afterSuccessfulUpload(data);
      }
    });
		return false; // cancel conventional submit
	});
}

//-----------------------------------------------------------------------------
// Capture coordinates from the jqueyr crop window
function captureCoords(selection) {
	scalar_inverse = 1/scalar;
	$j('#crop_values_crop_left').val(selection.x*scalar_inverse);
	$j('#crop_values_crop_top').val(selection.y*scalar_inverse);
	$j('#crop_values_crop_width').val(selection.w*scalar_inverse);
	$j('#crop_values_crop_height').val(selection.h*scalar_inverse);
}

//-----------------------------------------------------------------------------
// Return from an image crop, update the new item form accordingly
function swapCropImage(response) {
	closeCrop();
	response_text = response.responseText
	if(response_text && response_text != '') {
		json = $j.evalJSON(response_text);
		if(json && json.big_picture) {
			timestamp = new Date().getTime();
			$j('#item_image_main').attr('src', json.big_picture + "?" + timestamp);
			$j('#' + $j('#mouseOverImageID').val()).attr('id', json.image_id).attr('src', json.small_picture + "?" + timestamp).attr('name', json.big_picture).attr('alt', json.big_picture);
		}
	}
}


//-----------------------------------------------------------------------------
// Loop through item picture slots in search of an empty slot to insert the image contained by image_el
function addPictureToItem(pictureToAddElement, itemId, boothId) {
	image_slot = 0;
	$j('li.imgThumb').each(function() {
		image_el = $j(this).find('img');
		if(image_el && (!image_el.attr('name') || image_el.attr('name') == '')) {
			image_el.attr('src', '/images/itemview/moviecountdown.gif');
			$j.ajax({ type: "POST", url: '/booths/' + boothId + '/items/' + itemId + '/images/' + pictureToAddElement.attr('id') + '/copy',
				data: "image_slot=" + image_slot,
				complete: function(response) {
					my_object = $j.evalJSON(response.responseText);
					populateImageElement(image_el, my_object);
				}
			}); // ajax request

			return false;
		}
		image_slot++;
	});
}