if (Prototype.Browser.Opera) {
  var console = {
    log: function(str) {
      opera.postError(str);
    }
  }
}

var Global = {
  required: [],

  require: function(required) {
    if (required.constructor.toString().indexOf('Array') == -1 ) {
      required = [required];
    }
    required.each( function(script) {
      if (script.charAt(0) != '/') {
        script = '/javascripts/' + script;
      }
      if (script.slice(-3) != '.js') {
          script += '.js';
      }
      if (Global.required.indexOf(script) == -1) {
        Global.required.push(script);
        document.write('<script type="text/javascript" src="'+script+'"></script>');
      }
    } );
  },

  getArgs: function() {
    var args = new Object();
    var query = location.search.substring( 1 );
    var pairs = query.split('&');
    for (var i = 0; i < pairs.length; i++)
    {
        var pos = pairs[i].indexOf('=');
        if ( pos == -1 ) continue;
        var argname = pairs[i].substring( 0, pos );
        var value = pairs[i].substring( pos + 1 );
        args[argname] = unescape( value );
    }
    return args;
  },

  load: function() {
    var required = ['lib/scriptaculous', 'lib/forms', 'lib/modalbox'];
    var url = location.href;
    if (url.indexOf('#') > -1) {
      url = url.substring(0, url.indexOf('#'));
    }
    if (url.indexOf('?') > -1) {
      url = url.substring(0, url.indexOf('?'));
    }
    var url_array = url.split('/');
    Global.url_array = url_array;
    if (url_array[3]) {
      // '/{this}'
      Global.controller = url_array[3];
      //required.push(Global.controller + '/' + Global.controller);
      required.push(Global.controller);
      if (url_array[4]) {
        // '/organizations/{this}'
        if (isNaN(parseInt(url_array[4]))) {
          // '/organizations/people'
          Global.action = url_array[4];
        }
        else {
          // '/organizations/7'
          Global.object_id = url_array[4];
          if (url_array[5]) {
            // '/organizations/7/{this}'
            Global.action = url_array[5];
            if (url_array[6]) {
              // '/organizations/7/people/{this}'
              if (isNaN(parseInt(url_array[6]))) {
                // '/organizations/7/people/new'
                Global.action += url_array[6].capitalize();
              }
              else {
                // '/organizations/7/people/30'
                Global.action += 'Show';
              }
            }
          }
          else {
            Global.action = 'show';
          }
        }
      }
      else {
        Global.action = 'index';
      }
    }
    else {
      Global.controller = 'home';
      Global.action = 'index';
    }
    Global.require(required);
    Event.observe( window, 'load', function () {
      var controller_obj = Global.controller.gsub('_', '').capitalize();
      // uncomment the following line to see what function is being fired.
      //console.log(controller_obj + '.setup' + Global.action.capitalize());
      Try.these(
        function() { eval(controller_obj + '.setup' + Global.action.capitalize() + '()'); },
        function() { eval(controller_obj + '.setupAll()'); },
        function() { Application.setupAll(); }
      );
    });
    Global.args = Global.getArgs();
    Event.observe(document, 'dom:loaded', function() {
      if (Global.args['highlight']) {
        if ($(Global.args['highlight'])) {
          new Effect.Highlight(Global.args['highlight'], {duration: 2.0});
        }
      }
    } );
  }
}

Global.load();

var Application = {

  setupAll: function() {
    IntranetForms.setupForm();
    /*if ($('loginButton')) {
      $('loginButton').observe('click', function(e) {e.stop(); Modalbox.show('<p>I\'m sorry. That email was not found.</p>', {title: 'Login failed.'}); return false; });
    }*/
    setTimeout("$$('.flash').each(function(e) { Effect.Fade(e, { duration: 2.0 }); });", 4000);
  },

  buildSpinner: function(id_prefix, message) {
    if (id_prefix == undefined) { id_prefix = 'the'; }
    if (message == undefined) { message = ''; }
    return Builder.node('span', {className: 'spinner'}, [Builder.node( 'img', {id: id_prefix + '_spinner', src: '/images/spinner-small.gif', alt: ''} ), ' ' + message] );
  },

  matchField: function(needle, haystack, separator) {
    var r = new RegExp("^" + needle + separator + " (.*)$", "m");
    return r.exec(haystack);
  },

  remove_option: function(select, value) {
    for (var i=0; i<select.options.length; i++) {
      if (select.options[i].value == value) {
        $(select.options[i]).remove();
      }
    }
  },

  array_to_options: function(arr) {
    var retval = [];
    for (var i=0; i<arr.length; i++) {
      retval.push(new Option(arr[i], arr[i]));
    }
    return retval;
  },

  replace_options: function(select, new_options) {
    select = $(select);
    select.options.length = 0;
    for (var i=0; i<new_options.length; i++) {
      select.options[i] = new_options[i];
    }
  },

  goToOrganization: function(n) {
    if ( n.match( /^\d+$/ ) ) {
      window.location.href = '/admin/organizations/' + n.toString();
    }
  },
}

var Home = {
  setupAll: function() {
    $('purLink').observe('click', Home.showPurContent);
    $('hiFiLink').observe('click', Home.showHiFiContent);
    Application.setupAll();
  },

  showPurContent: function() {
    if ($('hiFiContent')) {
      $('hiFiContent').hide();
    }
    $('purLink').up().insert('<div id="purContent" style="display: none; width: 70%; border: 2px solid #666; background: url(/images/bg-translucent.png); position: absolute; top: 3px; left: 50px; padding: 0.5em;">\n<p>\nPUR stands for Polyurethane Reactive Binding. This is a technique in which a very thin layer of hot adhesive is applied on the binding edge. The adhesive cures as it reacts with humidity in the air.</p><p>What are some advantages of PUR?</p><ul><li>It is able to withstand temperature extremes of as much as -40F to 200F (-40C to 93C).</li><li>Can achieve many aesthetic qualities of other binding techniques</li><li>Requires less adhesive and is can lie flat when open for improved reading convenience</li><li>Provides less overlap for crossover images</li><li>Superior adhesion allows PUR bound products to accommodate a wide range of paper types and ink types</li></ul><p><a class="close" href="#" onclick="Effect.BlindUp(\'purContent\'); return false;">close</a></p></div>');

    Effect.BlindDown('purContent');
    //Modalbox.show(content, { title: 'What is PUR?' });
  },

  showHiFiContent: function() {
    if ($('purContent')) {
      $('purContent').hide();
    }
    $('purLink').up().insert('<div id="hiFiContent" style="display: none; width: 70%; border: 2px solid #666; background: white; position: absolute; top: 3px; left: 50px; padding: 0.5em;")\n<img class="left" src="/images/color-gamut-2.jpg" alt="" /><div style="padding: 0.75em;"><p><strong>Hi-Fi</strong> refers to a printing technology that provides a much higher-quality product than the normal four-color process. We use the six-color PANTONE Hexachrome&reg; Hi-Fi ink set, delivering a wider range of colors than the standard CMYK process. Hi-Fi breaks the color barrier and achieves far superior brightness levels, thus improving the authenticity of the final product.</p><p>Hi-Fi technology has two major advantages:</p><blockquote style="margin-left: 36%;"><p>The color space is expanded, adding more brightness and color accuracy, allowing the print color to resemble actual object color more closely.</p><p>Hi-Fi printing creates a more authentic sensation from the visual perspective, thus resulting in a more dimentional picture&mdash;a superior stereoscopic effect.</p></blockquote><img src="/images/hi-fi-sample.jpg" alt="" style="margin-left: 10%;" /><p><a class="close" href="#" onclick="Effect.BlindUp(\'hiFiContent\'); return false;">close</a></p></div></div>');
    Effect.BlindDown('hiFiContent');
  }
}
