new function() {

FILTER  = '';

var UPLOADS = 0;

var project, tip, site, user;

start(function() {  
  tip = content.find('tip');
});


O3.user = function(f) {
  var key;
  if (key = O3.cookie().key)
    xhr(url('/session/user', { key: key }), function(r) {
      if (user = user || r.page)
        f(user);
    });
  else f({})
}

bind('content', {
  
  'Download 2D drawing': function(part) {
    this.exec('Download file', part, '2D', 'Drawing');
  },
  
  'Download 3D model': function(part) {
    this.exec('Download file', part, '3D', 'Model');
  },

  'Download file': function(part, type, name) {
    var params = {
      '3D Partstream ID': part['Partstream ID'], type: type
    };
    var formats;
    if (formats = CONFIG[name + ' formats']) {
      content.dialog('Download ' + name.toLowerCase() + ' for ' + part['Part number']).build(function() {
        this.apply('download');
        this.add('options').fills(formats, function(o) {
          this.add('option').sets(o.name);
        });
      }).apply('progress').ext({

        'Submit dialog': function() {
          var d = this, format, name = this.find('options').value();
          for (var i = 0; i < formats.length; i++) {
            if (formats[i].name == name) {
              format = formats[i];
              break;
            }
          };
          xhr('/part_stream/download', cp(params, format), function(r) {
            if (r.ok && r.ok.location) {
              window.location = r.ok.location;
              content.exec('Close dialog');
            }
            if (r.error)
              d.remove('control') && d.remove('button') && d.find('explanation').sets(r.reason);
          });
          this.apply('busy')
          return true;
        }
      }).pos();
    }
  },

  'View partstream': function(part) {
    xhr('/part_stream/view', {
      '3D Partstream ID': part['Partstream ID']
    }, function(r) {
      if (r.ok && r.ok.location)
        content.dialog('').build(function() {
          this.reset({
            'iframe': {
              width: 700,
              height: 560,
              src: r.ok.location
            }
          });
          // this.node.id = 'Viewer';
          // this.node.innerHTML = '<embed width="650" height="450" vmpclassid="{03F998B2-0E00-11D3-A498-00104B6EB52E}" genieminimumversion="50333440" componentminimumversion="50333440" hostminimumversion="50333440" xmltext="" pluginurl="" instancename="MetaCtl0" properties="mts3interfaceversion=05.00.02.29;name=MetaCtl0;starthidden=true;" broadcastkeyfileurl="http://www.viewpoint.com/installer/UniversalBroadcastKey.mtx" id="MetaCtl0" name="MetaCtl0" script="true" type="application/x-mtx" source="'+r.ok.location+'" componentfilename="SceneComponent.mtc" component="ISceneComponent"/>';
          // new MTSPlugin( r.ok.location, 700, 400, "bkey.mtx", 'popup', 'contenttype=3; layer=Viewer; ComponentMinimumVersion=50335395; GenieMinimumVersion=50335395; HostMinimumVersion= 50335395; RequiredVersions=SWFView.dll=3.0.14.163, Cursors.dll=3.0.15.16, VMPSpeech.dll=3.0.14.163, LensFlares.dll=3.0.14.163, SreeD.dll=3.0.14.163, SreeDMMX.dll=3.0.14.163, Mts3Reader.dll=3.0.14.163;');
          // this.reset({
          //   'iframe': {
          //     width: 700,
          //     height: 400,
          //     src: r.ok.location
          //     //src: 'http://www.3dpublisher.net/SWService/outfile.asp?viewfile=/SWDownloads1/2044368049-267177/PT0609200975912.MTS'
          //   }
          // })
        }).pos().node.style.marginLeft = '-395px';
    });
  },

  'Add part to a project': function(part) {
    O3.user(function(user) {
      xhr(url('/api/projects/all', { person_id: user.id }), function(r) {
        var projects;
        if (r.ok && (projects = r.object))
          content.dialog('Add ' + (part['Part number'] || 'part') + ' to a project', 'Add').build(function() {
            this.apply('add');
            this.add('inner').apply('fields').send(function() {
              this.add('field').sets('Add part to:').build(function() {
                this.reset({
                  'select.options.control': {
                    name: 'project',
                    inner: tags('option.option', ['new project'].concat(projects), function(project) {
                      return {
                        data: project.Name || project,
                        value: project._id || false 
                      }
                    }).inner
                  }
                }).options.observe('change', function() {
                  this.next('field').update(this.first().node.selected);                
                }).update(O3.cookie().project_id || 'new project');
              });
              this.add('field').sets('Name:').build(function() {
                this.add('single');
              }).ext({
                update: function(on) {
                  on ? this.show() : this.hide();
                }
              }).update( !O3.cookie().project_id );
            }); 
            this.add('inner').apply('feedback').hide();
          }).ext({

            'Submit dialog': function() {
              var mod = this.controls(), d = this;

              function createPartAssignment(project_id) {
                xhr({ _type: 'PartAssignment', project_id: parseInt(project_id.split('/')[1]), part_id: part.id }, function(r) {
                  if (r.ok) {
                    O3.cookie({ project_id: project_id });

                    content.find('globals').send(function() {
                      if (!this.find('projects'))
                        load('a.link.projects', { data: 'Projects', href: '?Projects=true' }).move(this, this.find('logout'));
                    })
                    d.finalize('Added ' + (part['Part number'] || 'part'));
                  }
                });              
              }

              if (mod.project == 'new project')
                xhr({ _type: 'Project', Template: 'Project', Name: mod.Name, person_id: user.id }, function(r) {
                  if (r.ok)
                    createPartAssignment(r.ids[0]);
                });
              else
                createPartAssignment(mod.project);
              return false;
            },

            finalize: function(message) {
              this.hide('fields');
              this.find('explanation').sets(message);

              this.find('button').sets('View project').set('href', url(O3.cookie().project_id))
                .next('button').sets('Close').set('title', 'Close dialog');
            }

          }).pos();      
      })    
    })
  },
        
  'Rename this project': function() {
    var id = window.location.pathname.slice(1);

    xhr('/api/' + id, function(r) {
      var project;
      if (project = r.page)
        content.apply('dimmed').add('dialog').build(function() {
          this.add('explanation').sets('Rename this project');

          this.add('inner.fields').send(function() {
            this.add('field').sets('Name:').build(function() {
              this.add('single').update(project.Name);
            });
            this.add('buttons').adds({ 'Cancel': 0, 'Rename': 1 });
          });
          this.add('inner.feedback').hide().send(function() {
            this.add('inner');
            this.add('buttons').adds({ 'Cancel': 0, 'Back': 1 });
          });

          this.apply('edit')
        }).ext({

          'onRename': function() {
            var rename = this.find('single').value();
            if (rename) {
              content.find('projectsList').visit('opt', function() {
                if (this.read('value') == id)
                  project.Name = this.node.firstChild.data = rename;
              });
              xhr(project);
              this.close();
            } else {
              this.apply('error');
              this.hide('fields');
              this.show('feedback').sets('Name cannot be blank.');
            }
          },

          'onBack': function() {
            this.clear('error');
            this.hide('feedback');
            this.show('fields');
          },

          'onCancel': function() {
            this.close();
          }
        }).pos();
        
    })
  },
    
  'Delete this project': function() {
    this.dialog('Are you sure you wish to delete this project?', 'Delete').build(function() {
      this.apply('important');
    }).ext({
      'Submit dialog': function() {
        var id = window.location.pathname.slice(1);
        xhr({ _delete: true, _id: id }, function(r) {
          if (!content.find('projectsList').visit('opt', function() {
            if (this.node.value != id) {
              O3.cookie({ project_id: this.node.value });
              return window.location = '/' + this.node.value;
            }
          })) {
            O3.cookie({ project_id: null });
            window.location = '/';
          }
          
        });
      }
    });
  },
  
  'Edit part details': function(detail, pa, id) {
    this.dialog('Edit ' + id, 'Save').build(function() {
      this.apply('edit').add('field').sets('New value:').build(function() {
        this.add('multi').update(pa[id]);
      });
    }).pos().ext({
      
      'Submit dialog': function() {
        detail.update(pa[id] = this.controls()['New value']);
        xhr(pa);
      }
    });
  },
  
  'Delete part from project': function(o, ic) {
    xhr({ _delete: true, _id: 'part_assignments/' + o.id }, function(r) {
      if (r.ok)
        ic.up('part').fade(0.05, true)
    });
  },
  
  'Add custom part': function() {
    this.dialog().build(function() {
      var i = UPLOADS++;
      
      this.apply('upload').reset({
        '.explanation': 'Upload a custom part to your project',
        'form.inner.fields': {
          'target':  'target-' + i,
          'method':  'POST',
          'enctype': 'multipart/form-data',
          'action':  '/assets/upload?html=true',
          '.field:1': {
            'label': 'Name:',
            '.inner.contents': {
              'input.single.control': { type: 'text' }
            }
          },
          '.field.progress:2': {
            'label': 'Drawing/Image of part (MAX:1MB):',
            '.inner.contents': {
              'input.control.file': {
                'name': 'asset',
                'type': 'file'
              }
            }
          },
          '.field:3': {
            'label': 'Additional notes:',
            '.inner.contents': {
              'textarea.multi.control': ''
            }
          }
        },
        'iframe': {
          style: 'width: 0; height: 0; border: 0',
          name: 'target-' + i,
          onload: function() {
            var url;
            try {
              if (url = (this.contentDocument || this.contentWindow.document).body.innerHTML)
                xhr('/assets/reformat', {
                  id: url.match(/\/\/[^\/]+\/([a-zA-Z0-9]+)/)[1],
                  format: { mime: 'image/jpeg', width: 99, height: 80 }
                }, function(r) {
                  content.open.finalize(r.url);
                });
            } catch (e) {}
          }
        }
      });
    }).pos().ext({
      
      finalize: function(url) {
        var mods = this.clear('busy').controls();
        xhr({
          _type: 'PartAssignment',
          project_id: parseInt(window.location.pathname.split('/')[2]),
          'Part details': mods['Name'], 
          'Image URL': url, 
          'Custom details': mods['Additional notes']
        }, function(r) {
          if (r.ok)
            window.location.href = window.location.pathname;
        });
      },

      'Submit dialog': function() {
        if (this.find('file').value())
          this.apply('busy').find('fields').node.submit();
        else
          this.finalize();
        return true;
      }
    });
  },
  
  'Make enquiry': function() {    
    this.dialog('Please tell us as much as you can about your requirements so that we may better respond to your enquiry.').build(function() {
      this.apply('mail');
      this.add('inner').apply('fields').send(function() {
        this.add('multi').set('name', 'Enquiry');
      });
      this.add('inner').apply('feedback').send(function() {
      });
      
    }).pos().ext({
      
      'Submit dialog': function() {
        var com = this;
        if (!this.done)
          xhr('/mail/enquiry', {message: this.controls()['Enquiry'], project_id: window.location.pathname.replace(/[^\d]+/g,'')}, function(r) {
            com.hide('fields');
            com.find('weak').hide();
            if(r.ok){
              com.find('explanation').sets('Thanks - your enquiry has been recieved');
            }else if(r.reason){
              com.find('explanation').sets(r.reason);
            }else{
              com.find('explanation').sets('Unknown error');
            }
            com.done = true;
          });     
        else
          content.exec('Close dialog');
        return false;
      }
    });
  },
  
  'Submit dialog': function() {
    this.exec('Close dialog');
  },
  
  'Close dialog': function() {
    this.node.ownerDocument.documentElement.className = '';
    
    if (this.open) {
      this.clear('dimmed');
      this.open = !this.open.remove();
    }
  },
  
  onClick: function(event) {
    if (Com.drop.open)
      return Com.drop.open.toggle(false);
  },
  
  dialog: function(explanation, action) {
    this.node.ownerDocument.documentElement.className = 'fixed';
    
    return Com.dialog.spawn().move(this.apply('dimmed')).build(function() {
      this.apply('cleared');
      this.add('explanation').sets(explanation);
    }).ammend(function() {
      this.add('button').sets(action || 'OK').set('title', 'Submit dialog');
      this.add('button').apply('weak').sets('Cancel').set('title', 'Close dialog');
    });
  }
});

bind('dialog', {

  close: function() {
    content.clear('dimmed').open = !this.remove();
  },

  pos: function() {
    try {
      this.node.style.marginTop = '-' + Math.round(this.node.offsetHeight / 2) + 'px';
    } catch (e) {}
    return this;
    //return this.set('style', 'margin-top: -' + Math.round(this.node.offsetHeight / 2) + 'px')
  }
  
}).spawn = function() {
  return content.open = load('.dialog.pane', { '.TR': '', '.contents.inner': '', '.BL': '' });
}

def('div.buttons', '', {
  adds: function(o) {
    for (var id in o)
      this.add('button').toggle(o[id] < 1, 'weak').sets(id);
  }
});

bind('folder', {
    
  onExec: function() {
    this.toggle(!this.folder_on, 'folder_on');
    return false;
  }
});

base({
  
  /// Load the JSON stashed in .href
  stash: function() {
    var v = this.read('href') || '';
    if (v.charAt(0) == '#')
      return JSON.parse(v.slice(1));
  }
});

bind('pitem', {
  
  onExec: function(id, ev) {
    if (ev.ic) {
      if (ev.ic.read() == 'Delete part') {
        this.remove();
        xhr(cp({ _delete: true }, ev.ic.stash()));
        return false;      
      }
    }
  }
});

bind('actions', {
  
  onExec: function(id, ev) {
    this.parent.fire('exec', ev.ic.read(), JSON.parse(id), ev.ic);
    return false;      
  }
});

bind('pref', {
  
  onExec: function(v, ev) {
    if (window.parent && top.cycle) {
      v = parseInt(ev.ic.read());
      this.update(v);
      xhr(cp({ 'Preferability': v }, ev.ic.stash()));
    }
    return false;
  },
  
  update: function(n) {
    this.each('ic', function() { this.toggle(!this.match('remove') && n-- >= 0) });
    return this;
  }
});

bind('prefInfo', {
  
  onMouseover: function() {
    tip.update(this, function() {
      this.add('inner').sets('This colunm shows whether or not the part is a perferred size or if availability is limited.');
      this.add('inner').sets('Please enquire about items with a low availability.');
    });
  }
});

bind('a', {
    
  onMouseover: function() {
    tip.update(this, this.ic.read());
  }
});

bind('tip', {
  
  update: function(parent, v) {
    if (this.parent != parent)
      return this.move(parent).build(function() {
        this.empty();
        typeof v == 'function' ? v.apply(this) : this.sets(v);
      });
  }
});

bind('login', {
    
  onEnter: function(control) {
    if (control == this.last('control'))
      this.exec('login');
  },
  
  onLogin: function() {
    var com = this;
    xhr('/session/login', this.controls(), function(r) {
      if (r.ok && r.key) {
        O3.cookie({ key: r.key });
        window.location = window.location.href.replace('?Login=true', '');
      }
      if (r.error)
        com.find('error').sets(r.reason);
    })
  }
});

bind('Account', {
  
  onEnter: function(control) {
    if (control == this.last('control'))
      this.exec('submit');
  },
  
  onSubmit: function() {
    this.each('error', function() {
      this.sets('');
    });
    var com = this;
    O3.user(function(user) {
      xhr(cp({ _type: 'Person' }, user, com.controls()), function(r) {
        if (r.error)
          if (r.error.fields)
            com.fire('error', r.error.fields).node.scrollIntoView();
          else if (r.reason)
            com.find('error').sets(r.reason).node.scrollIntoView();
        if (r.ok)
          window.location = window.location.href.replace('Account', user && user._id ? 'Account updated' : 'Signup completed')
      });      
    })
  },
  
  onError: function(o) {
    this.controls(function(name, value) {
      this.next('error').sets(o[name] || '');
    })
  }
});

bind('filter', {
  init: function() {
    this.observe('click', function(e) {
      var s = this.read('href');
      FILTER = s.slice(s.indexOf('?') + 1);
      xhr(s, function(r) {
        content.find('below').reset(r);
      })
      if (e.stopPropagation)
        e.stopPropagation();
      return false;
    })
  }
})


bind('error');
bind('part');
bind('options', 'control', {
  
  value: function() {
    var option = this.node.options[this.node.selectedIndex];
    return option.value || option.text;
  }
});
bind('option');
bind('opt');

bind('detail', {
  
  init: function() {
    this.observe('click', function() {
      var v = this.id();
      this.fire('exec', 'Edit part details', this, { _id: v[0] }, v[1]);
      return false;
    })
  },
  
  update: function(s) {
    return this.sets(s || 'Click to edit').toggle(!s, 'blank');
  },
  
  id: function() {
    return this.read('href').slice(1).split('-')
  }
});

// function Project(user, name, body) {
//   var BR = "\n\n";
//   
//   var s = '', o, parts = user['Projects'][name]['Parts'];
//   
//   s += 'Web enquiry from ' + user['Email'] + ':';
//   s += BR;
//   s += "Project '" + name + "'";
//   s += BR;
//   for (var id in parts) {
//     for (var _id in parts[id])
//       switch (_id) {
//         case 'Product thumbnail': s += _id + ': ' + O3.asset({ 'Image file': parts[id][_id]['Image file'] }) + "\n"; break;
//         default: {
//           if (o = parts[id][_id])
//             if (typeof o == 'string')
//               if (!/ID/.test(_id))
//                 s += _id + ': ' + o + "\n";
//         }
//       }
//   }
//   s += "\n";
//   s += 'Enquiry:' + "\n";
//   s += body;
//   
//   return s;
// }

// =================================================================================

bind('globals', {
    
  onLogout: function() {
    O3.cookie({ key: null })
    window.location = window.location.href;
    return false;
  }
})

bind('tabs', {
  
  init: function() {
    var com;
    if (com = this.find('search'))
      com.observe('click', function() {
        this.parent.toggle(!this.expanded, 'expanded').next('search', true).toggle().send(function() {
          if (this.on)
            this.find('control').node.focus();
        });
        return false;
      })
  }
});
bind('listing')
}