// Copyright 2005 Google Inc.
// All Rights Reserved.

 /**
   * Functions used by TextCreativeEditorForm and ImageCreativeEditor form
   *
   * This script expects &lt;span&gt; elements with the following IDs
   * to be defined in the page which includes it:
   *  wzCreateAd-ExampleLine1 - Line 1 (headline) of example ad text
   *  wzCreateAd-ExampleLine2 - Line 2 (description line 1) of example ad
   *  wzCreateAd-ExampleLine3 - Line 3 (description line 2) of example ad
   *  wzCreateAd-ExampleLine4 - Line 4 (display URL) of example ad
   *
   * Copyright 2004-2005 Google Inc.  All Rights Reserved
   */

  /** Namespace */
  function wzCreateAd(){};

  /**
   * Handler for changing the anchor href attribute in the example ad
   */
  wzCreateAd.urlChanged = function() {
    awCreateAdUtil.urlChanged("exampleUrl",
        "wzCreateAdProtocol","wzCreateAd-ExampleProtocol",
        "wzCreateAdLine5","wzCreateAd-ExampleUrl");

    awCreateAdUtil.urlChanged("longExampleUrl",
        "wzCreateAdProtocol","wzCreateAd-ExampleProtocol",
        "wzCreateAdLine5","wzCreateAd-ExampleUrl");
  }

  /**
   * Handler for keypress events in the Long Description field
   */
  wzCreateAd.descChanged = function() {
    var field = document.getElementById("wzCreateAdDescription");
    if (!field) return;

    var maxLen = parseInt(awCreateAdUtil.getMessage("wzCreateAd-MaxLenDescription"));
    if (!maxLen) return;

    var defaultText = awCreateAdUtil.getMessage("wzCreateAd-ExampleDescription");

    awCreateAdUtil.enforceFieldLimit(field, maxLen, false);

    // Stick the entire text string into the long description example field
    var value = (field.value.length > 0) ? field.value : defaultText;
    awCreateAdUtil.setText("longExampleDesc", value.replace("\n", " "));

    // Wrap the long description into 35-character lines for the short example
    var wrapLen = parseInt(awCreateAdUtil.getMessage("wzCreateAd-MaxLen2"));
    var wrapped = wzCreateAd.wrapText(value, wrapLen);
    if (wrapped[2]) {
      wrapped[1] += "\u2026"; // '...';
    }
    awCreateAdUtil.setText("example2", wrapped[0]);
    awCreateAdUtil.setText("example3", wrapped[1]);
  }

  /**
   * Does line wrapping.  Splits a text string into multiple lines of length
   * lineLen or less, splitting at spaces, tabs, or newlines.
   */
  wzCreateAd.wrapText = function(text, lineLen) {
    var result = new Array();

    var resultIndex = 0;    // Which line we're working on
    var breakPos = -1;      // Last break position found
    var lastBreak = 0;      // Where last line ended
    var width = 0;          // Length of line so far
    var breakWidth = 0;     // Length of line at last break position

    for (var i = 0; i < text.length; i++) {
      var forceBreak = false;
      var c = text.charAt(i);
      width += awCreateAdUtil.displayWidth(c);

      if (c == "\n") {
        breakPos = i;
        if (width * 100 / lineLen >= 60) {
          forceBreak = true;
        }
        i++;
      } else if (wzCreateAd.isSpace(c)) {
        breakPos = i;
        breakWidth = width;
      }

      if (forceBreak || width > lineLen) {
        if (breakPos < 0) {
          // If all else fails, just force a line break regardless of spaces
          result[resultIndex++] = text.substring(lastBreak, i) + "-";
          lastBreak = i;
          width = 0;
        } else {
          result[resultIndex++] = text.substring(lastBreak, breakPos);
          lastBreak = breakPos + 1;
          width = width - breakWidth;
        }
      }
    }
    if (text.length > lastBreak) {
      result[resultIndex++] = text.substring(lastBreak, text.length);
    }

    for (var i in result) {
      result[i] = result[i].replace("\n", " ");
    }
    return result;
  }

  /**
   * Indicates whether the given character is a space at which line wrapping
   * can occur.
   */
  wzCreateAd.isSpace = function(c) {
    return c == ' '
        || c == '\u0009'
        || c == '\u000a'
        || c == '\u000d';
  }

  /**
   * Sets up the initial state of the Create Ad Page.  This should be called
   * when the page loads, and from the clear button's click handler.  It copies
   * the text from the entry fields into the example, except that empty text is
   * replaced by the corresponding text from the sample ad.
   */
  wzCreateAd.resetTextExample = function() {
    // Bail if there are no messages (the image ad page has none)
    var canary = document.getElementById("wzCreateAd-ExampleLine1");
    if (canary == null) return;
    awCreateAdUtil.textChanged("wzCreateAdLine1", "example1", "wzCreateAd-MaxLen1", "wzCreateAd-ExampleLine1");
    awCreateAdUtil.textChanged("wzCreateAdLine2", "example2", "wzCreateAd-MaxLen2", "wzCreateAd-ExampleLine2");
    awCreateAdUtil.textChanged("wzCreateAdLine3", "example3", "wzCreateAd-MaxLen3", "wzCreateAd-ExampleLine3");
    awCreateAdUtil.textChanged("wzCreateAdLine4", "example4", "wzCreateAd-MaxLen4", "wzCreateAd-ExampleLine4");
    awCreateAdUtil.textChanged("wzCreateAdLine5", "example5", "wzCreateAd-MaxLen5", "");

    wzCreateAd.descChanged();
    wzCreateAd.urlChanged();

  }

  /** OnClick handler for the "Clear Ad" button */
  wzCreateAd.clearAd = function() {

    // Text Ad Fields
    awCreateAdUtil.clearField("wzCreateAdLine1");
    awCreateAdUtil.clearField("wzCreateAdLine2");
    awCreateAdUtil.clearField("wzCreateAdLine3");
    awCreateAdUtil.clearField("wzCreateAdDescription");
    awCreateAdUtil.clearField("wzCreateAdLine4");
    awCreateAdUtil.clearField("wzCreateAdLine5");

    // Image Ad Fields
    awCreateAdUtil.clearField("wzCreateImageAdName");
    awCreateAdUtil.clearField("wzCreateImageAdLine3");
    awCreateAdUtil.clearField("wzCreateImageAdLine4");
    awCreateAdUtil.clearField("wzCreateImageAdLine5");
    awCreateAdUtil.clearField("wzSelectImage");
    awCreateAdUtil.clearCheckbox("wzCreateImageAdCheckbox");

    wzCreateAd.resetTextExample();

    // Reset to the first user-entry input field
    // - Only one of these controllers exist per page.
    focusField('imageController.imageCreative.creativeName');
    focusField('textController.textCreative.headline');

    return false; // Don't submit the page
  }

  /** event handlers for the text entry fields */
  wzCreateAd.line1changed = function() {
    awCreateAdUtil.textChanged("wzCreateAdLine1", "example1", "wzCreateAd-MaxLen1",
                           "wzCreateAd-ExampleLine1");
    return true;
  }

  wzCreateAd.line2changed = function() {
    awCreateAdUtil.textChanged("wzCreateAdLine2", "example2", "wzCreateAd-MaxLen2",
                           "wzCreateAd-ExampleLine2");
    return true;
  }

  wzCreateAd.line3changed = function() {
    awCreateAdUtil.textChanged("wzCreateAdLine3", "example3", "wzCreateAd-MaxLen3",
                           "wzCreateAd-ExampleLine3");
    return true;
  }

  wzCreateAd.line4changed = function() {
    awCreateAdUtil.textChanged("wzCreateAdLine4", "example4", "wzCreateAd-MaxLen4",
                           "wzCreateAd-ExampleLine4");
    return true;
  }

  wzCreateAd.line5changed = function() {
    awCreateAdUtil.textChanged("wzCreateAdLine5", "example5", "wzCreateAd-MaxLen5", "");
    wzCreateAd.urlChanged();
    awCreateAdUtil.pickCorrectProtocol("wzCreateAdProtocol", "wzCreateAdLine5");

    return true;
  }

  wzCreateAd.protocolchanged = function() {
    wzCreateAd.urlChanged();
    return true;
  }

  wzCreateAd.line4focused = function() {
    // If the visible URL field is empty, copy the dest URL into it
    awCreateAdUtil.copyValueWithMaxLen("wzCreateAdLine4", "wzCreateAdLine5",
                                   "wzCreateAd-MaxLen4");
    wzCreateAd.line4changed();
    return true;
  }

  wzCreateAd.line4blurred = function() {
    // If the dest URL field is empty, copy the visible URL into it
    awCreateAdUtil.copyValue("wzCreateAdLine5", "wzCreateAdLine4");
    wzCreateAd.line4changed();
    wzCreateAd.line5changed();
    return true;
  }

  wzCreateAd.line5focused = function() {
    // If the dest URL field is empty, copy the visible URL into it
    awCreateAdUtil.copyValue("wzCreateAdLine5", "wzCreateAdLine4");
    wzCreateAd.line5changed();
    return true;
  }

  wzCreateAd.line5blurred = function() {
    // If the visible URL field is empty, copy the dest URL into it
    awCreateAdUtil.copyValueWithMaxLen("wzCreateAdLine4", "wzCreateAdLine5",
                                   "wzCreateAd-MaxLen4");
    wzCreateAd.line4changed();
    wzCreateAd.line5changed();
    return true;
  }

  wzCreateAd.imageLine4blurred = function() {
    awCreateAdUtil.copyValue("wzCreateImageAdLine5", "wzCreateImageAdLine4");
  }

  wzCreateAd.imageLine4focused = function() {
    awCreateAdUtil.copyValueWithMaxLen("wzCreateImageAdLine4",
        "wzCreateImageAdLine5", "wzCreateAd-MaxLen4");
  }

  wzCreateAd.imageLine5blurred = function() {
    awCreateAdUtil.copyValueWithMaxLen("wzCreateImageAdLine4",
        "wzCreateImageAdLine5", "wzCreateAd-MaxLen4");
  }

  wzCreateAd.imageLine5focused = function() {
    awCreateAdUtil.copyValue("wzCreateImageAdLine5", "wzCreateImageAdLine4");
  }

  wzCreateAd.pickCorrectImageProtocol = function() {
    awCreateAdUtil.pickCorrectProtocol("wzCreateImageAdProtocol", "wzCreateImageAdLine5");
  }


  /** Runs at page load time */
  wzCreateAd.init = function() {
    // Lines one and two are optional, text only. Both forms have lines three
    // through five.

    for (var i = 1; i <= 5; i++) {
      var elm = document.getElementById("wzCreateAdLine" + i);
      if (elm) {
        elm.onkeydown = elm.onkeyup = elm.onblur =
            wzCreateAd["line" + i + "changed"];
      }
    }
    var elm1 = document.getElementById("wzCreateAdLine5");
    if (elm1) {
      elm1.onblur = wzCreateAd.line5blurred;
      elm1.onfocus = wzCreateAd.line5focused;
    }
    var elm2 = document.getElementById("wzCreateAdLine4");
    if (elm2) {
      elm2.onblur = wzCreateAd.line4blurred;
      elm2.onfocus = wzCreateAd.line4focused;
    }
    var elm3 = document.getElementById("wzCreateAdProtocol");
    if (elm3) {
      elm3.onchange = wzCreateAd.protocolchanged;
    }
    var elm4 = document.getElementById("wzCreateImageAdLine4");
    if (elm4) {
      elm4.onblur = wzCreateAd.imageLine4blurred;
      elm4.onfocus = wzCreateAd.imageLine4focused;
    }
    var elm5 = document.getElementById("wzCreateImageAdLine5");
    if (elm5) {
      elm5.onblur = wzCreateAd.imageLine5blurred;
      elm5.onfocus = wzCreateAd.imageLine5focused;
      elm5.onkeydown = elm5.onkeyup = elm5.onchange =
          wzCreateAd.pickCorrectImageProtocol;
    }

    wzCreateAd.resetTextExample();

    var reset = document.getElementById("resetAdButton");
    if (reset) {
      reset.onclick = wzCreateAd.clearAd;
    }

    // Handler for the long-description field.
    var desc = document.getElementById("wzCreateAdDescription");
    if (desc) {
      desc.onkeydown = desc.onkeyup = desc.onblur = wzCreateAd.descChanged;
    }
  }

  AW_Utils.addEvent(window, "onload", wzCreateAd.init);
