/**
 * CatPrint Jobs
 * Implements Job Wizard
 * 
 **/


var JobBuilder = Class.create({
  initialize: function(container, options) {
    options = options || {};
    
    this.container = $(container);
    this.jobs_path = options.jobs_path;
    this.editor_control = options.editor_control;
    this.user_login = options.user_login;
    
    this.message_block = new MessageBlock();
    this.job_editor = new JobBuilder.JobEditor(this, this.editor_control);
    this.predefined_job_selector = new JobBuilder.PredefinedJobSelector(this);
    this.paper_selector = new JobBuilder.PaperSelector(this);
    this.finishing_option_selector = new JobBuilder.FinishingOptionSelector(this);
    
    this.conflict_triggers = {};
    this.job_changed = false;
    
    this.event_handlers();
  },
  
  event_handlers: function() {
  	document.observe('choose_predefined_job:click', function(event) { 
		this.predefined_job_selector.show(); 
		if (event.memo.indexOf("scroll_to-")==0) {
			$('predefined-jobs').scrollTop = $('predefined-job-item-' + event.memo.replace("scroll_to-","")).offsetTop - 125
		}
		else {
			alert('To setup a custom job begin by entering the size of your piece, then choose your paper, and finishing options.');
		}
		}.bind(this));
    Event.observe('choose_predefined_job', 'click', function() { this.predefined_job_selector.show(); }.bind(this));
    Event.observe('choose_paper', 'click', function() { this.paper_selector.show(); }.bind(this));
    Event.observe('choose_finishing_option', 'click', function() { this.finishing_option_selector.show(); }.bind(this));
    
    ['job_pages', 'job_copies', 'draft_shipping_method_id'].each(function(element) {
      Event.observe(element, 'change', this.update.bindAsEventListener(this));
    }.bind(this));
    
    Event.observe('save_and_checkout', 'click', this.update.bindAsEventListener(this));
    
    Event.observe('apply_coupon', 'click', function(e) { this.update(); e.stop(); return false; }.bindAsEventListener(this));
    
    if ($('apply_price_overrides')) {
      Event.observe('apply_price_overrides', 'click', function(e) { this.update(); e.stop(); return false; }.bindAsEventListener(this));
    }
    
    Event.observe('job_copies', 'change', function(e) {
      if (e.target.value == '1') { $('copies_label').innerHTML = 'copy'; }
      else { $('copies_label').innerHTML = 'copies'; }
    });
    
    this.container.up('form').observe('submit', function(e) {
      /* if (parseInt($F('job_panel_count')) < parseInt($F('job_pages'))) {
        if (!confirm("You have elected to send us some or all of the files for this job later.  Are you sure you want to continue?")) {
          e.stop();
          return false;
        }
      } */ // this is not helping... so we just removed it... better to have some links so they can go back and edit
      
      // Invite the user to login
      if (this.user_login.toString().length == 0) {
        LoginWindow.show('/session/new?allow_continue=1');
        
        document.observe('window:hiding', function() {
          this.container.up('form').submit();
          document.stopObserving('window:hiding');
        }.bindAsEventListener(this));
        
        this.container.up('form').stopObserving('submit');
        e.stop();
        return false;
      }
    }.bindAsEventListener(this));
  },
  
  update: function() {
    new Ajax.Request(this.jobs_path + "/pricing", {
      method: 'post',
      parameters: Form.serialize('new-job-form'),
      
      onFailure: function(transport) {
        this.message_block.update(transport.responseJSON);
      }.bind(this),
      
      onSuccess: function(transport) {
        this.message_block.clear();
        this.job_changed = true;
        
        var pricing = transport.responseJSON;
        if (!pricing) { return; }
        
        $('subtotal').update(number_to_currency(pricing.subtotal, pricing.currency_symbol));
        $('shipping_cost').update(number_to_currency(pricing.shipping, pricing.currency_symbol));
        $('job_description').update(pricing.description);
        
        if (pricing.job_type) { $('job_job_type').update(pricing.job_type); }
        else { $('job_job_type').update("Not selected"); }
        
        if (pricing.coupon) {
          $('have-a-code').hide();
          $('coupon-applied').show();
          $('coupon-discount').update(pricing.coupon.discount);
          $('coupon-code').update(pricing.coupon.code);
          
          if (pricing.coupon.display_note) {
            $('coupon-display-note').update(pricing.coupon.display_note);
            $('coupon-display-note').show();
          } else {
            $('coupon-display-note').update('');
            $('coupon-display-note').hide();
          }
        } else {
          $('coupon-applied').hide();
          $('have-a-code').show();
          $('have-a-code-link').show();
          $('coupon-code-form').hide();
        }
        
        //TODO determine if this a more subtle color we want to use $('pricing').highlight();
        
        if (pricing.conflicts && pricing.conflicts.length > 0) {
          this.message_block.update({error: pricing.conflicts});
        }
        
        if (pricing.conflict_triggers) {
          this.conflict_triggers = pricing.conflict_triggers;
        } else {
          this.conflict_triggers = {}
        }
        
        this.apply_conflict_triggers();
        
      }.bind(this)
    });
    
  },
  
  apply_conflict_triggers: function() {
    // First enable all options
    
    // Next, disable only the right conflicts
    // Actually, this can occur when the dialog is shown
    
    $('editor_frontImgOption')
  },
  
  user_logged_in: function(user_login) {
    this.user_login = user_login;
    this.job_editor.change_to_user_id(user_login);
    this.update();
  }
  
});

/** Controller for Job Editor Control - Communicates with rest of interface **/
JobBuilder.JobEditor = Class.create({
  initialize: function(job_builder, control) {
    this.job_builder = job_builder;
    this.control = control;
    this.event_handlers();
  },
  
  event_handlers: function() {
    var tthis = this;
    $(document).observe('editor:jobdocchange', function(e) {
      tthis.job_doc_changed(e.memo.xmlString);
    });
    
    Event.observe('job_copies', 'change', function(e) { tthis.set_copies($F('job_copies')); });
    Event.observe('job_pages', 'change', function(e) { tthis.set_pages($F('job_pages')); });
    $(document).observe('editor:front_imaging_changed', function(e) { tthis.front_imaging_changed(e.memo.value); });
    $(document).observe('editor:back_imaging_changed', function(e) { tthis.back_imaging_changed(e.memo.value); });
	  $(document).observe('editor:bleed_width_changed', function(e) { tthis.bleed_width_changed(e.memo.value);});
    $(document).observe('editor:pages_changed', function(e) { tthis.pages_changed(e.memo.value); });
    
    // TODO this is a work around to problem 104 and 105
    $(document).observe('editor:forceupdate', function (e) {
    	tthis.job_builder.update();
    });
    
    this.job_builder.container.up('form').observe('submit', function(e) { tthis.load_editor_values(); });
  },
  
  front_imaging_changed: function(value) {
    console.log("[Editor] Front Imaging Changed: " + value);
    
    $("job_front_imaging_code").value = value;
    this.job_builder.update();
  },
  
  back_imaging_changed: function(value) {
    console.log("[Editor] Back Imaging Changed: " + value);
    
    $("job_back_imaging_code").value = value;
    this.job_builder.update();
  },
  
  bleed_width_changed: function(value){
  	console.log("[Editor] Bleed Option Changed: " + value);
	
	  $('job_full_bleed_option_id').value = (parseFloat(value) == 0) ? $('no_bleed_id').value : $('full_bleed_id').value
	  this.job_builder.update();
  },
  
  pages_changed: function(value) {
    console.log("[Editor] Pages Changed: " + value);
    
    $("job_pages").value = value;
    this.job_builder.update();
  },
  
  panel_count_changed: function(value) {
  	  console.log("[Editor] Panel Count Changed: " + value);
    
      $('job_panel_count').value = value;
      this.job_builder.update();
    },
  
  check_width_height_change: function(width, height) {  
	  var old_width = $('job_width_in_local_units').value;
	  var old_height = $('job_height_in_local_units').value;
	  
	  if (!isNaN(width)) {
    	// TODO: finished width should be divided by nfolds 
      $('job_finished_width_in_local_units').value = width * $('units_per_ps_pt').value;
      $('job_width_in_local_units').value = width * $('units_per_ps_pt').value;
    	  console.log("  Set Print Width: " + width * $('units_per_ps_pt').value)
  	  }
    
	  if (!isNaN(height)) {
      //TODO finished height should be divided by nfolds
      $('job_finished_height_in_local_units').value = height * $('units_per_ps_pt').value;
      $('job_height_in_local_units').value = height * $('units_per_ps_pt').value;
      console.log("  Set Print height: " + height * $('units_per_ps_pt').value)
    }
	  
	  if ((Math.min(old_width,old_height) != 
	  	   Math.min($('job_finished_width_in_local_units').value, 
	  	            $('job_finished_height_in_local_units').value)) || 
	  	  (Math.max(old_width,old_height) != 
	  	   Math.max($('job_finished_width_in_local_units').value, 
	  	            $('job_finished_height_in_local_units').value))) { 
	  	 this.job_builder.update()
	  }
	},
  
  load_editor_values: function() {
    job_doc = this.get_job_doc();
    job_doc_string = this.get_job_doc_string();
    
    $('job_job_doc_string').value = job_doc_string;
    
    console.log("[Editor] Loading Editor Values...");
    
    if (job_doc.printsizewidth) {
      //TODO finished sizes are divided by nfolds
      $('job_finished_width_in_local_units').value = job_doc.printsizewidth * $('units_per_ps_pt').value;
      $('job_width_in_local_units').value = job_doc.printsizewidth * $('units_per_ps_pt').value;
      console.log("  Set Print Width: " + job_doc.printsizewidth * $('units_per_ps_pt').value)
    }
    
    if (job_doc.printsizeheight) {
      //TODO finished sizes are divided by nfolds
      $('job_finished_height_in_local_units').value = job_doc.printsizeheight * $('units_per_ps_pt').value;
      $('job_height_in_local_units').value = job_doc.printsizeheight * $('units_per_ps_pt').value;
      console.log("  Set Print height: " + job_doc.printsizeheight * $('units_per_ps_pt').value)
    }
        
    if (job_doc.imagingfront) {
      $('job_front_imaging_code').value = job_doc.imagingfront;
      console.log("  Set Front Imaging: " + job_doc.imagingfront);
    }
    
    if (job_doc.imagingback) {
      $('job_back_imaging_code').value = job_doc.imagingback;
      console.log("  Set Back Imaging: " + job_doc.imagingback);
    }
	
  	if (job_doc.bleedwidth) {
  	  $('job_full_bleed_option_id').value = (job_doc.bleedwidth=="0") ? $('no_bleed_id').value : $('full_bleed_id').value;
  	  console.log("  Set Bleed Width: " + $('job_full_bleed_option_id').value)
  	}
    
    if (job_doc.fliponlongedge) {
      $('job_flip_on_long_edge').value = (job_doc.fliponlongedge == "true") ? "1" : "0";
      console.log("  Set Flip on Long Edge: "+ job_doc.fliponlongedge);
    }
    
    if (job_doc.pagecount) {
      $('job_pages').value = job_doc.pagecount;
      console.log("  Set Page Count: " + job_doc.pagecount);
    }
    
    if (job_doc.maxpagenum) {
      $('job_panel_count').value = job_doc.maxpagenum;
      console.log("  Set Panel Count: " + job_doc.maxpagenum);
    }
  },
  
  
  set_print_size_width: function(value) {
    job_doc = this.get_job_doc();
    job_doc.printsizewidth = value;
    this.set_job_doc(job_doc);
    
    console.log("[Editor] Set Print Size Width: " + value);
  },
  
  set_print_size_height: function(value) {
    job_doc = this.get_job_doc();
    job_doc.printsizeheight = value;
    this.set_job_doc(job_doc);
    
    console.log("[Editor] Set Print Size Height: " + value);
  },
  
  set_print_size_width_and_height: function(width, height) {
    job_doc = this.get_job_doc();
    job_doc.printsizewidth = width;
    job_doc.printsizeheight = height;
    this.set_job_doc(job_doc);
    
    console.log("[Editor] Set Print Size Width, Height: " + width + ", " + height);
  },
  
  set_paper_type: function(value) {
    job_doc = this.get_job_doc();
    job_doc.papertype = value;
    this.set_job_doc(job_doc);
    
    console.log("[Editor] Set Print Size Width: " + value);
  },
  
  set_fold_across_long_edge: function(value) {
    job_doc = this.get_job_doc();
    job_doc.foldacrosslongedge = value;
    this.set_job_doc(job_doc);
    
    console.log("[Editor] Set Fold Across Long Edge: " + value);
  },
  
  set_copies: function(value) {
    job_doc = this.get_job_doc();
    job_doc.copies = value;
    this.set_job_doc(job_doc);
    
    console.log("[Editor] Set Copies: " + value);
  },
  
  set_pages: function(value) {
    job_doc = this.get_job_doc();
    job_doc.pagecount = value;
    this.set_job_doc(job_doc);
    
    console.log("[Editor] Set Page Count: " + value);
  },
  
  set_finishing_option: function(value) {
    job_doc = this.get_job_doc();
    job_doc.finishingoption = value;
    this.set_job_doc(job_doc);
    
    console.log("[Editor] Set Finishing Option: " + value);
  },
  
  set_fold_count: function(value) {
    job_doc = this.get_job_doc();
    job_doc.nfolds = value;
    this.set_job_doc(job_doc);
    
    console.log("[Editor] Set Fold Count: " + value);
  },
  
  
  set_user_id: function(new_user_id) {
    this.control.SetUserId(new_user_id);
  },
  
  change_to_user_id: function(new_user_id) {
    this.control.UpdateUserId(new_user_id);
  },
  
  job_doc_to_string: function(job_doc) {
    var xoTree = new XML.ObjTree();
    xoTree.force_array = ["panel"];
    return '<?xml version="1.0" encoding="utf-16"?>' + "\n" + 
    xoTree.writeXML({jobdoc: job_doc});
  },
  
  job_doc_from_string: function(job_doc_string) {
    var xoTree = new XML.ObjTree();
    xoTree.force_array = ["panel"];
    var tempJobDoc = xoTree.parseXML(job_doc_string).jobdoc;
    return tempJobDoc;
  },
  
  set_job_doc_string: function(job_doc_string) {
    console.log("[Editor] Setting Job Doc to: \n" + job_doc_string + "\n");
    
    $('job_panel_count').value = this.control.setJobDocXmlString(job_doc_string);
  },
  
  set_job_doc: function(job_doc) {
    return this.set_job_doc_string(this.job_doc_to_string(job_doc));
  },
  
  get_job_doc_string: function() {
    return this.control.getJobDocXmlString();
  },
  
  get_job_doc: function() {
    return this.job_doc_from_string(this.get_job_doc_string());
  },
  
  job_doc_changed: function(job_doc_string) {
    console.log("[Editor] Job Doc Changed: \n" + job_doc_string + "\n");
    
    this.update_interface_from_job_doc(this.job_doc_from_string(job_doc_string));
  },
  
  update_interface_from_job_doc: function(job_doc) {
  	this.check_width_height_change(job_doc.printsizewidth, job_doc.printsizeheight);
    //alert('job doc change '+job_doc.bleedwidth+' '+$F('job_full_bleed_option_id')+' '+(parseFloat(job_doc.bleedwidth) == 0 ? $('no_bleed_id').value : $('full_bleed_id').value))
    if (job_doc.imagingfront && $F('job_front_imaging_code') != job_doc.imagingfront) { this.front_imaging_changed(job_doc.imagingfront); } 
    if (job_doc.imagingback && $F('job_back_imaging_code') != job_doc.imagingback) { this.back_imaging_changed(job_doc.imagingback); } 
    if (job_doc.bleedwidth && $F('job_full_bleed_option_id') != (parseFloat(job_doc.bleedwidth) == 0 ? $('no_bleed_id').value : $('full_bleed_id').value)) {this.bleed_width_changed(job_doc.bleedwidth); }
    if (job_doc.pagecount && $F('job_pages') != job_doc.pagecount) { this.pages_changed(job_doc.pagecount); }
    if (job_doc.maxpagenum && $F('job_panel_count') != job_doc.maxpagenum) { this.panel_count_changed(job_doc.maxpagenum); }
	
    console.log("[Editor] Updated Interface from Job Doc.");
  }
  
});


/** Controller for Predefined Jobs **/
JobBuilder.PredefinedJobSelector = Class.create({
  initialize: function(job_builder) {
    this.job_builder = job_builder;
    this.dialog_template = "";
    this.predefined_jobs = {};
  },
  
  changed: function() {
    return this.job_builder.update();
  },
  
  create_dialog: function() {
    this.dialog = new UI.Window({ 
			theme:  "alphacube",
			shadowTheme: "mac_shadow",
			shadow: true,
			width:  917,
			height: 457,
			resizable: false
    });
    keepDialogSizedRight(this.dialog, '#predefined-jobs', function (element, window) {
	  $(element).style.height = window.getSize().height-150+"px"
      }) 
    this.load_content();
  },
  
  show: function() {

		if (this.dialog == null || !this.dialog.visible) {
			hideTopBar(); // moved from above if statement... if there are problems move back...  Moved because we call show inside the dialog...
			this.create_dialog();
			this.dialog.show(true).activate().center();
			this.adjust_dialog_bounds();
		
		
			$$('.predefined-job-item').each(function(element){
				Event.observe(element, 'click', function(e){
					if (e.target.tagName != 'A') {
						var id = element.id.substr(20);
						this.choose(id, true);
						this.dialog.close();
					}
				}
	.bindAsEventListener(this));
			}
	.bind(this));
			
			this.dialog.observe('hiding', function(){
				$('job_finished_width_in_local_units').value = $('finished_width').value;
				$('job_finished_height_in_local_units').value = $('finished_height').value;
				
				$('job_width_in_local_units').value = $('unfinished_width').value;
				$('job_height_in_local_units').value = $('unfinished_height').value;
				
				// Notify Job Editor:
				this.job_builder.job_editor.set_print_size_width_and_height($('unfinished_width').value / $('units_per_ps_pt').value, $('unfinished_height').value / $('units_per_ps_pt').value);
				
				this.changed();
			}
	.bindAsEventListener(this));
			
			$('finished_width').value = $('job_finished_width_in_local_units').value;
			$('finished_height').value = $('job_finished_height_in_local_units').value;
			$('unfinished_width').value = $('job_width_in_local_units').value;
			$('unfinished_height').value = $('job_height_in_local_units').value;
	}},
	
	adjust_dialog_bounds: function() {
		return; // no longer used
    bounds = this.dialog.getBounds();
		if (bounds.top < 65) {
		  bounds.top = 65;
		  this.dialog.setBounds(bounds);
		}
  },
	
	load_content: function() {
	  this.dialog.setContent(this.dialog_template);
	},
	
	choose: function(id) {
  	var predefined_job = this.attributes(id);
  	
  	$('job_job_type').update(predefined_job.name);
  	$('job_predefined_job_id').value = predefined_job.id;
  	
  	$('finished_width').value = predefined_job.width_in_local_units;
  	$('finished_height').value = predefined_job.height_in_local_units;
  	
  	$('unfinished_width').value = predefined_job.width_in_local_units;
  	$('unfinished_height').value = predefined_job.height_in_local_units;
    
  	$('job_width_in_local_units').value = predefined_job.width_in_local_units;
  	$('job_height_in_local_units').value = predefined_job.height_in_local_units;
  	$('job_full_bleed_option_id').value = (parseInt(predefined_job.full_bleed_option_id) == 0) ? $('no_bleed_id').value : predefined_job.full_bleed_option_id;
  	$('job_front_imaging_code').value = predefined_job.front_imaging_code;
  	$('job_back_imaging_code').value = predefined_job.back_imaging_code;
    $('job_envelope_id').value = predefined_job.envelope_id;
    
    if (predefined_job.paper_id) { this.job_builder.paper_selector.choose(predefined_job.paper_id, true); }
  	if (predefined_job.finishing_option_id) { this.job_builder.finishing_option_selector.choose(predefined_job.finishing_option_id, true); }
  },
  
  attributes: function(id) {
    return this.predefined_jobs[id] || {};
  }
  
});


/** Controller for Paper Types **/
JobBuilder.PaperSelector = Class.create({
  initialize: function(job_builder) {
    this.job_builder = job_builder;
    this.dialog_template = "";
    this.papers = {};
  },
  
  create_dialog: function() {
    this.dialog = new UI.Window({
			theme:  "alphacube",
			shadowTheme: "mac_shadow",
			shadow: true,
			width:  917,
			height: 500,
			resizable: false
	 	});
	keepDialogSizedRight(this.dialog, '#papers', function (element, window) {
	  $(element).style.height = window.getSize().height-127+"px"
      }) 	
	this.load_content();
  },
  
  changed: function() {
    return this.job_builder.update();
  },
  
  show: function() {
  	hideTopBar()
  	if (this.dialog == null || !this.dialog.visible) {
  	  this.create_dialog();
  		this.dialog.show(true).activate().center();
  		this.adjust_dialog_bounds();
  		this.apply_conflict_triggers();
  	}
    
  	this.dialog.observe('hiding', function() {
      $('paper_weight_out').value = $('paper_weight').value;
      $('paper_coating_out').value = $('paper_coating').value;
      $('job_envelope_id').value = $('envelope_id').value; // this was commented out, but it seems customers prefer just to choose and close the dialog box
      this.changed();
  	}.bindAsEventListener(this));
    
  	this.event_handlers();
  	
  	if ($('paper_weight').selectedIndex != 0 || $('paper_coating').selectedIndex != 0) {
      this.filter($F('paper_weight'), $F('paper_coating'));
  	}
  },
  
  adjust_dialog_bounds: function() {
  	return; // no longer used
    bounds = this.dialog.getBounds();
		if (bounds.top < 65) {
		  bounds.top = 65;
		  this.dialog.setBounds(bounds);
		}
  },
  
  paper_item_event_handlers: function() {
    $$('#papers div.paper-item').each(function(element) {
		$(element).writeAttribute('title', 'click to select this paper');
  		Event.observe(element, 'click', function(e) {
  			if (e.target.tagName != 'A') {
  				var id = element.id.substr(11);
  				if (this.choose(id)) {
				  $('job_envelope_id').value = $('envelope_id').value 
  				  this.dialog.close();
  				}
  			}
  		}.bindAsEventListener(this));
  	}.bind(this));
  },
  
  event_handlers: function() {
    this.paper_item_event_handlers();
    
    $('paper_weight').value = $('paper_weight_out').value;
	  $('paper_coating').value = $('paper_coating_out').value;
	  $('envelope_id').value = $('job_envelope_id').value;
    
  	['paper_weight', 'paper_coating'].each(function(element) {
  	  Event.observe(element, 'change', function() { 
  	    this.filter($F('paper_weight'), $F('paper_coating'));
  	  }.bindAsEventListener(this));
  	}.bind(this));
	
	Event.observe('envelope_id', 'change', function() {
		var none_equals_blank = function(val) { 
			return val=="" ? "1" : val}  // TODO remove blank first entry in envelopes so we don't have to do this
		if (none_equals_blank($('envelope_id').value) != none_equals_blank($('job_envelope_id').value)) 
			$('save_button_div').show()
		else
			$('save_button_div').hide()
	});
  },
  
  load_content: function() {
    this.dialog.setContent(this.dialog_template);
  },
  
  apply_conflict_triggers: function() {
    if (this.job_builder.conflict_triggers && this.job_builder.conflict_triggers.paper_ids) {
      $H(this.job_builder.conflict_triggers.paper_ids).each(function(pair) {
        if ($('paper-item-' + pair.key)) {
    			$('paper-item-' + pair.key).addClassName('conflicted');
    			$('paper-item-' + pair.key).writeAttribute('title', pair.value);
    		}
      });
    }
    
    if (this.job_builder.conflict_triggers && this.job_builder.conflict_triggers.envelope_ids) {
      $H(this.job_builder.conflict_triggers.envelope_ids).each(function(pair) {
        $$('select#envelope_id option[value=' + pair.key + ']')[0].writeAttribute('disabled', true);
        $$('select#envelope_id option[value=' + pair.key + ']')[0].writeAttribute('title', pair.value);
      });
    }
  },
  
  filter: function(weight, coating) {
    var tthis = this;
  	if (coating != tthis.last_coating) {
  		last_changed = "coating"
  	} else {
  		last_changed = "weight"
  	}
  	
	  tthis.last_coating = coating;
	  
    new Ajax.Request(this.job_builder.jobs_path + "/papers", {
      method: 'get',
      parameters: {weight: weight, coating: coating, last_changed: last_changed},
      
      onSuccess: function(transport) {
        $('papers').innerHTML = transport.responseText;
        $('papers').highlight();
        $('papers').scrollTop = 0;
        tthis.paper_item_event_handlers();
        tthis.apply_conflict_triggers();
      }.bind(this)
    });
  },
  
  choose: function(id, predefined_job_setup) {
    //container = $('paper-item-' + id);  removed by mitch doesn't seem to have any purpose and is causing IE to crash
    var paper = this.attributes(id);
    
    if (!predefined_job_setup && this.job_builder.conflict_triggers && this.job_builder.conflict_triggers.paper_ids &&
        this.job_builder.conflict_triggers.paper_ids[id.toString()]) {
      conflict_message = this.job_builder.conflict_triggers.paper_ids[id.toString()];
      alert(conflict_message);
      return false;
    }
    // TODO need a better way to determine if there are conflicts, and force load of paper.
	// for now we are checking for "Poster" in the title, which is the only case that can cause conflicts
    if ($('job_paper_id').value=="undefined" || $('job_paper_id').value=="" || !predefined_job_setup || this.was_set_by_predefined_job || paper.title.indexOf("Poster")!=-1) {
  		$('job_paper_label').update(paper.title);
  		$('job_paper_id').value = paper.id;
  	
  		// Notify Job Editor:
  		this.job_builder.job_editor.set_paper_type(paper.title);
  		this.was_set_by_predefined_job = predefined_job_setup
  		}

  	return true;
  },
  
  attributes: function(id) {
    return this.papers[id] || {};
  }
});

/** Controller for Finishing Options **/
JobBuilder.FinishingOptionSelector = Class.create({
  initialize: function(job_builder) {
    this.job_builder = job_builder;
    this.dialog_template = "";
    this.finishing_options = {};
  },
  
  changed: function() {
    return this.job_builder.update();
  },
  
  create_dialog: function() {
    this.dialog = new UI.Window({ 
			theme:  "alphacube",
			shadowTheme: "mac_shadow",
			shadow: true,
			width:  810,
			height: 360,
			resizable: false
	 	});
	 	
	this.load_content();
  },
  
  show: function() {
  	hideTopBar()
  	if (this.dialog == null || !this.dialog.visible) {
  	  this.create_dialog();
  		this.dialog.show(true).activate().center();
  		this.adjust_dialog_bounds();
  		this.apply_conflict_triggers();
  		this.event_handlers();
  	}
  	
  	this.dialog.observe('hiding', function() {
      $('job_fold_across_long_edge').value = ($('fold_across_long_edge').checked ? '1' : '');
      
      // Notify Job Editor:
      this.job_builder.job_editor.set_fold_across_long_edge($('fold_across_long_edge').checked);
      
      this.changed();
    }.bindAsEventListener(this));
    
  	
  	$('fold_across_long_edge').checked = ($('job_fold_across_long_edge').value == '1');
  },
  
  adjust_dialog_bounds: function() {
  	return; // no longer used
    bounds = this.dialog.getBounds();
		if (bounds.top < 65) {
		  bounds.top = 65;
		  this.dialog.setBounds(bounds);
		}
  },
  
  load_content: function() {
    this.dialog.setContent(this.dialog_template);
  },
  
  apply_conflict_triggers: function() {
    if (this.job_builder.conflict_triggers && this.job_builder.conflict_triggers.finishing_option_ids) {
      $H(this.job_builder.conflict_triggers.finishing_option_ids).each(function(pair) {
        $('finishing-option-' + pair.key).addClassName('conflicted');
        $('finishing-option-' + pair.key).writeAttribute('title', pair.value);
      });
    }
  },
  
  event_handlers: function() {
    $$('.finishing-option').each(function(element) {
  		Event.observe(element, 'click', function() {
  			var id = element.id.substr(17);
  			if (this.choose(id)) {
  			  this.dialog.close();
  			  this.changed();
			  }
  		}.bindAsEventListener(this));
  	}.bind(this));
  },
  
  choose: function(id, ignore_errors) {
    var container = $('finishing-option-item-' + id); // changed to a local by mitch
    var finishing_option = this.attributes(id);
    
    if (!ignore_errors && this.job_builder.conflict_triggers && this.job_builder.conflict_triggers.finishing_option_ids &&
        this.job_builder.conflict_triggers.finishing_option_ids[id.toString()]) {
      conflict_message = this.job_builder.conflict_triggers.finishing_option_ids[id.toString()];
      alert(conflict_message);
      return false;
    }
    
    $('job_finishing_option_id').value = id;
    $('job_finishing_option_label').update(finishing_option.name);
    
    // Notify Editor:
    this.job_builder.job_editor.set_finishing_option(finishing_option.name);
    this.job_builder.job_editor.set_fold_count(finishing_option.fold_count);
    
    $$('.finishing-option').each(function(o) { Element.removeClassName(o, 'finishing-option-selected') });
  	Element.addClassName(container, 'finishing-option-selected');
  	return true;
  },
  
  attributes: function(id) {
    return this.finishing_options[id] || {};
  }
  
});

var LoadFilesHints = Class.create({
	
  initialize: function() {
  	this.window_manager = new UI.WindowManager({container: 'container'}); 
	this.user_has_disabled = false;
  },
  
  show: function(state){
  	this.state = state;
  	if (!this.user_has_disabled) {
		if (!this.dialog) {
			this.dialog = new UI.Window({ 
				theme:  "alphacube",
				shadowTheme: "mac_shadow",
				shadow: true,
				width:  300,
				height: 193,
				left: 385,
				top: 162,
				resizable: false,
				windowManager: this.window_manager})
				.observe('hiding', this.disable.bindAsEventListener(this));
		}
  		this.dialog.setContent($('load-files-'+state).innerHTML);
  		this.dialog.show(false).activate();
  		help_system.add_help_links('.load-files-hint');
  	}
  },
  
  disable: function(){
  	this.user_has_disabled = true;
  },
	
  hide: function() {
  	var old_user_has_disabled = this.user_has_disabled;
  	if (this.dialog) this.dialog.hide();
	this.user_has_disabled = old_user_has_disabled;
  }
  
})

var load_files_hints;

document.observe('dom:loaded', function() {
  load_files_hints = new LoadFilesHints();
  if ($('request_login')) LoginWindow.show()
});
