// Global Variables
var cookieVersionID = "XooXooXWantListV2x7";  // GLOBAL VAR current name of the versioned XooXooXWantList Cookie

// the following variables may be passed in via a QueryString or JavaScript Global Variables set within a local script on the page 
var publisherID; // default will be set  = "xooxooxunknown-20";
var listURL;     // default will be set  =  null (no alternate shopping list specified)
var adsize;      // default will be set  = "768x90"  Leaderboard Banner 
var retailerName ="Amazon"; // default will be set  = "Amazon"
var retailerIndex= 0; // default will be set  = 0
var retailerValue = "amazon"; // default will be set  = "amazon"
var category;	 // default will be set  = "Everything"
var categoryIndex; // default will be set  = 0
var categoryValue = "universal"; // default will be set = 'universal";
var keywords;    // default will be set  = ""

var xmlDoc;
var betweenAdsMessaging = "createYourList";
var betweenAdsMessagingString;
var amazon_ad_tag = publisherID; 
	amazon_ad_width = "728"; 
	amazon_ad_height = "90"; 
var iFrame;
var dataFrame;
var dataFrameInnerHTML;
var adWidth;
var adHeight;

var numberOfAdsShown = 0;
var activeWantListItems = new Array;
var userCookieWantList;
var userWantListInDOM;

var categoryNamesToValues = new Array;
var categoryValuesToNames = new Array;

var selectedRetailerName ="Amazon";
var selectedCategoryName = "Everything";
var selectedItem;
var theTextBuffer ="";
var userHasListWithActiveItems = false;
var timer;
var ad_timer;
var msg_timer;
var ad_timer_is_on=0;
var msg_timer_is_on=0;
var waitAfterAdTime = 30 * 1000; // time in milliseconds after an Ad is shown before the next Msg is shown
var waitAfterMsgTime = 30 * 1000; // time in milliseconds after a Msg is shown before the next Ad is shown

var A_Message = 'Click to <i>Personalize<' +'/i> these offers';
var B_Message = 'Click to turn ads into <i>Personalized<' +'/i> offers';
var percentageOfB_MessagesToShow = 50;  // percentageOfA_messages = 100% - percentageOfB_messages
var theSelectedAorBMessage = selectAorBmessages();

	
var adSizes = new Array("160x600", "120x600", "300x250", "180x150", "120x150", "768x90", "468x60" );
	
var AdDimensions = new Array;
	AdDimensions["160x600"] = new Object; 
	AdDimensions["160x600"].width = 160; 
	AdDimensions["160x600"].height = 600; 
	AdDimensions["160x600"].logoAreaWidth = 160; 
	AdDimensions["160x600"].logoAreaHeight = 80; 
	AdDimensions["160x600"].logoTextHeight = 14; 
	AdDimensions["160x600"].layout = "portrait";
	
	AdDimensions["120x600"] = new Object; 
	AdDimensions["120x600"].width = 120; 
	AdDimensions["120x600"].height = 600; 
	AdDimensions["120x600"].logoAreaWidth = 120; 
	AdDimensions["120x600"].logoAreaHeight = 60; 
	AdDimensions["120x600"].logoTextHeight = 12; 
	AdDimensions["120x600"].layout = "portrait";
	
	AdDimensions["300x250"] = new Object; 
	AdDimensions["300x250"].width = 300; 
	AdDimensions["300x250"].height = 250; 
	AdDimensions["300x250"].logoAreaWidth = 300; 
	AdDimensions["300x250"].logoAreaHeight = 60; 
	AdDimensions["300x250"].logoTextHeight = 17; 
	AdDimensions["300x250"].layout = "portrait";
	
	AdDimensions["180x150"] = new Object; 
	AdDimensions["180x150"].width = 180; 
	AdDimensions["180x150"].height = 150; 
	AdDimensions["180x150"].logoAreaWidth = 180; 
	AdDimensions["180x150"].logoAreaHeight = 40; 
	AdDimensions["180x150"].logoTextHeight = 10; 
	AdDimensions["180x150"].layout = "portrait";
	
	AdDimensions["120x150"] = new Object; 
	AdDimensions["120x150"].width = 120; 
	AdDimensions["120x150"].height = 150; 
	AdDimensions["120x150"].logoAreaWidth = 120; 
	AdDimensions["120x150"].logoAreaHeight = 40; 
	AdDimensions["120x150"].logoTextHeight = 8; 
	AdDimensions["120x150"].layout = "portrait";
	
	AdDimensions["768x90"] = new Object; 
	AdDimensions["768x90"].width = 768; 
	AdDimensions["768x90"].height = 90; 
	AdDimensions["768x90"].logoAreaWidth = 162; 
	AdDimensions["768x90"].logoAreaHeight = 90; 
	AdDimensions["768x90"].logoTextHeight = 18; 
	AdDimensions["768x90"].layout = "landscape";
	
	AdDimensions["468x60"] = new Object; 
	AdDimensions["468x60"].width = 468; 
	AdDimensions["468x60"].height = 60; 
	AdDimensions["468x60"].logoAreaWidth = 100; 
	AdDimensions["468x60"].logoAreaHeight = 60; 
	AdDimensions["468x60"].logoTextHeight = 11; 
	AdDimensions["468x60"].layout = "landscape";
		 
	// activeWantListItems is an array of Want List Items from either the User's List or Publisher's list.
	// Each Want List Item has the following attributes:
	// retailer (string from enumerated list of retailer. Currently only "Amazon" or "Any" are valid)
	// category (string from enumerated list of retailer dependent category identifiers)
	// keywords (search string passed to retailer's ad retrieval function)


// mainline*******************************************************
pageload();


// String Function prototypes ************************************

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

// A/B Messaging **************************************************

function selectAorBmessages() {
	if ( Math.floor(Math.random()*100) <= percentageOfB_MessagesToShow) return B_Message;
	else return A_Message;
}	

// EVENT LOOP CALLBACK FUNCTIONS **********************************
function showMenu() {

		var theMenu = document.getElementById("theMenu");
		var theCategory = document.getElementById("categoryMenu");
		
		for (var i=0; i < theCategory.options.length; i++) {
			if (theCategory.options[i].text = category) {
				theCategory.options[i].selected = true; 
				
				break;
			}
			theCategory.options[0].selected = true;  // we only get here if there is never a match 
		}
		
		var theKeywords = document.getElementById("keywordsInputBox");
		var theCommandMenu = document.getElementById("commandMenu");
		
		if ((userHasListWithActiveItems) && ((keywords != "") || (keywords != null))) {
			theKeywords.value = keywords;  // from the global variable
			theCommandMenu.options[1].disabled = false;
			theCommandMenu.options[1].selected = true;  // Replace this item
		} else {
			theKeywords.value = "list items you want";
			theCommandMenu.options[0].selected = true;  // Add item to list
			theCommandMenu.options[1].disabled = true;
		}
		
		theMenu.style.visibility="visible";
		theMenu.style.display="block";
}

function waitThenHideMenu() {
	// do nothing for now.   hideMenu whenever we change the Ad.
	//hideMenu();
	//timer =setTimeout("hideMenu();",5000);
}

function hideMenu() {
		var theMenu = document.getElementById("theMenu");
		theMenu.style.visibility="hidden";
		theMenu.style.display="none";
}

function showEditor() {
		window.open('WantListEditor.php', 'WantListEditor');
}

function showHelp() {
		window.open('miniControlHelp.html', 'miniControl');
}


function changedCategory(theCategory) { 
	categoryIndex = theCategory.selectedIndex;
	category = theCategory.options[categoryIndex].text;
	categoryValue = theCategory.options[categoryIndex].value;
	clearTimeout(ad_timer);
	showTheAd();
 }

function changedKeywords(theKeywords) { 
	keywords = theKeywords.value; 
	clearTimeout(ad_timer);
	showTheAd();
}

function changingKeywords(theKeywords) { 
	keywords = theKeywords.value; 
}

function SaveWantListToCookie(theWantListInDOM) {
	var DateString = Date().toString();
	theWantListInDOM.attributes.lastwritten.nodeValue=DateString;
	theWantListInDOM.attributes.version.nodeValue='Beta2.0';
	theWantListInDOM.attributes.xooxooxversion.nodeValue='Beta2.0';
	var theWantListAsAnXMLString = (new XMLSerializer()).serializeToString(theWantListInDOM);
	var expiresDate = new Date();
	expiresDate.setDate(expiresDate.getDate() + 365);
	// global cookieVersionID;
	document.cookie = cookieVersionID + "=" 
					+ escape(theWantListAsAnXMLString) 
					+ ";expires=" 
					+ expiresDate.toGMTString();
}

function addItemToList() { 
	var theWantListInXML = userWantListInDOM.childNodes[0];
	var currentNumberOfRows = theWantListInXML.childElementCount;
	var newRowNumber =  currentNumberOfRows + 1;
	
	// create an XML item with the values in the Add Row, and append it to the WantListControls;
	// then add the new item to the end of the XML area

	var theNewItem = document.createElement('ITEM');
	var DateString = Date().toString();
	var LastWrittenAttribute = theNewItem.setAttribute('LastWritten',DateString);
	var theNewRowNumber = document.createElement('ROWNUMBER'); 
	theNewRowNumber.textContent = newRowNumber;
	theNewItem.appendChild(theNewRowNumber);
	var theNewActiveCheckBox = document.createElement('ENABLED');
	theNewActiveCheckBox.textContent = "true";
	theNewItem.appendChild(theNewActiveCheckBox);
	var theNewRetailer = document.createElement('RETAILER'); 
	theNewRetailer.textContent = retailerValue.trim(); // from global
	theNewRetailer.setAttribute('retailerValue', retailerName.trim());  // from global
	theNewItem.appendChild(theNewRetailer);
	var theNewCategory = document.createElement('CATEGORY'); 
	categoryValue = categoryNamesToValues[category];
	theNewCategory.textContent = category.trim(); // from global
	theNewCategory.setAttribute('categoryValue', categoryValue.trim()); // from global
	theNewItem.appendChild(theNewCategory);
	var theNewKeywords = document.createElement('KEYWORDS'); 
	theNewKeywords.textContent = keywords.trim(); // from global
	theNewItem.appendChild(theNewKeywords);
	var theNewDeletedCheckBox = document.createElement('DELETED'); 
	theNewDeletedCheckBox.textContent = "false";
	theNewItem.appendChild(theNewDeletedCheckBox);
	theWantListInXML.appendChild(theNewItem);
	SaveWantListToCookie(theWantListInXML);	
	showTheAd();
	clearTimeout(ad_timer);
	ad_timer=setTimeout("showXooXooXMsg()",waitAfterAdTime);
	//reloadPage();  // reload the page with the new list  
}

function replaceItemInList() {
	var theWantListInXML = userWantListInDOM.childNodes[0];

	
	// create an XML item with the values in the Add Row, and append it to the WantListControls;
	// then add the new item to the end of the XML area

	var theNewItem = theWantListInXML.getElementsByTagName('ITEM')[selectedItem];
	var DateString = Date().toString();
	var LastWrittenAttribute = theNewItem.setAttribute('LastWritten',DateString);
	
	var theNewCategory = theNewItem.getElementsByTagName('CATEGORY')[0]; 
	theNewCategory.textContent =  category.trim(); // from global
	theNewCategory.setAttribute('categoryValue',categoryValue.trim()); // from global
	
	var theNewKeywords = theNewItem.getElementsByTagName('KEYWORDS')[0]; 
	theNewKeywords.textContent = keywords; // from global
	
	SaveWantListToCookie(theWantListInXML);	
	showTheAd();
	clearTimeout(ad_timer);
	ad_timer=setTimeout("showXooXooXMsg()",waitAfterAdTime);
	//reloadPage();  // reload the page with the new list 
}

//Helper Functions *************************************************************

function getWindowAttributes(attributeName)	{
	var value = null;
	eval("value = window." + attributeName + ";");
	return value;
}
	
function getQueryVariable(variableName) { 
	// variableName is variable that we are searching for in query string
	// returns value of variable name variableName from query string
	
	var query = window.location.search.substring(1);
	var querypair = query.split("&");
	for (var i=0;i<querypair.length;i++) {
		pair = querypair[i].split("=");
		if (pair[0] == variableName) {
			return pair[1]; // returns value of variable name variableName from query string
		}
	}
	
	// Apparently there is nothing in the query string with that variableName.
	// Let's see if the user set a global variable with that name.  If so, we will return that.  
	
	if (getWindowAttributes(variableName) != undefined) {
		return getWindowAttributes(variableName) ;
	}
	else return null;
}


function resize()
   {
    var currentSize = getViewportSize();
    if (currentSize[0] != g_prevSize[0] || currentSize[1] != g_prevSize[1])
    {
     g_prevSize = currentSize;
     debug.value = 'the window was resized: ' +
                   document.documentElement.clientWidth + ', ' +
                   document.documentElement.clientHeight;
    }
   }

   function init()
   {
    window.debug = document.getElementById('debug');
    window.g_prevSize = getViewportSize();
    setInterval(resize, 100);
   }

   function grow()
   {
    var p = document.createElement('p');
    p.appendChild(document.createTextNode('This is a paragraph'));
    document.body.appendChild(p);
   }

function getViewportSize()
{
    var size = [0, 0];
    if (typeof window.innerWidth != 'undefined')
    {
     size = [ window.innerWidth, window.innerHeight ];
    }
    else if (typeof document.documentElement != 'undefined' &&
             typeof document.documentElement.clientWidth != 'undefined' &&
             document.documentElement.clientWidth != 0)
    {
       size = [ document.documentElement.clientWidth, document.documentElement.clientHeight ];
    }
    else
    {
       size = [ document.getElementsByTagName('body')[0].clientWidth,
              document.getElementsByTagName('body')[0].clientHeight ];
    }

    return size;
}
   

function getViewportSize() { 
	// returns viewport object which has height and width attributes
	var viewport = new Object;
	viewport.width = 0;
	viewport.height = 0;
 
 	// the more standards compliant browsers (mozilla/netscape/opera/IE7) 
	// use window.innerWidth and 	window.innerHeight
 
 	if (typeof window.innerWidth != 'undefined')
 	{
    	viewport.width = window.innerWidth,
    	viewport.height = window.innerHeight
 	}
 
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

 	else if (typeof document.documentElement != 'undefined'
     	&& typeof document.documentElement.clientWidth !=
     	'undefined' && document.documentElement.clientWidth != 0)
 	{
       	viewport.width = document.documentElement.clientWidth,
       	viewport.height = document.documentElement.clientHeight
	 }
 
 	// older versions of IE
 
 	else
 	{
       viewport.width = document.getElementsByTagName('body')[0].clientWidth,
       viewport.height = document.getElementsByTagName('body')[0].clientHeight
	 }
	
	return viewport; // returns viewport object which has height and width attributes
}

function IsInteger(sText){
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;   
}


function calculateBestFit(adsize) { 
	//returns largest adSize that will fit in viewport as string in "form WWWxHHH"
	// or returns "0x0" if viewport is smaller than the smallest available ad size.
	
	// We only check adsize if a value was passed in by Query String or Global Variable
	// So let's start by trying to figure out what dimensions they passed.
	// We will place the largest ad possible within the dimensions passed.
	
	if (adsize.indexOf('x') != -1) {  // valid adsize strings should be in form  WWWxHHH or WWWxHH
		var adDimensions = adsize.split("x")
		var adWidth= IsInteger(adDimensions[0]);
		var adHeight = IsInteger(adDimensions[1]);

		if (adWidth < 120)  { } // Too narrow for any ad
		else if (adWidth < 160 ) {
			if (adHeight < 150) { }// too short for SMALL RECTANGLE
			else if (adHeight < 600) {return "120x150";}// only SMALL RECTANGLE can fit
			else {return "120x600";} //SKYSCRAPER could also fit
		} else if (adWidth < 180) {
			if (adHeight < 150) { } //too short for SMALL RECTANGLE
			else if (adHeight < 600) {return "120x150";} // SMALL RECTANGLE can fit
			else { return "160x600";} //WIDE SKYSCRAPER can fit
		} else if (viewport.width < 300) {
			if (adHeight < 150) { }  //too short for SMALL or MEDIUM RECTANGLE
			else if (adHeight < 600) {return "180x150";} // MEDIUM RECTANGLE can fit
			else {return "160x600";} //WIDE SKYSCRAPER can fit
		} else if (adWidth < 468) {
			if (adHeight < 150) { }  //too short for small or MEDIUM RECTANGLE
			else if (adHeight < 250) {return "180x150";} // MEDIUM RECTANGLE can fit 
			else if (adHeight < 600) {return "300x250";} // LARGE RECTANGLE can fit
			else {return "160x600";} // WIDE SKYSCRAPER can fit
		} else if (adWidth < 728) {
			if (viewport.height < 60) { }  //too short for banner
			else if (adHeight < 150) {return "468x60";} // BANNER can fit
			else if (adHeight < 250) {return "180x150";} // MEDIUM RECTANGLE can fit 
			else if (adHeight < 600) {return "300x250";} // LARGE RECTANGLE can fit
			else  {return"160x600";} // WIDE SKYSCRAPER can fit	
		} else if (adHeight < 60) { }// too short for banner
			else if (adHeight < 90) {return "468x60";} // BANNER can fit	
			else if (adHeight < 90) {return "728x60";} // LEADERBOARD can fit	
		else return "0x0";
	} 
	
	// If we got here, either we have a mangled adsize with no "x" in it,
	// so now we will try to see what fits in the viewport we have been given
	var viewport = getViewportSize();
	var adsize = "0x0";
	if (viewport.width < 120)  { } // Too narrow for any ad
	else if (viewport.width < 160 ) {
		if (viewport.height < 150) { }// too short for SMALL RECTANGLE
		else if (viewport.height < 600) {adsize = "120x150";}// only SMALL RECTANGLE can fit
		else {adsize = "120x600";} //SKYSCRAPER could also fit
	} else if (viewport.width < 180) {
		if (viewport.height < 150) {} //too short for SMALL RECTANGLE
		else if (viewport.height < 600) {adsize="120x150";} // SMALL RECTANGLE can fit
		else { adsize= "160x600";} //WIDE SKYSCRAPER can fit
	} else if (viewport.width < 300) {
		if (viewport.height < 150) {}  //too short for SMALL or MEDIUM RECTANGLE
		else if (viewport.height < 600) {adsize = "180x150";} // MEDIUM RECTANGLE can fit
		else {adsize = "160x600";} //WIDE SKYSCRAPER can fit
	} else if (viewport.width < 468) {
		if (viewport.height < 150) {}  //too short for small or MEDIUM RECTANGLE
		else if (viewport.height < 250) {adsize = "180x150";} // MEDIUM RECTANGLE can fit 
		else if (viewport.height < 600) {adsize = "300x250";} // LARGE RECTANGLE can fit
		else {adsize = "160x600";} // WIDE SKYSCRAPER can fit
	} else if (viewport.width < 728) {
		if (viewport.height < 60) {}  //too short for banner
		else if (viewport.height < 150) {adsize = "468x60";} // BANNER can fit
		else if (viewport.height < 250) {adsize = "180x150";} // MEDIUM RECTANGLE can fit 
		else if (viewport.height < 600) {adsize = "300x250";} // LARGE RECTANGLE can fit
		else  {adsize = "160x600";} // WIDE SKYSCRAPER can fit	
	} else if (viewport.height < 60) { // too short for banner
	} else if (viewport.height < 90) {adsize = "468x60"; // BANNER can fit	
	} else if (viewport.height < 90) {adsize = "728x60"; // LEADERBOARD can fit	
	}
	return adsize;//returns largest adSize that will fit in viewport as string in "form WWWxHHH"
	// or returns "0x0" if viewport is smaller than the smallest available ad size.
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function LoadXMLStringIntoWantListDOM(text){
	
	if (window.DOMParser){
  		parser=new DOMParser();
  		xmlDoc=parser.parseFromString(text,"text/xml");
  	}
	else // Internet Explorer
  	{
 		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  		xmlDoc.async="false";
  		xmlDoc.loadXML(text);
 	 } 
	 return xmlDoc;
}



function convertWantListDOMtoActiveArray( wantListDOM, alertUserToWarnings ){
	// takes a WantList in DOM (originally in XML) and returns an Array of wantListItem objects
	// alertUserToErrors is a boolean that controls whether  or not to display warnings to Users
	
	var wantList = new Array;
	
	var DOMItems =  wantListDOM.getElementsByTagName("ITEM");
	if (DOMItems.length == 0) { // no items in the list
		if (alertUserToWarnings == true) alert(
			"You have ZERO items in your XooXooX Personal Want List right now.\n\n" 
			+ "To make sure you see only the personalized offers you want,"
			+ "you must have at least ONE ACTIVE ITEM in your want list.");
	} else {
		var activeItems = 0;
		for (var item = 0; item < DOMItems.length; item++) {
			var enabledValue =  DOMItems[item].getElementsByTagName("ENABLED")[0].textContent;
			var deletedValue =  DOMItems[item].getElementsByTagName("DELETED")[0].textContent;
			if ( (enabledValue == "true") && (deletedValue == "false") ){
				wantList[activeItems] = new Array;
				wantList[activeItems].retailerName = DOMItems[item].getElementsByTagName("RETAILER")[0].textContent.trim();
				wantList[activeItems].retailerValue = DOMItems[item].getElementsByTagName("RETAILER")[0].attributes.retailervalue.nodeValue.trim();
				wantList[activeItems].categoryName = DOMItems[item].getElementsByTagName("CATEGORY")[0].textContent.trim();
				wantList[activeItems].categoryValue = DOMItems[item].getElementsByTagName("CATEGORY")[0].attributes.categoryvalue.nodeValue.trim();
				wantList[activeItems].keywords = DOMItems[item].getElementsByTagName("KEYWORDS")[0].textContent.trim();
				activeItems++;
				
			}
		}
		if ( activeItems == 0 ) { // If no enabled items alert user
			if (alertUserToWarnings == true) alert(
				"You have zero ACTIVE items in your XooXooX Personal Want List right now.\n\n" 
				+ "To make sure you see only the personalized offers you want,"
				+ "you must have at least one ACTIVE item in your want list.");
		}
	}
	return wantList;
}




// MAIN LINE FUNCTION ***********************************************************************************

function pageload() {

	createControlsFrame() ;
	adsize = getQueryVariable("adsize");
	
	if (adsize == null) adsize = "728x90" // If called with no size specified, default value is a Leaderboard
	else adsize = adsize.toLowerCase();
	
	var src;
	switch (adsize) {
		case "728x90": // Leaderboard
			initialAd = "./initads/" + adsize + ".html";
			break;
		case "468x60": // Banner
			initialAd = "./initads/" + adsize  + ".html";
			break;
		case "120x600": // Skyscraper
			initialAd = "./initads/" + adsize  + ".html";
			break;
		case "160x600": // Wide Skyscraper
			initialAd = "./initads/" + adsize  + ".html";
			break;
		case "300x250": // Large Rectangle
			initialAd = "./initads/" + adsize  + ".html";
			break;
		case "180x150": // Medium Rectangle
			initialAd = "./initads/" + adsize  + ".html";
			break;
		case "120x150": // Small Rectangle
			initialAd = "./initads/" + adsize  + ".html";
			break;
		
		default: // ONLY HAPPENS IF THERE IS A SPECIFIED, BUT UNSUPPORTED SIZE PASSED IN
			var alertUserToWarnings = false;
			if (alertUserToWarnings == true) alert("XooXooXAd passed invalid value for variable 'adsize' in URL query string or global variable.\n" 
				+ "Received &adsize='" + adsize + "'.\n"
				+ "Valid adSize values are:\n"
				+ "'728x90' (Leaderboard),\n"
				+ "'468x60' (Banner),\n"
				+ "'120x600' (Skyscraper),\n"
				+ "'160x600' (Wide Skyscraper),\n"
				+ "'300x250' (Large Rectangle),\n"
				+ "'180x150' (Medium Rectangle),\n"
				+ "'120x150' (Small Rectangle).");
			adsize = calculateBestFit(adsize);
			if (adsize = "0x0") adsize = "728x90";
			initialAd = "./initads/" + adsize  + ".html";
		break;	
	}
	if (adsize != "0x0") {
				var adDimensions = adsize.split("x")
				adWidth= adDimensions[0];
				adHeight = adDimensions[1];
	} else return;
	src =  "<iframe id='adSpace' scrolling='no' width='" + adWidth + "px' height= '" + adHeight + "px' src='" + initialAd + "' />";
	
	iFrame = document.getElementById("adIFrame"); iFrame.innerHTML =  src;
	if (showData == "true") {
		dataFrame = document.getElementById("dataFrame"); 
		dataFrame.innerHTML = "<br />" + adsize + " " + publisherID;
	}
	
	reloadPage();
}

//******************** END OF MAIN LINE PROGRAM **************************************************


//******************* PAGE LAYOUT AND DISPLAY FUNCTIONS ******************************************

function reloadPage() {
	var unescapedWantList = unescape(readCookie(cookieVersionID));
	var trimmedWantList = unescapedWantList.replace(/^\s+|\s+$/g,"");
	userCookieWantList = trimmedWantList.replace(/\++/g,' ');
	//userCookieWantList = unescape(readCookie(cookieVersionID)).trim().replace(/\++/g,' '); //  global var
	publisherID = getQueryVariable("publisherID"); // this is a global because other callbacks will need it too.
	var alertUserToWarnings = false;
	if  ( publisherID == null ) publisherID="xooxooxunknown-20"; // If publisher didn't include their ID, we won't 
													   // know who to pay. But we can tag these with the
													   // missing tag and then try to guess based on timestamp
													   // in our web log showing which webpage called for the
													   // ad with the missing publisherID tag.
	
	betweenAdsMessaging = "createAList";
	if ( userCookieWantList != null ) { // Cookie exists
		userWantListInDOM = LoadXMLStringIntoWantListDOM(userCookieWantList);  // parse UserCookieWantList in XML into DOM
		
		// convert active items from userWantListInDOM to a JavaScriptArray of Objects
		var alertUserToWarnings = false; // the user can't change publisher's list anyway so ignore warnings
		activeWantListItems = convertWantListDOMtoActiveArray(userWantListInDOM, alertUserToWarnings);
		
		// Set Global variable betweenAdsMessaging to control between Ad Messaging
		if (activeWantListItems.length > 0) {// User has list with at least one active item
			betweenAdsMessaging = "addToYourList"; 
			userHasListWithActiveItems = true;  // set global variable
		} else {
			betweenAdsMessaging = "noActiveItemsInList"; // User has list, but no active items	
			userHasListWithActiveItems = false; // set global variable
		}
	} 
	
	if (betweenAdsMessaging != "addToYourList") { 
		// Either user has no list at all, or no active items, so we'll see if the publisher has provided 
		// a list in an XML file.
		userHasListWithActiveItems = false; // set global variable
		var listURL =getQueryVariable("listURL"); 
		if ( listURL != null) { // Is there is a URL for a publisher defined Want List? If so, we'll try it!
			publisherWantListInDOM = XML.load(listURL);
			// convert active items from publisherWantListInDOM to a JavaScriptArray of Objects
			var alertUserToWarnings = false; // the user can't change publisher's list anyway so ignore warnings
			activeWantListItems = convertWantListDOMtoArray(UserWantListInDOM, alertUserToWarnings);
		
			// Set Global variable betweenAdsMessaging to control between Ad Messaging
			if (activeWantListItems.length > 0)  {// Publisher has list with at least one active item
				// If we are only using the publisher's list because there are no active items in user's list
				// we want to keep messaging the user to add active items to their list.
				// But if the user had no list, we want to message them to create one.
				if (betweenAdsMessaging != "noActiveItemsInList") betweenAdsMessaging = "createAList";
			} else { // publisher doesn't have a list or it has no active items either.
				if (betweenAdsMessaging != "noActiveItemsInList") betweenAdsMessaging = "createAList";	
			}	
		}
	}
	betweenAdsMessagingString = "./" + betweenAdsMessaging + "MsgAds/" + adsize + ".html";
	
	category = getQueryVariable("category"); 

	if ((category == null) || (category == '')) {category = "Everything"; categoryValue="universal";} // use default category = "Everything"
	categoryValue = categoryNamesToValues[category];
	if ((categoryValue == null) ||  (categoryValue == '')) {category = "Everything"; categoryValue="universal";}
	keywords = getQueryVariable("keywords"); 
	if (keywords == null)  keywords = "";  // use default keyword =""
	showTheAd();
	clearTimeout(ad_timer);
	ad_timer=setTimeout("showXooXooXMsg()",waitAfterAdTime);
	showAd();
}

function showAd() {
	
	// By now we either have an active list from the user or from the publisher,
	// or we have no list to guide us at all.  In that case we will let Amazon choose the ad 
	// by using their OMIKASE service.
	if (( numberOfAdsShown == 0) && (categoryValue != null) && (keywords != null)) {
		// if user passed in a preferred keyword and category, show that for the first ad.
		showTheAd();

	} else if (activeWantListItems.length > 0)  { // we have a list that we can use to select ads.
		//  choose one of the active items at random		
		//	compose the AmazonAdRequestString from the category and keywords in the selected item	
		selectedItem = Math.floor(Math.random()*activeWantListItems.length);
		category = activeWantListItems[selectedItem].categoryName;
		categoryValue = activeWantListItems[selectedItem].categoryValue;
		keywords = activeWantListItems[selectedItem].keywords ;
		showTheAd();	
	}  else { // We don't have a usable list, 
		//so we'll let Amazon choose the default ad for us
		selectedItem = 0;
		var AmazonAdRequestString = composeAmazonOmakaseAdRequestString(publisherID, adsize);
		if (showData == "true") {
			dataFrame.innerHTML = "<br />" + adsize + " " + publisherID + " User has no want list";
		}
		var src =  "<iframe id='adSpace' scrolling='no' style='position:relative; top:0px; left:0px;' width='" 
			+ adWidth + "px' height= '" + adHeight + "px' src='" + AmazonAdRequestString + "' />"; 
		iFrame.innerHTML =  src;
	}	
	hideMenu();
	clearTimeout(ad_timer);
	ad_timer=setTimeout("showXooXooXMsg()",waitAfterAdTime);
	
}



function showXooXooXMsg()
{	
	var src =  "<iframe id='adSpace' scrolling='no' style='position:relative; top:0px; left:0px' onclick='showEditor();' frameborder='0' marginheight='0' marginwidth='0' vspace='0' hspace='0' width='" 
	+ adWidth + "px' height= '" + adHeight + "px' src='" + betweenAdsMessagingString + "' />";
	
	iFrame.innerHTML =  src;
	if (showData == "true") {
		dataFrame.innerHTML = "<br />" + adsize + " " + betweenAdsMessaging;
	}
	clearTimeout(ad_timer);
	ad_timer=setTimeout("showAd()",waitAfterMsgTime);
	
}

function showTheAd() {
		var AmazonAdRequestString = composeAmazonAdRequestString (	publisherID, adsize, categoryValue, keywords );
		if (showData == "true") {
			dataFrame.innerHTML = "<br />" + adsize + " " + publisherID + " " + categoryValue + " " + keywords;
		}
		var src =  "<iframe id='adSpace' style='position:relative; top:0px; left:0px' scrolling='no' width='" 
			+ adWidth + "px' height= '" + adHeight + "px' src='" + AmazonAdRequestString + "' />"; 
		iFrame.innerHTML =  src;
		numberOfAdsShown++;
	ad_timer=setTimeout("showXooXooXMsg()",30000);

}

function composeAmazonAdRequestString(publisherID, adSize,theCategory, theKeywords) { // returns formatted request string
	var httpText = "http://rcm.amazon.com/e/cm?t=";	
	var accountText = publisherID;
	var adSizeText = getAdSizeText(adSize);
	var searchText = "&search=";
	var subSearch = getSubSearch(theKeywords.replace(/^\s+|\s+$/g,""));
	var currentSearch = subSearch;
	var searchString = subSearch.replace(/^\s+|\s+$/g,"").replace(/\s+/g,'+'); 
	// trims leading and trailing spaces and replaces an arbitrary number of contiguous internal spaces with a '+'
	// since this is going into a queryString (URL)				
	var formatText = "&fc1=000000&lt1=&lc1=3366FF&bg1=FFFFFF&f=ifr";
	var src = httpText + accountText + adSizeText + theCategory + searchText + searchString + formatText;
	return src;
}

 
function composeAmazonOmakaseAdRequestString(publisherID, adSize) {
	var httpText = "http://rcm.amazon.com/e/cm?t=";	
	var accountText = publisherID;
	var adSizeText = getAdSizeText(adSize);
	// trims leading and trailing spaces and replaces an arbitrary number of contiguous internal spaces with a '+'
	// since this is going into a queryString (URL)				
	var formatText = "&fc1=000000&lt1=&lc1=3366FF&bg1=FFFFFF&f=ifr";
	var src = httpText + accountText + adSizeText + formatText;
	return src;
 }
 
function getSubSearch(s) { 
	// s is a set of comma separated keywords each of which should be searched for separately
	// this function tokenizes the string and returns ONE of the tokenized substrings as the searchString
	// which one is selected randomly

	var a1 = s.split(/,\s?/); //tokenizes s into array a1 using "," or ", " as delimiter
	var i = Math.floor(Math.random()*a1.length);
	return a1[i];
}
		
function getAdSizeText(adSize) { // returns formated string indicating size of ad
	var s;
	switch (adSize)
	{
	  // Changed by SLM 03-03-2009. Added support for the 125x125 and 234x60 sizes
	  // to provide these ad sizes to David Fraden for his Maui site
	  // see https://affiliate-program.amazon.com/gp/associates/network/build-links
	  //   /banner/get-html.html?category=books
	  case "125x125":
	  s = "&o=1&p=21&l=st1&mode=";
	  break;
	  case "234x60":
	  s =  "&o=1&p=42&l=st1&mode=";
	  break;
	  // end of SLM 03-03-2009 addition
	  case "120x150":
	  s = "&o=1&p=6&l=st1&mode=";
	  break;
	  case "728x90":
	  s =  "&o=1&p=48&l=st1&mode=";
	  break;
	  case "468x60":
	  s =  "&o=1&p=13&l=st1&mode=";
	  break;
	  case "180x150":
	  s =  "&o=1&p=9&l=st1&mode=";
	  break;
	  case "120x450":
	  s =  "&o=1&p=10&l=st1&mode=";
	  break;
	  case "120x600":
	  s =  "&o=1&p=11&l=st1&mode=";
	  break;
	  case "300x250":
	  s =  "&o=1&p=12&l=st1&mode=";
	  break;
	  case "160x600":
	  s =  "&o=1&p=14&l=st1&mode=";
	  break;
	  case "468x240":
	  s =  "&o=1&p=15&l=st1&mode=";
	  break;
	  case "468x336":
	  s =  "&o=1&p=16&l=st1&mode=";
	  break;
	  
	  default:
	  s =  "&o=1&p=13&l=st1&mode=";
	} 
	return s;
}

function parseRetailersCategoryTable() {
	var xhttp;
	if (window.XMLHttpRequest) {
  		xhttp=new XMLHttpRequest();
  	}
	else // Internet Explorer 5/6
  	{
  		xhttp=new ActiveXObject("Microsoft.XMLHTTP");
 	 }
	xhttp.open("GET","http://www.xooxoox.com/retailersCategoriesTable.xml",false);
	xhttp.send("");
	var xmlDoc=xhttp.responseXML; 
	return xmlDoc;
}

function documentWrite(nextLine){
	theTextBuffer += nextLine;
	return theTextBuffer;
}

function doMouseOut() {
	document.getElementById("controlsFrame").style.visibility="hidden";
}

function doMouseOver() {
	document.getElementById("controlsFrame").style.visibility="visible";
}

function createControlsFrame( )  {
	var xmlDoc = parseRetailersCategoryTable();  
	// uses global vars selectedRetailerName, selectedCategoryName 
	var fullXMLTable  				= xmlDoc.getElementsByTagName("retailercategories");
	var listOfRetailers   			= xmlDoc.getElementsByTagName("retailer");
	var listOfRetailersLabelText   	= xmlDoc.getElementsByTagName("labelText");
	var listOfRetailersDataValue   	= xmlDoc.getElementsByTagName("dataValue");
	var listOfAllCategories   		= xmlDoc.getElementsByTagName("category");
	var listOfALLCategoryLabels 	= xmlDoc.getElementsByTagName("categoryLabel");
	var listOfAllCategoryData 		= xmlDoc.getElementsByTagName("categoryData");
	var listOfCategories  = new Array;
	var retailerNames     = new Array;
	var retailerValues    = new Array;
	var categoryNames     = new Array;
	var categoryValues    = new Array;
	var logoAreaHeight = 160;
	
	var adWidth = AdDimensions[adsize].width; 
	var adHeight = AdDimensions[adsize].height; 
	//var adWidth =  160;
	//var adHeight =  600;
	
	var cntlBarWidth =  AdDimensions[adsize].logoAreaWidth; 
	if (AdDimensions[adsize].layout == "portrait") var cntlBarHeight = AdDimensions[adsize].logoAreaHeight /2;
	else var cntlBarHeight = AdDimensions[adsize].logoAreaHeight /2;
	var cntlBarLeft =  0 ;
	var cntlBarTop = -adHeight;
	if (AdDimensions[adsize].layout == "portrait") var cntlTextHeight = cntlBarHeight;
	else var cntlTextHeight = .75 * cntlBarHeight;
	
	var logoAreaWidth = AdDimensions[adsize].logoAreaWidth -2; 
	var logoAreaHeight = AdDimensions[adsize].logoAreaHeight - cntlBarHeight -2 ;
	if (AdDimensions[adsize].layout == "portrait") var logoAreaLeft =  -cntlBarWidth ;
	else var logoAreaLeft = -cntlBarWidth;
	if (AdDimensions[adsize].layout == "portrait") var logoAreaTop = cntlBarTop + cntlBarHeight;
	else logoAreaTop = cntlBarTop + cntlBarHeight;
	var logoTextHeight = AdDimensions[adsize].logoTextHeight;
	
	var cntlAreaWidth = logoAreaWidth;
	var cntlAreaHeight = logoAreaHeight;
	if (AdDimensions[adsize].layout == "portrait") var cntlAreaLeft =  -cntlBarWidth -logoAreaWidth;
	else var cntlAreaLeft = -cntlBarWidth - logoAreaWidth;
	if (AdDimensions[adsize].layout == "portrait") var cntlAreaTop = logoAreaTop;
	else var cntlAreaTop = -logoAreaHeight;
	
	if (AdDimensions[adsize].layout == "portrait") var msgAreaWidth = adWidth;
	else var msgAreaWidth = adWidth - cntlBarWidth;
	if (AdDimensions[adsize].layout == "portrait") var msgAreaHeight = adHeight - cntlBarHeight - cntlAreaHeight;
	else var msgAreaHeight = adHeight;
	if (AdDimensions[adsize].layout == "portrait") var msgAreaLeft = -cntlBarWidth -logoAreaWidth - cntlAreaWidth -1;
	else var msgAreaLeft = -2 * cntlBarWidth; 
	if (AdDimensions[adsize].layout == "portrait") var msgAreaTop = cntlAreaTop + cntlAreaHeight;
	else var msgAreaTop = -adHeight;

	if (AdDimensions[adsize].layout == "portrait") var dataDivWidth = 30;
	else var dataDivWidth = adWidth;
	if (AdDimensions[adsize].layout == "portrait") var dataDivHeight = adHeight;
	else var dataDivHeight = 20;
	if (AdDimensions[adsize].layout == "portrait") var dataDivLeft = msgAreaLeft;
	else var dataDivLeft = - msgAreaWidth - cntlAreaWidth - logoAreaWidth - cntlBarWidth;
	if (AdDimensions[adsize].layout == "portrait") var dataDivTop = cntlBarTop; 
	else var dataDivTop = 5; 
	
	if (AdDimensions[adsize].layout == "portrait")  {
		var dataDivStyle 	= 'style="-webkit-transform: rotate(90deg); ' 
							+ '-moz-transform: rotate(90deg);  '
							+ 'filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);"';
	}
	else var dataDivStyle = '';
	
	
	
	// The AD DIVISION ************************************************************
	documentWrite('<div id="adIFrame" onMouseOut="doMouseOut();" style="z-index:2;  width:'  + adWidth + 'px; height:' + adHeight + 'px">');
	
			// The ad gets replace by setting the innerHTML
			
	
	documentWrite('<' + '/div>');
	// END OF The AD DIVISION ************************************************************
	
	
	// The CONTROL BAR  DIVISION ************************************************************
    documentWrite('<div id="controlBarDiv" onMouseOver="showMenu();" onMouseOut="waitThenHideMenu();" ')
	documentWrite(' "style="float:left; z-index:3; background-color:#FF6600;  width:');
	documentWrite(cntlBarWidth + 'px; height:' + cntlBarHeight + 'px; position:relative; left:' + cntlBarLeft + 'px; top:' + cntlBarTop + 'px">');
		
			// ********* put the XooXooX Label on the CONTROL BAR below here *******************************************
        	documentWrite('<center><span  id="controlBarSpan" style="padding: 5px; line-height: ');
			documentWrite(cntlTextHeight + 'px; font-size:' + cntlTextHeight + 'px;font-family:');
			documentWrite("'" + 'Curlz MT' + "'" + '">XooXooX<' + '/span><' + '/center>'); 
			// ********* put the XooXooX Label on the CONTROL BAR above here *******************************************
			
    documentWrite('<' + '/div>');
	// END OF The CONTROL BAR  DIVISION ************************************************************
	
	
	// The LOGO MSG DIVISION ************************************************************
	documentWrite('<div  id="logoDiv"  onMouseOut="doMouseOut();" onClick="javascript:showEditor();" '); 
	documentWrite('style="float: left; z-index:4; background-color:#FFFFFF; border:1px solid #FF6600;  width:');
	documentWrite(logoAreaWidth + 'px; height:' + logoAreaHeight + 'px; position:relative; left:' + logoAreaLeft + 'px; top:' + logoAreaTop + 'px">');
	
			// ********* put the Selected A/B Messaging below here *******************************************
        	documentWrite('<center><span id="logoSpan" style="font-size:' + logoTextHeight + 'px; color:#000000">');
			documentWrite(theSelectedAorBMessage + '<' + '/span><' + '/center>');
			// ********* put the Selected A/B Messaging above here *******************************************
			
    documentWrite('<' + '/div>');
	// END OF The LOGO MSG DIVISION ************************************************************	
		
		
	// The MINI-CONTROLS POP-UP DIVISION ************************************************************	
    documentWrite('<div  id="controlsFrame"  onMouseOut="doMouseOut();" style="float:left; z-index:8; background-color:#CC6600; visibility:hidden; width:');
	documentWrite(cntlAreaWidth + 'px; height:' + cntlAreaHeight + 'px;  position:relative; left:' + cntlAreaLeft + 'px; top:' + cntlAreaTop + 'px">'); 
	
		// ********* put mini-controls menu below here *******************************************
        documentWrite('<table id="theMenu" name="theMenu" name="theMenu" style="z-index:9; background-color:#CC6600; visibility:hidden; display:none" ');
		documentWrite('onMouseOver=' + "'" + 'showMenu();' + "'");
		documentWrite(' onMouseOut=' + "'" + 'waitThenHideMenu();' + "'>"); 

    		documentWrite('<tr>');
				documentWrite('<td>');
					for (var i = 0; i < listOfRetailers.length; i++) {
						retailerNames[i]    = listOfRetailersLabelText[i].textContent;
						retailerValues[i]   = listOfRetailersDataValue[i].textContent; 
						if (retailerNames[i] == selectedRetailerName ) { // we are only supporting Amazon in this release
							documentWrite('<select id="categoryMenu" onChange="changedCategory(this);">');
							var k = 0;
							listOfCategories[i] = new Array;
							categoryNames[i] = new Array;
							categoryValues[i] = new Array;
							for (var j = 0; j < listOfRetailers[i].childNodes.length; j++) {		
								if (listOfRetailers[i].childNodes[j].nodeName == "category") {  
									listOfCategories[i][k] = listOfRetailers[i].childNodes[j];
									for (var m = 0; m < listOfCategories[i][k].childNodes.length; m++) {
										if (listOfCategories[i][k].childNodes[m].nodeName == "categoryLabel") {
											categoryNames[i][k] = listOfCategories[i][k].childNodes[m].textContent;
										} else if (listOfCategories[i][k].childNodes[m].nodeName == "categoryData") {
											categoryValues[i][k] = listOfCategories[i][k].childNodes[m].textContent;
										}	
									}
									documentWrite('<option value="' + categoryValues[i][k] + '">' + categoryNames[i][k] + '<' + '/option>');
									categoryNamesToValues[categoryNames[i][k]] = categoryValues[i][k]; // create globals table
									categoryValuesToNames[categoryValues[i][k]] = categoryNames[i][k]; // create globals table
									k++;
								}
							}
							documentWrite('<' + '/select>'); 
						}
					}
	 			documentWrite('<' + '/td>');
			documentWrite('<' + '/tr>');
       		documentWrite('<tr>');
				documentWrite('<td>');
					documentWrite('<input id="keywordsInputBox" type="text" ');
						documentWrite('onChange="changedKeywords(this);" onKeyUp="changingKeywords(this);" onTextChanged="changedKeywords(this);">');
                	documentWrite('<' + '/input>');
        		documentWrite('<' + '/td>');
        	documentWrite('<' + '/tr>');
        	documentWrite('<tr>');
        		documentWrite('<td>');
   			 		documentWrite('<select id="commandMenu">');
						documentWrite('<option value="Add" onclick="javascript:addItemToList(this);">Add to Want List<' + '/option>');
						documentWrite('<option value="Replace" onclick="javascript:replaceItemInList(this);">Replace in Want List<' + '/option>');
               			documentWrite('<option value="Edit" onclick="javascript:showEditor();">Edit Want List<' + '/option>');
						documentWrite('<!--option value="SaveWantList">Save copy of your Want List<' + '/option-->');
						documentWrite('<!--option value="LoadWantList">Load a Want List<' + '/option-->');
						documentWrite('<!--option value="ShareWantList">Share your Want List<' + '/option-->');
       		 			documentWrite('<!--option value="ShareOffer">Share an offer<' + '/option-->');
       		 			documentWrite('<!--option value="SendFeedback">Send XooXooX Feedback<' + '/option-->');
       					documentWrite('<!--option value="BookmarkOffer">Bookmark an offer<' + '/option-->');
         				documentWrite('<!--option value="ReviewBookmarks">Review bookmarked offers<' + '/option-->');
          				documentWrite('<option value="Help"  onclick="javascript:showHelp();">Help<' + '/option>');
   			  		documentWrite('<' + '/select>');
            	documentWrite('<' + '/td>');
        	documentWrite('<' + '/tr>');
		documentWrite('<' + '/table>');
		// ********* put mini-controls menu above here *******************************************
			
    documentWrite('<' + '/div>'); 
	// END OF The MINI-CONTROLS POP-UP DIVISION  ************************************************************	
		
		
	// The MSG AREA-DIVISION ************************************************************	
    documentWrite('<div  id="msgAreaDiv" style="float:left; z-index:6; visibility:hidden; display:block; width:');
	documentWrite(msgAreaWidth + 'px; height:' + msgAreaHeight + 'px; position:relative; left:' + msgAreaLeft + 'px; top:' + msgAreaTop + 'px">'); 
	
			// This section is reserved for new A/B Messaging that is independent of the ad switching
			// ********* put the Between Ad Messages below here *******************************************
       		//documentWrite('<center><span  id="msgAreaSpan">Message Area<' + '/span><' + '/center>'); 
			// ********* put the Between Ad Messages above here *******************************************
		
    documentWrite('<' + '/div>');
	// END OF The MSG AREA-DIVISION ************************************************************	
		
		
	// The DATA-DIVISION ************************************************************
	showData = getQueryVariable("showdata");
	if (showData == "true") {	
    	documentWrite('<div  id="dataDiv" style="float:left;  z-index:7; color:#CCCCCC; width:');
		documentWrite(dataDivWidth + 'px; height:' + dataDivHeight + 'px; position:relative; left:' + dataDivLeft + 'px; top:' + dataDivTop + 'px">');
			documentWrite('<span id="dataFrame" ' + dataDivStyle +'>' + dataFrameInnerHTML + '<' + '/span>');
    	documentWrite('<' + '/div>');
	} else {
		// Don't show the Data area
	}	
	// END OF The DATA DIVISION ************************************************************	
	

	
	document.body.innerHTML =  theTextBuffer;  // global variable
	
}
