// Copyright 2005 Google Inc.
// All rights reserved.
// Used in CampaignSummary.gxp

var renderStartTime = new Date();

function popup(url) {
  var h=Math.min(600,screen.height-50);
  window.open(url,'popup','width=500,height='+h+',toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1');
  return false;
}

/**
 * Rather than calling this directly, use PopUpLink.gxp or
 * QuestionMarkLink.gxp.
 *
 * Raise a help popup window in the standard way. 
 *
 * @param linkRef Can be a string, to be used as the URL
 * of the popped window, or can be an anchor element, whose
 * target and href values will be used.
 *
 * @param opt_target String to use as target (window name).
 * If null, linkRef.target will be used. If that is also null,
 * google_popup will be used.
 */
function helpPopUp(linkRef, opt_target) {
  if (!window.focus) return true;

  // get the link
  var href;
  if (typeof(linkRef) == 'string') href = linkRef;
  else href = linkRef.href;

  // Get the window name
  if (!opt_target) {
    opt_target = linkRef.target;
  }
  if (!opt_target) opt_target = 'google_popup';

  // pop the window, bring to top/focus
  var newWin;
  newWin = window.open(href, opt_target, 'width=690,height=500,toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1');
  newWin.focus();
  return false;
}

function focusField(name) {
  for(var i=0; i < document.forms.length; ++i) {
    var obj = document.forms[i].elements[name];
    if (obj && obj.focus) {obj.focus();}
  }
}

function selectField(name) {
  for(var i=0; i < document.forms.length; ++i) {
    var obj = document.forms[i].elements[name];
    if (obj && obj.focus){obj.focus();}
    if (obj && obj.select){obj.select();}
  }
}

function limitField(name, maxlimit) {
  for(var i=0; i < document.forms.length; ++i) {
    var obj = document.forms[i].elements[name];
    if (obj) {
      if (obj.value.length > maxlimit) {
        obj.value = obj.value.substring(0, maxlimit);
      }
    }
  }
}

function limitFieldById(id, maxlimit) {
  if (document.getElementById) {
    var obj = document.getElementById(id);
    if (obj && (obj.value.length > maxlimit)) {
      obj.value = obj.value.substring(0, maxlimit);
    }
  }
}

function getStyleObject(objectId) {
  // cross-browser function to get an object's style object given its id
  if(document.getElementById && document.getElementById(objectId)) {
    // W3C DOM
    return document.getElementById(objectId).style;
  } else if (document.all && document.all(objectId)) {
    // MSIE 4 DOM
    return document.all(objectId).style;
  } else if (document.layers && document.layers[objectId]) {
    // NN 4 DOM.. note: this won't find nested layers
    return document.layers[objectId];
  } else {
    return false;
  }
}

function getObject(objectId) {
  // cross-browser function to get an object given its id
  // If you need to change the style of an object or its display/visibility
  // use one of the other methods in this template
  // This function won't work for NN 4 DOM ==> Only use internally
  if(document.getElementById && document.getElementById(objectId)) {
    // W3C DOM
    return document.getElementById(objectId);
  } else if (document.all && document.all(objectId)) {
    // MSIE 4 DOM
    return document.all(objectId);
  } else {
    return false;
  }
}

/** 
 * Takes an object Id and a new visibility -- which accepts either
 * a boolean (true for 'visible', false for 'hidden') or one of these two Strings
 * return true if successful, false otherwise.
 *
 * @throws if newVisibilityParam is neither a boolean nor a string
 */
function changeObjectVisibility(objectId, newVisibilityParam) {

  if (isBoolean (newVisibilityParam)) {
    newVisibility = newVisibilityParam ? 'visible' : 'hidden';
  } else if (isString (newVisibilityParam)) {
    newVisibility = newVisibilityParam;
  } else {
    throw "Illegal newVisibilityParam " + newVisibilityParam;
  }
  // get a reference to the cross-browser style object and make sure the object exists
  var styleObject = getStyleObject(objectId);
  if(styleObject) {
    styleObject.visibility = newVisibility;
    return true;
  } else {
    // we couldn't find the object, so we can't change its visibility
    return false;
  }
}


function changeObjectDisplay(objectId, newDisplay) {
  // get a reference to the cross-browser style object and make sure the object exists
  var styleObject = getStyleObject(objectId);
  if(styleObject) {
    styleObject.display = newDisplay;
    return true;
  } else {
    // we couldn't find the object, so we can't change its visibility
    return false;
  }
}

// deprecated. please use toggleOnOff() instead, as '' is more compatible than
// 'block' across browers
function setOnOff(id1, id2) {
  changeObjectDisplay(id1, 'block');
  changeObjectDisplay(id2, 'none');
}

function toggleOnOff(id1, id2) {
  changeObjectDisplay(id1, '');
  changeObjectDisplay(id2, 'none');
}

function ga(o,e){var a,f,g,h,p,r,t; if (document.getElementById){a=o.id.substring(1); p = "";r = "";g = e.target;if (g) { t = g.id;f = g.parentNode;if (f) {p = f.id;h = f.parentNode;if (h) r = h.id;}} else{h = e.srcElement;f = h.parentNode;if (f) p = f.id;t = h.id;}if (t==a || p==a || r==a) return true;location.href=document.getElementById(a).href}}

// cross platform equiv. to document.getElementById
function gGetElementById(s) {
  var o = (document.getElementById ? document.getElementById(s) : document.all[s]);
  return o == null ? false : o;
}

// simple hide/display
function toggleVisibility(id) {
  var o = gGetElementById(id);
  if (o != null) {
    if (o.style.display == 'none')
      o.style.display = 'block';
    else
      o.style.display = 'none';
  }
}

function isGoodBrowser() {
  var ua=navigator.userAgent;
  var isGood=0;
  if ((ua.indexOf("MSIE 5")!=-1)
      || (ua.indexOf("MSIE 6")!=-1)
      || (ua.indexOf("Mozilla/5")!=-1) )
  {
    if (ua.indexOf("Opera")==-1){
      isGood = 1;
    }
  }
  return isGood;
}

function isBoolean(a) {
    return typeof a == 'boolean';
}

function isString(a) {
    return typeof a == 'string';
}

//------------------------------------------------------------------------
// Cookies
// TODO: Copied from 'google/javascript/common.js. This file should be
// integrated into the Ads build at some point.
//------------------------------------------------------------------------

//------------------------------------------------------------------------
// Functions needed by the cookie logic.
//------------------------------------------------------------------------

//------------------------------------------------------------------------
// Time
//------------------------------------------------------------------------
function Now() {
  return (new Date()).getTime();
}

// Check if a value is defined
function IsDefined(value) {
  return (typeof value) != 'undefined';
}

//------------------------------------------------------------------------
// Assertions
// DEPRECATED: Use assert.js
//------------------------------------------------------------------------
/**
 * DEPRECATED: Use assert.js
 */
function raise(msg) {
  if (typeof Error != 'undefined') {
    throw new Error(msg || 'Assertion Failed');
  } else {
    throw (msg);
  }
}

/**
 * DEPRECATED: Use assert.js
 *
 * Fail() is useful for marking logic paths that should
 * not be reached. For example, if you have a class that uses
 * ints for enums:
 *
 * MyClass.ENUM_FOO = 1;
 * MyClass.ENUM_BAR = 2;
 * MyClass.ENUM_BAZ = 3;
 *
 * And a switch statement elsewhere in your code that
 * has cases for each of these enums, then you can
 * "protect" your code as follows:
 *
 * switch(type) {
 *   case MyClass.ENUM_FOO: doFooThing(); break;
 *   case MyClass.ENUM_BAR: doBarThing(); break;
 *   case MyClass.ENUM_BAZ: doBazThing(); break;
 *   default:
 *     Fail("No enum in MyClass with value: " + type);
 * }
 *
 * This way, if someone introduces a new value for this enum
 * without noticing this switch statement, then the code will
 * fail if the logic allows it to reach the switch with the
 * new value, alerting the developer that he should add a
 * case to the switch to handle the new value he has introduced.
 *
 * @param {string} opt_msg to display for failure
 *                 DEFAULT: "Assertion failed"
 */
function Fail(opt_msg) {
  if (opt_msg === undefined) opt_msg = 'Assertion failed';
  if (IsDefined(DumpError)) DumpError(opt_msg + '\n');
  raise(opt_msg);
}

/**
 * DEPRECATED: Use assert.js
 *
 * Asserts that an expression is true (non-zero and non-null).
 *
 * Note that it is critical not to pass logic
 * with side-effects as the expression for AssertTrue
 * because if the assertions are removed by the
 * JSCompiler, then the expression will be removed
 * as well, in which case the side-effects will
 * be lost. So instead of this:
 *
 *  AssertTrue( criticalComputation() );
 *
 * Do this:
 *
 *  var result = criticalComputation();
 *  AssertTrue(result);
 *
 * @param {anything} expression to evaluate
 * @param {string}   opt_msg to display if the assertion fails
 *
 */
function AssertTrue(expression, opt_msg) {
  if (!expression) {
    if (opt_msg === undefined) opt_msg = 'Assertion failed';
    Fail(opt_msg);
  }
}

var ILLEGAL_COOKIE_CHARS_RE = /[\s;]/
/**
 * Sets a cookie.
 * The max_age can be -1 to set a session cookie. To expire cookies, use
 * ExpireCookie() instead.
 *
 * @param name The cookie name.
 * @param value The cookie value.
 * @param opt_max_age The max age in seconds (from now). Use -1 to set a
 *   session cookie. If not provided, the default is -1 (i.e. set a session
 *   cookie).
 * @param opt_path The path of the cookie, or null to not specify a path
 *   attribute (browser will use the full request path). If not provided, the
 *   default is '/' (i.e. path=/).
 * @param opt_domain The domain of the cookie, or null to not specify a domain
 *   attribute (brower will use the full request host name). If not provided,
 *   the default is null (i.e. let browser use full request host name).
 * @return Void.
 */
function SetCookie(name, value, opt_max_age, opt_path, opt_domain) {

  value = '' + value;
  AssertTrue((typeof name == 'string' &&
              typeof value == 'string' &&
              !name.match(ILLEGAL_COOKIE_CHARS_RE) &&
              !value.match(ILLEGAL_COOKIE_CHARS_RE)),
             'trying to set an invalid cookie');

  if (!IsDefined(opt_max_age)) opt_max_age = -1;
  if (!IsDefined(opt_path)) opt_path = '/';
  if (!IsDefined(opt_domain)) opt_domain = null;

  var domain_str = (opt_domain == null) ? '' : ';domain=' + opt_domain;
  var path_str = (opt_path == null) ? '' : ';path=' + opt_path;

  var expires_str;

  // Case 1: Set a session cookie.
  if (opt_max_age < 0) {
    expires_str = '';

  // Case 2: Expire the cookie.
  // Note: We don't tell people about this option in the function doc because
  // we prefer people to use ExpireCookie() to expire cookies.
  } else if (opt_max_age == 0) {
    // Note: Don't use Jan 1, 1970 for date because NS 4.76 will try to convert
    // it to local time, and if the local time is before Jan 1, 1970, then the
    // browser will ignore the Expires attribute altogether.
    var date = new Date(1970, 1 /*Feb*/, 1);  // Feb 1, 1970
    expires_str = ';expires=' + date.toUTCString();

  // Case 3: Set a persistent cookie.
  } else {
    var date = new Date( Now() + opt_max_age * 1000 );
    expires_str = ';expires=' + date.toUTCString();
  }

  document.cookie = name + '=' + value + domain_str + path_str + expires_str;
}

var EXPIRED_COOKIE_VALUE = 'EXPIRED';

/**
 * Expires a cookie.
 *
 * @param name The cookie name.
 * @param opt_path The path of the cookie, or null to expire a cookie set at
 *   the full request path. If not provided, the default is '/' (i.e. path=/).
 * @param opt_domain The domain of the cookie, or null to expire a cookie set
 *   at the full request host name. If not provided, the default is null (i.e.
 *   cookie at full request host name).
 * @return Void.
 */
function ExpireCookie(name, opt_path, opt_domain) {
  SetCookie(name, EXPIRED_COOKIE_VALUE, 0, opt_path, opt_domain);
}

/** Returns the value for the first cookie with the given name
 * @param name : string
 * @return a string or the empty string if no cookie found.
 */
function GetCookie(name) {
  var nameeq = name + "=";
  var cookie = String(document.cookie);
  for (var pos = -1; (pos = cookie.indexOf(nameeq, pos + 1)) >= 0;) {
    var i = pos;
    // walk back along string skipping whitespace and looking for a ; before
    // the name to make sure that we don't match cookies whose name contains
    // the given name as a suffix.
    while (--i >= 0) {
      var ch = cookie.charAt(i);
      if (ch == ';') {
        i = -1;  // indicate success
        break;
      } else if (' \t'.indexOf(ch) < 0) {
        break;
      }
    }
    if (-1 === i) {  // first cookie in the string or we found a ;
      var end = cookie.indexOf(';', pos);
      if (end < 0) { end = cookie.length; }
      return cookie.substring(pos + nameeq.length, end);
    }
  }
  return "";
}


