// Copyright 2006 Google Inc. All rights reserved.

/**
 * Functions used in campaignmgmt/creatives/display
 */

/** namespace */
function cdUtils(){};

cdUtils.updateUrlWithParam = function(oldUrl, name, value) {
  value = encodeURIComponent(value);
  name = encodeURIComponent(name);
  var nameValue = name + "=" + value;
  var nameIndex = 0;

  // Split the previous request into url and query params

  var oldUrlAndFragment = oldUrl.split('#');
  var oldPathAndArgs = oldUrlAndFragment[0].split('?');
  var oldUrlBase = oldPathAndArgs[0];
  var newArgs;

  if (oldPathAndArgs.length == 1) {
    newArgs = new Array();
  } else {
    // There were some arguments, preserve them

    newArgs = oldPathAndArgs[1].split('&');

    // Make note of where name was last time, if anywhere

    for (var i = 0; i < newArgs.length; i++) {
      if (newArgs[i].split('=')[0] == name) break;
    }
    // If we didn't find name, i is array length, so
    // we'll wind up appending new nameValue end of the array
    nameIndex = i;
  }

  // Set the value of name in the new query params

  newArgs[nameIndex] = nameValue;

  // Put the new request URL together

  var newUrl = oldUrlBase;

  for (var i = 0; i < newArgs.length; i++) {
    newUrl += ((i == 0) ? '?' : '&');
    newUrl += newArgs[i];
  }

  // add the fragment back, if there was one.

  if (oldUrlAndFragment[1]) {
    newUrl += "#" + oldUrlAndFragment[1];
  }
  return newUrl;
};

/**
 * Converts a relativeUrl into an absolute url, relative to the current
 * window.location object.
 */
cdUtils.makeUrlAbsolute = function(relativeUrl, opt_fakeLocation) {
  var location = opt_fakeLocation ? opt_fakeLocation : window.location;

  var start = location.protocol + "//" + location.host;
  var path = location.pathname;

  if (relativeUrl.indexOf("://") != -1) {
    return relativeUrl;
  }

  if (location.port) {
    start += ":" + location.port;
  }

  if (relativeUrl.indexOf("/") == 0) {
    return start + relativeUrl;
  }

  if (relativeUrl.indexOf("?") == 0) {
    return start + path + relativeUrl;
  }

  var relativePath = path.substring(0, path.lastIndexOf("/") + 1);

  return start + relativePath + relativeUrl;
};

// global
var CDU_previewWindow = null;

/**
 * Opens a new window to preview the given full slot ad.
 */
cdUtils.openPreviewWindow = function(url, width, height) {
  if (CDU_previewWindow) {
    // close the old preview window if any
    CDU_previewWindow.close();
  }
  CDU_previewWindow = window.open(url, "imageAd", "resizable = 1, scrollbars = 0," +
     "toolbar = 0, status = 0, menubar = 0, location = 0, width = " + width +
     ", height = " + height);
  CDU_previewWindow.focus();
  return false;
}
