var defaultAdCode = "";
var defaultAdCodeLayers = "";
var allAdCodeLayers = "";
var nextTile = 1;
var debug = 0;
var test = 0;
var testcolor = "8080FF";
var tilesInUse = new Array();

function replaceStr(modStr, searchStr, repStr) {
    var searchIdx = modStr.lastIndexOf(searchStr);
    while (searchIdx > -1) {
       var substr1 = modStr.substring(0,searchIdx);
       var substr2 = modStr.substring(searchIdx + searchStr.length);
       modStr = substr1 + repStr + substr2;
       searchIdx = modStr.lastIndexOf(searchStr);
    }
    return modStr;
}
function setupAdCode(){
    // set debuging and test options
    if(window.location.search.indexOf("debugadcode") > -1) debug = 1;
    if(window.location.search.indexOf("testadcode") > -1) test = 1;


    // populate default ad code variables
    // this ad code contains strings which will be replaced by values passed into later functions
    defaultAdCode += "<NOLAYER>\n";
    defaultAdCode += "<IFRAME SRC=\"http://ad.doubleclick.net/adi/sitename/pagename;kw=keywords;pos=position;sz=adwidthxadheight;tile=tilenumber;ord=randomnumber?\" width=\"adwidth\" height=\"adheight\" frameborder=\"no\" border=\"0\" MARGINWIDTH=\"0\" MARGINHEIGHT=\"0\" SCROLLING=\"no\">\n";
    defaultAdCode += "<A HREF=\"http://ad.doubleclick.net/jump/sitename/pagename;kw=keywords;pos=position;sz=adwidthxadheight;tile=tilenumber;ord=randomnumber?\"><IMG SRC=\"http://ad.doubleclick.net/ad/sitename/pagename;kw=keywords;pos=position;sz=adwidthxadheight;tile=tilenumber;ord=randomnumber?\" border=0 width=\"adwidth\" height=\"adheight\"></A>\n";
    defaultAdCode += "</IFRAME>\n";
    defaultAdCode += "</NOLAYER>\n";
    defaultAdCode += "<ILAYER id=\"layerposition\" visibility=\"hidden\" width=\"adwidth\" height=\"adheight\" border=\"0\" bgcolor=\"testcolor\" clip=\"adwidth,adheight\"></ILAYER>";
    
    defaultAdCodeLayers += "<LAYER SRC=\"http://ad.doubleclick.net/adl/sitename/pagename;kw=keywords;pos=position;sz=adwidthxadheight;tile=tilenumber;ord=randomnumber?\" width=adwidth height=adheight visibility=\"hidden\" onLoad=\"moveToAbsolute(layerposition.pageX,layerposition.pageY);clip.height=adheight;clip.width=adwidth;visibility='show';\"></LAYER>\n";

    //  check for the test parameter and enable color changes for testing adcode position
    if (test > 0) { 
      if (navigator.userAgent.indexOf("MSIE") > -1) {
        // change bg color so white ad code blocks are visible
        document.bgColor = testcolor;
      } else {
        // change color of ad code blocks and make visible so that they can be seen against any color background
        defaultAdCode = replaceStr(defaultAdCode, "testcolor", "#" + testcolor);
        defaultAdCode = replaceStr(defaultAdCode, "visibility=\"hidden\"", "");
      }
    } else {
      // if no test mode then remove the testcolor parameter from the adcode so it doesn't get confused.
      defaultAdCode = replaceStr(defaultAdCode, "testcolor", "");
    }

    // set random number here so that it is consistent throughout all the ad code snippets on the page.
    var randomNumber = Math.random() + "";
    defaultAdCode = replaceStr(defaultAdCode, "randomnumber", randomNumber);
    defaultAdCodeLayers = replaceStr(defaultAdCodeLayers, "randomnumber", randomNumber);

    // for each parm passed into this funct, replace the string matching arg[0] with arg[1]
    args = setupAdCode.arguments
    for(i=0; i<args.length; i+=1) if(args[i].indexOf("=") != -1) {
      // check for invalid setup code
      if(args[i].indexOf('<!--') > -1) {
        defaultAdCode = "Error In Ad Code Setup Arguments: Found Comment Tags. Illegal Format.";
        return;
      }
      arg = args[i].split("=");
	  if(arg[0] == "debug"){
	    debug = 1;
	    continue;
	  }
      // creates a generic regular expression that will find all ocurrences of arg[0] then replace with arg[1]
      defaultAdCode = replaceStr(defaultAdCode, arg[0], arg[1]);
      defaultAdCodeLayers = replaceStr(defaultAdCodeLayers, arg[0], arg[1]);
    }
  var msg = "---"
  for(i=0; i<tilesInUse.length; i+=1){
    msg += i+"="+tilesInUse[i]+";";
  }
}
function getAdCode(){
  // getAdCode(["name=value"][,"name2=value2"]...)

  // for each ad code block, set parameters specific to that block
  var args = getAdCode.arguments;
  var adCode = new String(defaultAdCode);
  var adCodeLayers = new String(defaultAdCodeLayers);
  var tileNumber = 0;
  
  for(i=0; i<args.length; i += 1) {
    if(args[i].indexOf('<!--') > -1) {
      return "Error In Ad Code Arguments: Found Comment Tags. Illegal Format.";
    }
    if(args[i].indexOf("=") != -1) {
      arg = args[i].split("=");
        // manual tile nums have to be validated unique
	if(arg[0] == "tilenumber") {
	  tileNumber = parseInt(arg[1]);
	  if(tilesInUse[tileNumber] != true) {
  	    tilesInUse[tileNumber] = true;
	  } else {
	    adCode = "ERROR: Tile Number "+tileNumber+" is already in use.";
	    adCodeLayers = adCode;
            i = args.length;
	  }
          if(debug > 0) adCode += "\n<!-- Manual Tile Placement ("+tileNumber+")-->";
	}
      adCode = replaceStr(adCode, arg[0], arg[1]);
      adCodeLayers = replaceStr(adCodeLayers, arg[0], arg[1]);
    }
  }

  // tile values are intended to be unique to each block on the page
  if(tileNumber < 1) {
    while (tilesInUse[nextTile] == true) {
      nextTile += 1;
    }
    tileNumber = nextTile;
    tilesInUse[tileNumber] = true;
    nextTile += 1;
    if(debug > 0 ) adCode += "\n<!-- Seqential Tile Placement ("+tileNumber+")-->";
  }
  adCode = replaceStr(adCode, "tilenumber", tileNumber);
  adCodeLayers = replaceStr(adCodeLayers, "tilenumber", tileNumber);
  
  // ad code layers are not returned each time a new block is created. they are collected and returned at the end of the document
  allAdCodeLayers += adCodeLayers;
  if(debug > 0 ) return "<FORM><TEXTAREA COLS=40 ROWS=7 WRAP=OFF>" + adCode + "</TEXTAREA></FORM>";
  else return adCode;
}
function getAdCodeLayers(){
  // no values accepted in the func.
  // returns the layer ad code for netscape
  var msg = "";
  if(debug > 0 ) {
    for(i=1; i<tilesInUse.length; i+=1) {
      if(tilesInUse[i] == true && msg.length > 0) msg += ", ";
      if(tilesInUse[i] == true) msg += i;
    }
    if(msg.length > 0) msg = "<!-- tiles used "+msg+" -->\n";
  }
  if(debug > 0) return "<FORM><TEXTAREA COLS=65 ROWS=7 WRAP=OFF>"+msg+allAdCodeLayers+"</TEXTAREA></FORM>";
  else return allAdCodeLayers;
}
