
var sessionId;

var imagesDirectory;

var ratePackageId;
var lastRatePackageId;
var categoryId;
var adText;
var parentProperty;
var childProperty;
var forceRefreshPreview;
var forceRefreshKeywords;

var maximumLinesError = false;
var minimumLinesError = false;
var showPackageChange = true;

var currentRequests = new Array();
	//	alert(currentRequests.length);
var Http = {
	ReadyState: {
		Uninitialized: 0,
		Loading: 1,
		Loaded:2,
		Interactive:3,
		Complete: 4
	},
		
	Status: {
		OK: 200,
		
		Created: 201,
		Accepted: 202,
		NoContent: 204,
		
		BadRequest: 400,
		Forbidden: 403,
		NotFound: 404,
		Gone: 410,
		
		ServerError: 500
	},
		
	Cache: {
		Get: 1,
		GetCache: 2,
		GetNoCache: 3,
		FromCache: 4
	},
	
	Method: {Get: "GET", Post: "POST", Put: "PUT", Delete: "DELETE"},
	
	enabled: false,
	logging: false,
	_get: null,	
	_cache: new Object(),
	
	Init: function(){
		Http._get = Http._getXmlHttp()
		Http.enabled = (Http._get != null)
		Http.logging = (window.Logging != null);
	},
	
	_getXmlHttp: function(){

	  if(window.XMLHttpRequest) {
	    try { return new XMLHttpRequest(); } catch(e) { req = false; }
	  }
	  else if(window.ActiveXObject)
	  {
	    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {
	    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { req = false; } }
	  }

		return null;
	},


	get: function(params, callback_args){	
		if (!Http.enabled) throw "Http: XmlHttpRequest not available.";
		
		var url = params.url;
		if (!url) throw "Http: A URL must be specified";

		var cache = params.cache || Http.Cache.Get;
		var method = params.method || Http.Method.Get;
		var callback = params.callback;
		
		if ((cache == Http.Cache.FromCache) || (cache == Http.Cache.GetCache))
		{
			var in_cache = Http.from_cache(url, callback, callback_args)

			if (Http.logging){
				Logging.log(["Http: URL in cache: " + in_cache]);
			}

			if (in_cache || (cache == Http.Cache.FromCache)) return in_cache;
		}
		
		if (cache == Http.Cache.GetNoCache)
		{
			var sep = (-1 < url.indexOf("?")) ? "&" : "?"	
			url = url + sep + "__=" + encodeURIComponent((new Date()).getTime());
		}

		//alert('check readystate');
		//alert(document);
		if (document.body != null) {
			document.body.style.cursor = "wait";
		}

		var httpGetArray = new Array(params, callback_args);
		//alert(currentRequests.length);
		currentRequests[currentRequests.length] = httpGetArray;
		//alert(currentRequests.length);
		if (currentRequests.length > 1) {
			// Already Processing
			alert('adding ' + params.url);
			alert(currentRequests.length);
			this._get.abort();
			return;
			
		} else {
			//alert('not adding');
			currentRequests.splice(0,1);
		}

		// Only one request at a time, please
		if ((Http._get.readyState != Http.ReadyState.Uninitialized) && 
			(Http._get.readyState != Http.ReadyState.Complete)){
			this._get.abort();
			
			if (Http.logging){
				Logging.log(["Http: Aborted request in progress."]);
			}
		}
		//alert("open " + url + " with " + method);
		Http._get.open(method, url, true);
		
		Http._get.onreadystatechange =  function() {
			if (Http._get.readyState != Http.ReadyState.Complete) {
				//alert('not complete');
				return;
			}
			
			//alert("Http: Returned, status: " + Http._get.status);
			if (Http.logging){
				Logging.log(["Http: Returned, status: " + Http._get.status]);
			}

			if ((cache == Http.Cache.GetCache) && (Http._get.status == Http.Status.OK)){
				Http._cache[url] = Http._get.responseText;
			}
			
			if (callback_args == null) callback_args = new Array();

			var cb_params = new Array();
			cb_params.push(Http._get);
			for(var i=0;i<callback_args.length;i++)
				cb_params.push(callback_args[i]);
				
			callback.apply(null, cb_params);
		}
		//alert('readystate = ' + Http._get.readyState);
		
		if(Http.logging){
			Logging.log(["Http: Started\n\tURL: " + url + "\n\tMethod: " + method + "; Cache: " + Hash.keyName(Http.Cache,cache)])
		}
		
		Http._get.send(params.body || null);
		if (document.body != null) {
			document.body.style.cursor = "default";
		}
		//alert('done');
	},
	
	from_cache: function(url, callback, callback_args){
		var result = Http._cache[url];
		
		if (result != null) {
			var response = new Http.CachedResponse(result)
			
			var cb_params = new Array();
			cb_params.push(response);
			for(var i=0;i<callback_args.length;i++)
				cb_params.push(callback_args[i]);
							
			callback.apply(null, cb_params);
				
			return true
		}
		else
			return false
	},
	
	clear_cache: function(){
		Http._cache = new Object();
	},
	
	is_cached: function(url){
		return Http._cache[url]!=null;
	},
	
	CachedResponse: function(response) {
		this.readyState = Http.ReadyState.Complete
		this.status = Http.Status.OK
		this.responseText = response
	}	
}

var Http2 = {
	ReadyState: {
		Uninitialized: 0,
		Loading: 1,
		Loaded:2,
		Interactive:3,
		Complete: 4
	},
		
	Status: {
		OK: 200,
		
		Created: 201,
		Accepted: 202,
		NoContent: 204,
		
		BadRequest: 400,
		Forbidden: 403,
		NotFound: 404,
		Gone: 410,
		
		ServerError: 500
	},
		
	Cache: {
		Get: 1,
		GetCache: 2,
		GetNoCache: 3,
		FromCache: 4
	},
	
	Method: {Get: "GET", Post: "POST", Put: "PUT", Delete: "DELETE"},
	
	enabled: false,
	logging: false,
	_get: null,	
	_cache: new Object(),
	
	Init: function(){
		Http2._get = Http2._getXmlHttp()
		Http2.enabled = (Http2._get != null)
		Http2.logging = (window.Logging != null);
	},
	
	_getXmlHttp: function(){

	  if(window.XMLHttpRequest) {
	    try { return new XMLHttpRequest(); } catch(e) { req = false; }
	  }
	  else if(window.ActiveXObject)
	  {
	    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {
	    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { req = false; } }
	  }

		return null;
	},


	get: function(params, callback_args){	
		if (!Http2.enabled) throw "Http: XmlHttpRequest not available.";
		
		var url = params.url;
		if (!url) throw "Http: A URL must be specified";
				
		var cache = params.cache || Http2.Cache.Get;
		var method = params.method || Http2.Method.Get;
		var callback = params.callback;
		
		if ((cache == Http2.Cache.FromCache) || (cache == Http2.Cache.GetCache))
		{
			var in_cache = Http2.from_cache(url, callback, callback_args)

			if (Http2.logging){
				Logging.log(["Http: URL in cache: " + in_cache]);
			}

			if (in_cache || (cache == Http2.Cache.FromCache)) return in_cache;
		}
		
		if (cache == Http2.Cache.GetNoCache)
		{
			var sep = (-1 < url.indexOf("?")) ? "&" : "?"	
			url = url + sep + "__=" + encodeURIComponent((new Date()).getTime());
		}
//		alert('check readystate');
		document.body.style.cursor = "wait";

		var httpGetArray = new Array(params, callback_args);
		//alert(currentRequests.length);
		currentRequests[currentRequests.length] = httpGetArray;
		//alert(currentRequests.length);
		if (currentRequests.length > 1) {
			// Already Processing
			alert('adding ' + params.url);
			alert(currentRequests.length);
			this._get.abort();
			return;
			
		} else {
			//alert('not adding');
			currentRequests.splice(0,1);
		}

		// Only one request at a time, please
		if ((Http2._get.readyState != Http2.ReadyState.Uninitialized) && 
			(Http2._get.readyState != Http2.ReadyState.Complete)){
			this._get.abort();
			
			if (Http2.logging){
				Logging.log(["Http: Aborted request in progress."]);
			}
		}
//		alert('ok...open ' + url);
		
		Http2._get.open(method, url, true);

		Http2._get.onreadystatechange =  function() {
			if (Http2._get.readyState != Http2.ReadyState.Complete) {
				//alert('not complete');
				return;
			}
			
			//alert("Http: Returned, status: " + Http._get.status);
			if (Http2.logging){
				Logging.log(["Http: Returned, status: " + Http2._get.status]);
			}

			if ((cache == Http2.Cache.GetCache) && (Http2._get.status == Http2.Status.OK)){
				Http2._cache[url] = Http2._get.responseText;
			}
			
			if (callback_args == null) callback_args = new Array();

			var cb_params = new Array();
			cb_params.push(Http2._get);
			for(var i=0;i<callback_args.length;i++)
				cb_params.push(callback_args[i]);
				
			callback.apply(null, cb_params);
		}
		//alert('readystate = ' + Http._get.readyState);
		
		if(Http2.logging){
			Logging.log(["Http: Started\n\tURL: " + url + "\n\tMethod: " + method + "; Cache: " + Hash.keyName(Http2.Cache,cache)])
		}
		
		Http2._get.send(params.body || null);
		document.body.style.cursor = "default";
		//alert('done');
	},
	
	from_cache: function(url, callback, callback_args){
		var result = Http2._cache[url];
		
		if (result != null) {
			var response = new Http2.CachedResponse(result)
			
			var cb_params = new Array();
			cb_params.push(response);
			for(var i=0;i<callback_args.length;i++)
				cb_params.push(callback_args[i]);
							
			callback.apply(null, cb_params);
				
			return true
		}
		else
			return false
	},
	
	clear_cache: function(){
		Http2._cache = new Object();
	},
	
	is_cached: function(url){
		return Http2._cache[url]!=null;
	},
	
	CachedResponse: function(response) {
		this.readyState = Http2.ReadyState.Complete
		this.status = Http2.Status.OK
		this.responseText = response
	}	
}

var Http3 = {
	ReadyState: {
		Uninitialized: 0,
		Loading: 1,
		Loaded:2,
		Interactive:3,
		Complete: 4
	},
		
	Status: {
		OK: 200,
		
		Created: 201,
		Accepted: 202,
		NoContent: 204,
		
		BadRequest: 400,
		Forbidden: 403,
		NotFound: 404,
		Gone: 410,
		
		ServerError: 500
	},
		
	Cache: {
		Get: 1,
		GetCache: 2,
		GetNoCache: 3,
		FromCache: 4
	},
	
	Method: {Get: "GET", Post: "POST", Put: "PUT", Delete: "DELETE"},
	
	enabled: false,
	logging: false,
	_get: null,	
	_cache: new Object(),
	
	Init: function(){
		Http3._get = Http3._getXmlHttp()
		Http3.enabled = (Http3._get != null)
		Http3.logging = (window.Logging != null);
	},
	
	_getXmlHttp: function(){

	  if(window.XMLHttpRequest) {
	    try { return new XMLHttpRequest(); } catch(e) { req = false; }
	  }
	  else if(window.ActiveXObject)
	  {
	    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {
	    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { req = false; } }
	  }

		return null;
	},


	get: function(params, callback_args){	
		if (!Http3.enabled) throw "Http: XmlHttpRequest not available.";
		
		var url = params.url;
		if (!url) throw "Http: A URL must be specified";
				
		var cache = params.cache || Http3.Cache.Get;
//		var method = params.method || Http3.Method.Get;
		var method = 'POST'; 
		var callback = params.callback;
		
		if ((cache == Http3.Cache.FromCache) || (cache == Http3.Cache.GetCache))
		{
			var in_cache = Http3.from_cache(url, callback, callback_args)

			if (Http3.logging){
				Logging.log(["Http: URL in cache: " + in_cache]);
			}

			if (in_cache || (cache == Http3.Cache.FromCache)) return in_cache;
		}
		
		if (cache == Http3.Cache.GetNoCache)
		{
			var sep = (-1 < url.indexOf("?")) ? "&" : "?"	
			url = url + sep + "__=" + encodeURIComponent((new Date()).getTime());
		}
//		alert('check readystate');
		document.body.style.cursor = "wait";

		var httpGetArray = new Array(params, callback_args);
		//alert(currentRequests.length);
		currentRequests[currentRequests.length] = httpGetArray;
		//alert(currentRequests.length);
		if (currentRequests.length > 1) {
			// Already Processing
			alert('adding ' + params.url);
			alert(currentRequests.length);
			this._get.abort();
			return;
			
		} else {
			//alert('not adding');
			currentRequests.splice(0,1);
		}

		// Only one request at a time, please
		if ((Http3._get.readyState != Http3.ReadyState.Uninitialized) && 
			(Http3._get.readyState != Http3.ReadyState.Complete)){
			this._get.abort();
			
			if (Http3.logging){
				Logging.log(["Http: Aborted request in progress."]);
			}
		}
//		alert('ok...open ' + url);
		
		Http3._get.open(method, url, true);

		Http3._get.onreadystatechange =  function() {
			if (Http3._get.readyState != Http3.ReadyState.Complete) {
				//alert('not complete');
				return;
			}
			
			//alert("Http: Returned, status: " + Http._get.status);
			if (Http3.logging){
				Logging.log(["Http: Returned, status: " + Http3._get.status]);
			}

			if ((cache == Http3.Cache.GetCache) && (Http3._get.status == Http3.Status.OK)){
				Http3._cache[url] = Http3._get.responseText;
			}
			
			if (callback_args == null) callback_args = new Array();

			var cb_params = new Array();
			cb_params.push(Http3._get);
			for(var i=0;i<callback_args.length;i++) {
				cb_params.push(callback_args[i]);
			}
				
			callback.apply(null, cb_params);
		}
		//alert('readystate = ' + Http._get.readyState);
		
		if(Http3.logging){
			Logging.log(["Http: Started\n\tURL: " + url + "\n\tMethod: " + method + "; Cache: " + Hash.keyName(Http3.Cache,cache)])
		}
		//alert("Http: Started\n\tURL: " + url);
		//alert(url.length);
		
		Http3._get.send(params.body || null);
		document.body.style.cursor = "default";
		//alert('done');
	},
	
	post: function(params, callback_args){	
		if (!Http3.enabled) throw "Http: XmlHttpRequest not available.";
		
		var url = params.url;
		if (!url) throw "Http: A URL must be specified";

		var parameters = params.params;
						
		var method = 'POST'; 
		var cache = params.cache || Http3.Cache.Get;
		var callback = params.callback;
		
		if ((cache == Http3.Cache.FromCache) || (cache == Http3.Cache.GetCache))
		{
			var in_cache = Http3.from_cache(url, callback, callback_args)

			if (Http3.logging){
				Logging.log(["Http: URL in cache: " + in_cache]);
			}

			if (in_cache || (cache == Http3.Cache.FromCache)) return in_cache;
		}
		
		if (cache == Http3.Cache.GetNoCache)
		{
			var sep = (-1 < url.indexOf("?")) ? "&" : "?"	
//			url = url + sep + "__=" + encodeURIComponent((new Date()).getTime());
		}
		document.body.style.cursor = "wait";

		var httpGetArray = new Array(params, callback_args);
		//alert(currentRequests.length);

		// Only one request at a time, please
		if ((Http3._get.readyState != Http3.ReadyState.Uninitialized) && 
			(Http3._get.readyState != Http3.ReadyState.Complete)){
			this._get.abort();
			
			if (Http3.logging){
				Logging.log(["Http: Aborted request in progress."]);
			}
		}
//		alert('ok...open ' + url);
//		alert(method);
		//alert(url);
		
		Http3._get.open(method, url, true);

		Http3._get.onreadystatechange =  function() {
			if (Http3._get.readyState != Http3.ReadyState.Complete) {
				//alert('not complete');
				return;
			}
			
			//alert("Http: Returned, status: " + Http._get.status);
			if (Http3.logging){
				Logging.log(["Http: Returned, status: " + Http3._get.status]);
			}

			if ((cache == Http3.Cache.GetCache) && (Http3._get.status == Http3.Status.OK)){
				Http3._cache[url] = Http3._get.responseText;
			}
			
			if (callback_args == null) callback_args = new Array();

			var cb_params = new Array();
			cb_params.push(Http3._get);
			for(var i=0;i<callback_args.length;i++) {
				cb_params.push(callback_args[i]);
			}
				
			callback.apply(null, cb_params);
		}
		//alert('readystate = ' + Http._get.readyState);
		
		if(Http3.logging){
			Logging.log(["Http: Started\n\tURL: " + url + "\n\tMethod: " + method + "; Cache: " + Hash.keyName(Http3.Cache,cache)])
		}
		//alert("Http: Started\n\tURL: " + url);
		//alert(url.length);
		
		Http3._get.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		Http3._get.setRequestHeader("Content-length", parameters.length);
		Http3._get.setRequestHeader("Connection","close");
		//alert(parameters);
		Http3._get.send(parameters);
		document.body.style.cursor = "default";
		//alert('done');
	},

	from_cache: function(url, callback, callback_args){
		var result = Http3._cache[url];
		
		if (result != null) {
			var response = new Http3.CachedResponse(result)
			
			var cb_params = new Array();
			cb_params.push(response);
			for(var i=0;i<callback_args.length;i++) {
				cb_params.push(callback_args[i]);
			}
							
			callback.apply(null, cb_params);
				
			return true
		}
		else
			return false
	},
	
	clear_cache: function(){
		Http3._cache = new Object();
	},
	
	is_cached: function(url){
		return Http3._cache[url]!=null;
	},
	
	CachedResponse: function(response) {
		this.readyState = Http3.ReadyState.Complete
		this.status = Http3.Status.OK
		this.responseText = response
	}	
}


Http.Init()
Http2.Init()
Http3.Init()

function json_response(response){
	var js = response.responseText;
	try{
		return eval(js); 
	} catch(e){
		if (Http.logging){
			Logging.logError(["json_response: " + e]);
		}
		else{
			alert("Error: " + e + "\n" + js);
		}
		return null;
	}
}

function getResponseProps(response, header){
	try {
		var s = response.getResponseHeader(header || 'X-Ajax-Props');
		if (s==null || s=="")
			return new Object()
		else
			return eval("o="+s)
	} catch (e) { return new Object() }
}

function fill(xmlreply, catelmt)
{
  if (xmlreply.status == Http.Status.OK){
    var catresponse = xmlreply.responseText;
	//alert();
//    if (navigator.appName == 'Netscape') {
//  	  alert(catresponse);
//    }
    var catar = catresponse.split("|");
    catelmt.length = 0;
    catelmt.length = catar.length;
    for (o=0; o < catar.length; o++){
      var itemar = catar[o].split('!');
			catelmt[o].value= itemar[0];
			catelmt[o].text = itemar[1];						
    }
  } else {
//    if (navigator.appName == 'Netscape') {
//    	  alert(xmlreply.status);
//      }
  }
}

function handledd(dd1)
{
  var idx = dd1.selectedIndex;
  var val = dd1[idx].text;
  var par = document.forms["placead"];
  var parelmts = par.elements;
  var catsel = parelmts["categories_id"];
  var section = dd1[idx].value;
  var caturl = "categories2.cmp?bfcid=" + sessionId + "&i=" + section; 
  //alert(section);
  //alert(caturl);
 	Http.get({
		url: caturl,
		callback: fill,
		cache: Http.Cache.Get
	}, [catsel]);
  
}

function getLocalRatesPackages(localZoneSelection, categoryId, testRates, advertisersType)
{
  var idx = localZoneSelection.selectedIndex;
//  var par = document.forms["placead"];
//  var parelmts = par.elements;
  //alert(document.getElementById("local_rate_packages_html").innerHTML);
  //alert(ratepackages);
  var zoneId = localZoneSelection[idx].value;
  //alert('zone=' + zoneId + " and cat=" + categoryId);
  //document.getElementById("local_rate_packages_html").innerHTML="test";
 	Http.get({
		url: "rate_packages2.cmp?bfcid=" + sessionId + "&selected_storefronts_id=" + zoneId + "&categories_id=" + categoryId + "&test_rates=" + testRates + "&advertisers_type=" + advertisersType,
		callback: setLocalRatesPackages,
		cache: Http.Cache.Get
	});
  
}

function setLocalRatesPackages(xmlreply)
{
  var ratepackages = document.getElementById("local_rate_packages_html");
  if (xmlreply.status == Http.Status.OK){
    var rpresponse = xmlreply.responseText;
	//ratepackages.innerHTML=rpresponse;
	jsFunction = "setZone";
	zoneJSStart = rpresponse.indexOf(jsFunction+"(");
	if (zoneJSStart >= 0) {
		jsString = rpresponse.substring(zoneJSStart + jsFunction.length+1);
		jsString = jsString.substring(0,jsString.indexOf(")"));  // Plus 8 for string lengh of setZone(		
		setZone(jsString);
	}
	jsFunction = "selectLocalRegion";
	zoneJSStart = rpresponse.indexOf(jsFunction+"(");
	if (zoneJSStart >= 0) {
		jsString = rpresponse.substring(zoneJSStart + jsFunction.length+1);
		jsString = jsString.substring(0,jsString.indexOf(")"));  // Plus 8 for string lengh of setZone(		
		selectLocalRegion(jsString);
	}
    
	ratepackages.innerHTML=rpresponse;
	//alert('after');
  }  
}

function getPreview(url, adText, textElementData, placeadPropertiesData) {
	//alert(adText);
	//alert(url);
	//alert(textElementData);
	//alert(placeadPropertiesData);
	//alert('State='+Http._get.readyState);
	Http3._get.abort();
	var urlSplit = url.split("?");
	var url = urlSplit[0];
	//alert(url);
	//var params = urlSplit[1] + '&print_preview_text=' + escape(adText) + textElementData + placeadPropertiesData;
	//alert(adText);
	var params = urlSplit[1] + '&print_preview_text=' + encodeURIComponent(adText) + textElementData + placeadPropertiesData;
//	alert(params);
 	Http3.post({
		url: url,
		params: params,
		callback: setPreview,
		cache: Http.Cache.GetNoCache
	});
}

function setPreview(xmlreply) {
try {
	//alert("callback worked"); 
  if (xmlreply.status == Http.Status.OK){
    var rpresponse = xmlreply.responseText;
    var previewDiv = document.getElementById("preview_div");
    var priceDiv = document.getElementById("price_div");
    var priceDiv2 = document.getElementById("price_div2");
    var errorDiv = document.getElementById("errorDiv");
    var stringTotalPrice = document.placead.string_total_ad_price;
    var line_count = document.placead.print_line_count;
    var word_count = document.placead.print_word_count;
	rpresponse = rpresponse.replace( /\n/g, "" );
	rpresponse = rpresponse.replace( /\r/g, "" );
	//alert(rpresponse);
	var lineCount=rpresponse.substring(0,rpresponse.indexOf("|"));
	rpresponse = rpresponse.substring(rpresponse.indexOf("|")+1);
	//alert('linecount = ' + lineCount);
	var wordCount = rpresponse.substring(0,rpresponse.indexOf("|"));
	rpresponse = rpresponse.substring(rpresponse.indexOf("|")+1);
	//alert(wordCount);
	var priceInfo = rpresponse.substring(0,rpresponse.indexOf("|"));
	rpresponse = rpresponse.substring(rpresponse.indexOf("|")+1);
	var previewInfo = rpresponse;
	if (priceInfo.indexOf("ERROR:") >= 0) {
	//	alert(priceInfo);
	//	alert(priceInfo.substring(6));
		var errorMessage = priceInfo.substring(6);
		if (errorMessage == "Maximum Lines Exceeded" && maximumLinesError == true) {
				//javascriptFunction = "changeStep(this);";
				//errorMessage = "Your ad text exceeds the maximum allowed lines for your selected package.  To keep your ad copy as is and upgrade to a different package,&nbsp;&nbsp; <a id='zones_step' href='" + targetUrl + "' onClick='"+javascriptFunction+"'>Click Here</a>";
				if (showPackageChange == true) {				
					targetUrl = "javascript://";
					javascriptFunction = "doSubmit(" + '"changeCoverageArea"' + ',"");';
					errorMessage = "Your ad text exceeds the maximum allowed lines for your selected package.  To keep your ad copy as is and upgrade to a different package,&nbsp;&nbsp; <span id='changeCoverageArea' style='color:black;cursor:pointer;' href='" + targetUrl + "' onClick='"+javascriptFunction+"'><u>Click Here</u></span>";
				} else {
					errorMessage = "You have exceeded the maximum number of lines. Adjust your text to fit in the preview box.";
				}
				//alert(errorMessage);
			    errorDiv.innerHTML='<p class="error" style="margin-top:10px;text-align:left;">' + errorMessage + '</p>';
			  	previewDiv.innerHTML=previewInfo;
				priceInfo="";
				priceDiv.innerHTML=priceInfo;
				if (priceDiv2 != null) {
					priceDiv2.innerHTML=priceInfo;	
				}
				//alert(stringTotalPrice);
				if (stringTotalPrice != null) {
					stringTotalPrice.value = priceInfo;
				}
				return;
		} else if (errorMessage == "Maximum Depth Exceeded" && maximumLinesError == true) {
				//javascriptFunction = "changeStep(this);";
				//errorMessage = "Your ad text exceeds the maximum allowed lines for your selected package.  To keep your ad copy as is and upgrade to a different package,&nbsp;&nbsp; <a id='zones_step' href='" + targetUrl + "' onClick='"+javascriptFunction+"'>Click Here</a>";
				if (showPackageChange == true) {				
					targetUrl = "javascript://";
					javascriptFunction = "doSubmit(" + '"changeCoverageArea"' + ',"");';
					errorMessage = "Your ad text exceeds the maximum allowed lines for your selected package.  To keep your ad copy as is and upgrade to a different package,&nbsp;&nbsp; <span id='changeCoverageArea' style='color:black;cursor:pointer;' href='" + targetUrl + "' onClick='"+javascriptFunction+"'><u>Click Here</u></span>";
				} else {
					errorMessage = "Your ad text exceeds the maximum number of lines that fit in your ad space. Please remove some of your ad text.";
				}
				//alert(errorMessage);
			    errorDiv.innerHTML='<p class="error" style="margin-top:10px;text-align:left;">' + errorMessage + '</p>';
			  	previewDiv.innerHTML=previewInfo;
				priceInfo="";
				priceDiv.innerHTML=priceInfo;
				if (priceDiv2 != null) {
					priceDiv2.innerHTML=priceInfo;	
				}
				//alert(stringTotalPrice);
				if (stringTotalPrice != null) {
					stringTotalPrice.value = priceInfo;
				}
				return;

		} else if (errorMessage == "Minimum Lines Not Met" && minimumLinesError == true) {
				targetUrl = "javascript://";
				//javascriptFunction = "changeStep(this);";
				javascriptFunction = "doSubmit(" + '"changeCoverageArea"' + ',"");';
				//errorMessage = "Your ad text exceeds the maximum allowed lines for your selected package.  To keep your ad copy as is and upgrade to a different package,&nbsp;&nbsp; <a id='zones_step' href='" + targetUrl + "' onClick='"+javascriptFunction+"'>Click Here</a>";
				errorMessage = "Your ad text does not meet the minimum allowed lines for your selected package.  To keep your ad copy as is and upgrade to a different package,&nbsp;&nbsp; <span id='changeCoverageArea' style='color:black;cursor:pointer;' href='" + targetUrl + "' onClick='"+javascriptFunction+"'><u>Click Here</u></span>";
				//alert(errorMessage);
			    errorDiv.innerHTML='<p class="error" style="margin-top:10px;text-align:left;">' + errorMessage + '</p>';
			  	previewDiv.innerHTML=previewInfo;
				priceInfo="";
				priceDiv.innerHTML=priceInfo;
				if (priceDiv2 != null) {
					priceDiv2.innerHTML=priceInfo;	
				}
				//alert(stringTotalPrice);
				if (stringTotalPrice != null) {
					stringTotalPrice.value = priceInfo;
				}
				return;
		} else if (errorMessage != '') {
			    errorDiv.innerHTML='<p class="error" style="margin-top:10px;text-align:left;">' + errorMessage + '</p>';
			  	previewDiv.innerHTML=previewInfo;
				priceInfo="";
				priceDiv.innerHTML=priceInfo;
				if (priceDiv2 != null) {
					priceDiv2.innerHTML=priceInfo;	
				}
				//alert(stringTotalPrice);
				if (stringTotalPrice != null) {
					stringTotalPrice.value = priceInfo;
				}
				return;
		} else {
			priceInfo = '';
		    errorDiv.innerHTML='';
		}
	} else {
	    errorDiv.innerHTML='';
	}
	//alert(previewInfo);
	
	line_count.value = lineCount;
	word_count.value = wordCount;
	
	priceDiv.innerHTML=priceInfo;
	//alert(priceDiv2);	
	if (priceDiv2 != null) {
		priceDiv2.innerHTML=priceInfo;	
	}
	//alert(stringTotalPrice);
	if (stringTotalPrice != null) {
		stringTotalPrice.value = priceInfo;
	}
  	previewDiv.innerHTML=previewInfo;
    document.continueButton.src=imagesDirectory + "/next_button.gif";
    document.continueButton.style.cursor="pointer";
 } else {
 	//alert('Dynamic Preview Failed');
  	//alert(xmlreply.responseText);
  }
  
} catch(e) { 
 	//alert('Dynamic Preview Failed');
}
  
}

function getPrice(url) {
	//alert(url);
//	Http2.Init()
//	Http2.get({
//		url: url,
//		callback: setPrice,
//		cache: Http2.Cache.GetNoCache
//	});
	
	Http3._get.abort();
	var urlSplit = url.split("?");
	var url = urlSplit[0];
	//alert(url);
	var params = urlSplit[1];
	//alert(params);
 	Http3.post({
		url: url,
		params: params,
		callback: setPrice,
		cache: Http.Cache.GetNoCache
	});
	
}

function setPrice(xmlreply) {
  if (xmlreply.status == Http.Status.OK){
    var rpresponse = xmlreply.responseText;
	rpresponse = rpresponse.replace( /\n/g, "" );
	rpresponse = rpresponse.replace( /\r/g, "" );
	//alert(rpresponse);
    var priceDiv = document.getElementById("price_div");
    var priceDiv2 = document.getElementById("price_div2");
    var errorDiv = document.getElementById("errorDiv");
    var vpe2iframe = document.getElementById("vpe2mini");
    var stringTotalPrice = document.placead.string_total_ad_price;
	var priceInfo = rpresponse;
	//alert('priceInfo='+priceInfo);
	
	
	priceDiv.innerHTML=priceInfo;	
	if (priceDiv2 != null) {
		priceDiv2.innerHTML=priceInfo;	
	}
	//alert('stringTotalPrice'+stringTotalPrice);
	if (stringTotalPrice != null) {
		stringTotalPrice.value = priceInfo;
	}
    if (errorDiv.innerHTML == '') {
    	if (vpe2iframe != null && typeof(vpe2iframe) != 'undefined') {
    		//alert('vpe2');
		} else if (document.continueButton != null && typeof(document.continueButton) != 'undefined') {
	    	document.continueButton.src=imagesDirectory + "/next_button.gif";
	    	document.continueButton.style.cursor="pointer";
    	}
    }
    //alert('price set?');
  } else {
  	//alert(xmlreply.responseText);
  }
}

function getStates(country) {
	var idx = country.selectedIndex;
    var val = country[idx].value;
	//alert(val);
 	Http.get({
		url: "states.cmp?bfcid=" + sessionId + "&i=" + val,
		callback: setStates,
		cache: Http.Cache.GetNoCache
	});
}

function setStates(xmlreply) {
  if (xmlreply.status == Http.Status.OK){
	var state = document.getElementById("state");
    var stateresponse = xmlreply.responseText;
	//alert(stateresponse);
    var statear = stateresponse.split("|");
    state.length = 0;
    state.length = statear.length;
    for (o=0; o < statear.length; o++){
      var itemar = statear[o].split('!');
			state[o].value= itemar[0];
			state[o].text = itemar[1];						
    }
  }  
}

function getSearchKeywords(_adText, _categoryId, _ratePackageId)
{
	//alert('ratePackageId=' + ratePackageId);
	ratePackageId = _ratePackageId;
	categoryId = _categoryId;
	adText = _adText;
	var URL = "search_keywords2.cmp?bfcid=" + sessionId + "&action=get_word_prices&rate_packages_id=" + ratePackageId + "&categories_id=" + categoryId + "&ad_text=" + escape(adText);
	//alert(URL);
 	Http.get({
		url: URL,
		callback: setWordPrices,
		cache: Http.Cache.GetNoCache
	});

}

function getSearchKeywordsPrices(_adText, _categoryId, _ratePackageId)
{
	//alert('ratePackageId=' + ratePackageId);
	ratePackageId = _ratePackageId;
	categoryId = _categoryId;
	adText = _adText;
	var URL = "search_keywords2.cmp?bfcid=" + sessionId + "&action=get_word_prices&rate_packages_id=" + ratePackageId + "&categories_id=" + categoryId + "&ad_text=" + escape(adText);
	//alert(URL);
 	Http.get({
		url: URL,
		callback: setWordPrices2,
		cache: Http.Cache.GetNoCache
	});

}


function setWordPrices2(xmlreply)
{

    var numCol = 2;
    
	//alert('response=' + xmlreply.status);
//	alert('OK=' + Http.Status.OK);
  
  if (xmlreply.status == Http.Status.OK){
    var searchKeywordsDiv = document.getElementById("search_keywords_div");
    var wpresponse = xmlreply.responseText;
	//alert("wpresponse2=" + wpresponse);
    var wpar = wpresponse.split("|");
    searchKeywordPrices = {};
    skhtml = '';
    columns = 0;
    for (o=0; o < wpar.length; o++){
      var wordar = wpar[o].split('=');
	  word = wordar[0];
	  price = wordar[1];	
	  if (typeof(word) != 'undefined' && typeof(price) != 'undefined') {					
		  //alert(word + "=" + price);
		  searchKeywordPrices[word] = price;
		  
		    if (o == 0) { // First Word
				skhtml += '<table class="box-content" border="0" width="100%" cellspacing="0" cellpadding="0">';
			    skhtml += '<tr>';
		    }
		  
		  
			skhtml += '<td>';
			skhtml += '<table class="box-content" border="0" width="100%" cellspacing="0" cellpadding="0">';
			skhtml += '<tr>';
			skhtml += '<td><input ';
			selectedSponsoredKeyword = document.getElementById("document.placead.sponsored_keyword_" + word);
			if (selectedSponsoredKeyword == null || typeof(selectedSponsoredKeyword) == 'undefined') {
				  // Create word form input elements
				  selectedSponsoredKeyword = document.createElement("input");
				  selectedSponsoredKeyword.id = "document.placead.sponsored_keyword_" + word;
				  selectedSponsoredKeyword.name = "document.placead.sponsored_keyword_" + word;
				  selectedSponsoredKeyword.value = "";
				  selectedSponsoredKeyword.type = "hidden";
				  document.placead.appendChild(selectedSponsoredKeyword);
			} else {
				if (selectedSponsoredKeyword.value == "") {
				} else {
					skhtml += ' checked ';
				}
			}
			
			skhtml += ' onClick="processSearchKeyword(' + "'" + word + "'" + ');" name="search_keyword_' + word + '" type=checkbox>&nbsp;' + word + '</td>';
			skhtml += '<td width=100 align="left"><div id="search_keyword_' + word + '_div">&nbsp;</div></td>';
			skhtml += '</tr>';
			skhtml += '</table>';
			
			columns++;
			if (columns < numCol) {
				skhtml += '</td>';
			} else {
				skhtml += '</td>';
				skhtml += '</tr><tr>';
				columns = 0;
			}
		  
		
		
	  }
	  
    }
    if (skhtml != '') {
	    skhtml += '</tr>';
		skhtml += '</table>';
		if (searchKeywordsDiv != null && typeof(searchKeywordsDiv) != 'undefined') {
	    	searchKeywordsDiv.innerHTML=skhtml;
	    }
    }
  } else {
//  	alert('bad return'); 
//  	alert(xmlreply.responseText); 
  }  
}

function getSearchKeywords2(_adText, _categoryId, _ratePackageId) {
	ratePackageId = _ratePackageId;
	categoryId = _categoryId;
	adText = _adText;
	Http.Init()
 	Http.get({
		url: "search_keywords2.cmp?bfcid=" + sessionId + "&action=get_html&rate_packages_id=" + ratePackageId + "&categories_id=" + categoryId + "&ad_text=" + escape(adText),
		callback: setSearchKeywords,
		cache: Http.Cache.GetNoCache
	});
}  



function updatePropertyListRefreshPreview(parentPropertyId, childPropertyId) {
	var parentSelect = document.getElementById("placead_property_" + parentPropertyId);
	var parentKey = parentSelect.value;
	childProperty = childPropertyId;
	//alert('ParentKey = ' + parentKey + ' and Child = ' + childPropertyId);
	forceRefreshPreview = true;
	forceRefreshKeywords = false;
 	Http.get({
		url: "property_options.cmp?bfcid=" + sessionId + "&i=" + childPropertyId + "&k=" + parentKey,
		callback: setPropertyListValues,
		cache: Http.Cache.GetNoCache
	});
}
function updatePropertyList(parentPropertyId, childPropertyId) {
	var parentSelect = document.getElementById("placead_property_" + parentPropertyId);
	var parentKey = parentSelect.value;
	childProperty = childPropertyId;
	//alert('ParentKey = ' + parentKey + ' and Child = ' + childPropertyId);
	forceRefreshPreview = false;
	forceRefreshKeywords = false;
 	Http.get({
		url: "property_options.cmp?bfcid=" + sessionId + "&i=" + childPropertyId + "&k=" + parentKey,
		callback: setPropertyListValues,
		cache: Http.Cache.GetNoCache
	});
	
}

function updatePropertyListRefreshKeywords(parentPropertyId, childPropertyId) {
	var parentSelect = document.getElementById("placead_property_" + parentPropertyId);
	var parentKey = parentSelect.value;
	childProperty = childPropertyId;
	//alert('ParentKey = ' + parentKey + ' and Child = ' + childPropertyId);
	forceRefreshPreview = false;
	forceRefreshKeywords = true;
 	Http.get({
		url: "property_options.cmp?bfcid=" + sessionId + "&i=" + childPropertyId + "&k=" + parentKey,
		callback: setPropertyListValues,
		cache: Http.Cache.GetNoCache
	});
	
}

function setPropertyListValues(xmlreply) {
try {

  if (xmlreply.status == Http.Status.OK){
	var childSelect = document.getElementById("placead_property_" + childProperty);
    var response = xmlreply.responseText;
	//alert(response);
    var valueArray = response.split("|");
    childSelect.length = 0;
    childSelect.length = valueArray.length;
    for (o=0; o < valueArray.length; o++){
      var itemar = valueArray[o].split('!');
			childSelect[o].value= itemar[0];
			childSelect[o].text = itemar[1];						
    }
  }  
  if (forceRefreshPreview) {
  	refreshPreview();
  }
  if (forceRefreshKeywords) {
	  updateSearchWords(getTextForSearchKeywords());
  }
} catch(e) { 
 	//alert('');
}
}

function updateSearchPropertyList(parentPropertyId, childPropertyId) {
	var parentSelect = document.getElementById("search_property_" + parentPropertyId);
	var parentKey = parentSelect.value;
	childProperty = childPropertyId;
	//alert('ParentKey = ' + parentKey + ' and Child = ' + childPropertyId);
	forceRefreshPreview = false;
 	Http.get({
		url: "property_options.cmp?bfcid=" + sessionId + "&i=" + childPropertyId + "&k=" + parentKey,
		callback: setSearchPropertyListValues,
		cache: Http.Cache.GetNoCache
	});
	
}

function setSearchPropertyListValues(xmlreply) {
  if (xmlreply.status == Http.Status.OK){
	var childSelect = document.getElementById("search_property_" + childProperty);
    var response = xmlreply.responseText;
	//alert(response);
    var valueArray = response.split("|");
    childSelect.length = 0;
    childSelect.length = (valueArray.length+1);
	childSelect[0].value= '';
	childSelect[0].text = 'All';	
    for (o=0; o < valueArray.length; o++){
      var itemar = valueArray[o].split('!');
	  childSelect[(o+1)].value= itemar[0];
	  childSelect[(o+1)].text = itemar[1];						
    }
  }  
  //if (forceRefreshPreview) {
  //	refreshPreview();
  //}
}

function showProperties(NewOrEdit) {
	//var parentSelect = document.getElementById("placead_property_sets_id");
	var parentSelect = null;
	var inputType = null;
	var inputHeight = null;
	var inputWidth = null;
	var childSelect = null;
	if (NewOrEdit == 'new') {
		parentSelect = document.getElementById("placead_property_sets_id_new");
		inputType = document.getElementById('ste_input_type_new');
		inputHeight = document.getElementById('ste_input_height_new');
		inputWidth = document.getElementById('ste_input_width_new');
		childSelect = document.getElementById('placead_properties_id_new');
		selectOptions = document.getElementById('ste_select_options_text_new');
	} else if (NewOrEdit == 'edit') {
		parentSelect = document.getElementById("placead_property_sets_id_edit");
		inputType = document.getElementById('ste_input_type_edit');
		inputHeight = document.getElementById('ste_input_height_edit');
		inputWidth = document.getElementById('ste_input_width_edit');
		childSelect = document.getElementById('placead_properties_id_edit');
		selectOptions = document.getElementById('ste_select_options_text_edit');
	} else {
		inputType = null;
		inputHeight = null;
		inputWidth = null;
		childSelect = null;
	}
	childProperty = childSelect;

	var parentKey = parentSelect.value;
	if (parentKey != '') {
		inputType.disabled = true;
		inputHeight.disabled = true;
		inputWidth.disabled = true;
		if (selectOptions != null) {
			selectOptions.disabled = true;
		}
	 	Http.get({
			url: "show_properties.cmp?bfcid=" + sessionId + "&i=" + parentKey,
			callback: setPropertiesValues,
			cache: Http.Cache.GetNoCache
		});
	} else {
		inputType.disabled = false;
		inputHeight.disabled = false;
		inputWidth.disabled = false;
		childSelect.length = 0;
		if (selectOptions != null) {
			selectOptions.disabled = false;
		}
	}
	
}

function setPropertiesValues(xmlreply) {
  if (xmlreply.status == Http.Status.OK){
	//var childSelect = document.getElementById("placead_properties_id_new");
	var childSelect = childProperty;;
    var response = xmlreply.responseText;
	//alert(response);
    var valueArray = response.split("|");
    childSelect.length = 0;
    childSelect.length = valueArray.length;
    for (o=0; o < valueArray.length; o++){
      var itemar = valueArray[o].split('!');
			childSelect[o].value= itemar[0];
			childSelect[o].text = itemar[1];						
    }
  }  
}

function updateSearchPropertyDiv(categoryElementName, searchPage, bfcid) {
	//alert(bfcid);
	var categoryElement = document.getElementById(categoryElementName);
	var categoryId = categoryElement.value;
	if (categoryId == '') {
		var searchPropertiesDiv = document.getElementById("search_properties_div");
		searchPropertiesDiv.innerHTML='&nbsp;';
		return;
	} else {
		if (bfcid != '') {
		 	Http.get({
				url: "set_search_properties.cmp?bfcid=" + sessionId + "&cat=" + categoryId + "&page=" + searchPage,
				callback: setSearchPropertyDiv,
				cache: Http.Cache.GetNoCache
			});
		} else {
		 	Http.get({
				url: "set_search_properties.cmp?bfcid=" + sessionId + "&cat=" + categoryId + "&page=" + searchPage,
				callback: setSearchPropertyDiv,
				cache: Http.Cache.GetNoCache
			});
		}
	}
	
}

function setSearchPropertyDiv(xmlreply) {
  if (xmlreply.status == Http.Status.OK){
	var searchPropertiesDiv = document.getElementById("search_properties_div");
	//alert(searchPropertiesDiv.innerHTML);
    var response = xmlreply.responseText;
	//alert(response);
	searchPropertiesDiv.innerHTML=response;
  }  
}

function updateCustomerSearchDiv(action) {
	//alert(bfcid);
	var nameValue = "";
	var emailValue = "";
	var phoneValue = "";
	var nameElement = document.getElementById('search_name');
	if (nameElement != null) nameValue = nameElement.value;
	var emailElement = document.getElementById('search_email');
	if (emailElement != null) emailValue = emailElement.value;
	var phoneElement = document.getElementById('search_phone');
	if (phoneElement != null) phoneValue = phoneElement.value;
	var requestURL = "";
	if (action == 'search') {
		requestURL = "search_customers.cmp?bfcid=" + sessionId + "&name=" + nameValue + "&email=" + emailValue + "&phone=" + phoneValue; 
	} else if (action == 'create') {
		requestURL = "account_fields.php?bfcid=" + sessionId + "&create_advertiser=yes";
	}
	//alert(requestURL);
	Http.get({
			url: requestURL,
			callback: setCustomerSearchDiv,
			cache: Http.Cache.GetNoCache
	});
	
}

function setCustomerSearchDiv(xmlreply) {
  if (xmlreply.status == Http.Status.OK){
	var customerSearchDiv = document.getElementById("customer_search_div");
    var response = xmlreply.responseText;
	//alert(response);
	customerSearchDiv.innerHTML=response;
  }  
}

function setPhoneNumberField(customers_telephone) {
//	alert(customers_telephone);
	var countryElement = document.getElementById('country');
	var phoneNumberDiv = document.getElementById('phone_number_div');
	var areaCodeValue = '';
	var phonePrefixValue = '';
	var phoneSuffixValue = '';
	var extensionValue = '';
	phoneNumberFieldHTML = '';
	if (countryElement.value == '222') {
		//phoneNumberFieldHTML = "UK PHONE";
		if (customers_telephone != '') {
			phonePrefixValue = customers_telephone.substring(0,5);
			phoneSuffixValue = customers_telephone.substring(6,7);
			extensionValue = customers_telephone.substring(12);
		}
    	phoneNumberFieldHTML += "<input name='phonePrefix' type='text' class='textbox-required' size='5' maxlength='5' value='" + phonePrefixValue + "' />"; 
    	phoneNumberFieldHTML += "-"; 
    	phoneNumberFieldHTML += "<input name='phoneSuffix' type='text' class='textbox-required' size='7' maxlength='7' value='" + phoneSuffixValue + "'/>"; 
    	phoneNumberFieldHTML += "ext."; 
    	phoneNumberFieldHTML += "<input name='extension' type='text' class='textbox' id='extension' size='5' maxlength='5' value='" + extensionValue + "' />";
	} else {
		if (customers_telephone != '') {
			areaCodeValue = customers_telephone.substring(0,3);
			phonePrefixValue = customers_telephone.substring(4,3);
			phoneSuffixValue = customers_telephone.substring(8,4);
			extensionValue = customers_telephone.substring(12);
		}
		phoneNumberFieldHTML = "(";
        phoneNumberFieldHTML += "<input name='areaCode' type='text' class='textbox-required' size='3' maxlength='3' value='" + areaCodeValue  + "'/>";
    	phoneNumberFieldHTML += ")";
    	phoneNumberFieldHTML += "<input name='phonePrefix' type='text' class='textbox-required' size='3' maxlength='3' value='" + phonePrefixValue + "' />"; 
    	phoneNumberFieldHTML += "-"; 
    	phoneNumberFieldHTML += "<input name='phoneSuffix' type='text' class='textbox-required' size='4' maxlength='4' value='" + phoneSuffixValue + "'/>"; 
    	phoneNumberFieldHTML += "ext."; 
    	phoneNumberFieldHTML += "<input name='extension' type='text' class='textbox' id='extension' size='4' maxlength='4' value='" + extensionValue + "' />";
	}
	phoneNumberDiv.innerHTML = phoneNumberFieldHTML;
	
}

function setSessionId(sess_, imagePath_) {
	sessionId = sess_;
        if (imagePath_ == '') {
             imagePath_ = 'images/';
        }
	imagesDirectory = imagePath_;
}

function setWordPrices(xmlreply)
{
	//alert('response=' + xmlreply.status);
//	alert('OK=' + Http.Status.OK);
  
  if (xmlreply.status == Http.Status.OK){
    var wpresponse = xmlreply.responseText;
	alert("wpresponse2=" + wpresponse);
    var wpar = wpresponse.split("|");
    searchKeywordPrices = {};
    for (o=0; o < wpar.length; o++){
      var wordar = wpar[o].split('=');
	  word = wordar[0];
	  price = wordar[1];	
	  if (typeof(word) != 'undefined') {					
		  //alert(word + "=" + price);
		  searchKeywordPrices[word] = price;
		  
		  // Create word form input elements
		  selectedSponsoredKeyword = document.createElement("input");
		  selectedSponsoredKeyword.id = "document.placead.sponsored_keyword_" + word;
		  selectedSponsoredKeyword.name = "document.placead.sponsored_keyword_" + word;
		  selectedSponsoredKeyword.value = "";
		  selectedSponsoredKeyword.type = "hidden";
		  document.placead.appendChild(selectedSponsoredKeyword);
	  }
	  
    }
 	Http.get({
		url: "search_keywords2.cmp?bfcid=" + sessionId + "&action=get_html&rate_packages_id=" + ratePackageId + "&categories_id=" + categoryId + "&ad_text=" + escape(adText),
		callback: setSearchKeywords,
		cache: Http.Cache.GetNoCache
	});
  

  } else {
  	alert('bad return'); 
  	alert(xmlreply.responseText); 
  }  
}

function changeInventory()
{
	var adInventoryId = placead.placead_retail_inventory_id;
//	var adInventoryId = document.getElementById("placead_retail_inventory_id");
	var adInventory = document.getElementById("retail_ad_inventory");
	
	if (adInventoryId != null && adInventoryId.value > 0) {
		var thisurl = "show_ad_inventory.cmp?bfcid=" + sessionId ;
		thisurl = thisurl + "&placead_retail_inventory_id=" + adInventoryId.value;
	 	Http.get({
			url: thisurl,
			callback: setRetailAdInventory,
			cache: Http.Cache.GetNoCache
		});
	} else {
		var pubs = document.getElementById("publications");
		var sects = document.getElementById("sections");
		var adtypes = document.getElementById("ad_types");
		var sortBy = document.getElementById("sort_by");
		var startDate = document.getElementById("start_date");
		var endDate = document.getElementById("end_date");
		var firstAvailableDate = document.getElementById("first_available_date");
		var showReserved = document.getElementById("show_reserved_ads");
		
		adInventory.innerHTML = "<img src='images/loading2.gif'>Searching Ad Space Inventory...";
	
		if (showReserved.checked) {
			var showReservedAds = 'yes';
		} else {
			var showReservedAds = '';
		}
	
	
		//alert (startDate.value);
		if (firstAvailableDate.checked) {
			var databaseStartDate = "";
			var databaseEndDate = "";
			var firstDateChecked = "1";
		} else {
			var databaseStartDate = startDate.value.substring(6) + startDate.value.substring(0,2) + startDate.value.substring(3,5);
			var databaseEndDate = endDate.value.substring(6) + endDate.value.substring(0,2) + endDate.value.substring(3,5);
			var firstDateChecked = "0";
		}
		
		//alert(databaseStartDate);
	
		//alert(pubs.length);
		var length = pubs.length;
		var selectedPubs = "";	
		for (var i=length;i>=0;i--) {
		  if (pubs.options[i] != null && pubs.options[i].selected == true && pubs.options[i].value > 0) {
		  	if (selectedPubs == "") {
			  	selectedPubs += pubs.options[i].value;
		  	} else {
			  	selectedPubs += "," + pubs.options[i].value;
		  	}
		  }
		}
		
		//alert(sects.length);
		var length = sects.length;
		var selectedSections = "";	
		for (var i=length;i>=0;i--) {
		  if (sects.options[i] != null && sects.options[i].selected == true && sects.options[i].value > 0) {
		  	if (selectedSections == "") {
			  	selectedSections += sects.options[i].value;
		  	} else {
			  	selectedSections += "," + sects.options[i].value;
		  	}
		  }
		}
		//alert(selectedSections);
		
		//alert(sects.length);
		var length = adtypes.length;
		var selectedAdTypes = "";	
		for (var i=length;i>=0;i--) {
		  if (adtypes.options[i] != null && adtypes.options[i].selected == true && adtypes.options[i].value > 0) {
		  	if (selectedAdTypes == "") {
			  	selectedAdTypes += adtypes.options[i].value;
		  	} else {
			  	selectedAdTypes += "," + adtypes.options[i].value;
		  	}
		  }
		}
		
		//alert(selectedPubs);
		var thisurl = "show_ad_inventory.cmp?bfcid=" + sessionId ;
		if (selectedPubs != "") {
			thisurl = thisurl + "&pubs=" + selectedPubs;
		}
		if (selectedSections != "") {
			thisurl = thisurl + "&sects=" + selectedSections; 
		}
		if (selectedAdTypes != "") {
			thisurl = thisurl + "&adtypes=" + selectedAdTypes;
		}
		if (sortBy != null && sortBy.value != "") {
			thisurl = thisurl + "&sort_by=" + sortBy.value;
		}
		if (databaseStartDate != "") {
			thisurl = thisurl + "&st=" + databaseStartDate;
		}
		if (databaseEndDate != "") {
			thisurl = thisurl + "&en=" + databaseEndDate;
		}
		if (firstDateChecked != "") {
			thisurl = thisurl + "&fad=" + firstDateChecked;
		}
		if (showReservedAds != "") {
			thisurl = thisurl + "&res=" + showReservedAds;
		}
	 	Http.get({
			url: thisurl,
			callback: setRetailAdInventory,
			cache: Http.Cache.GetNoCache
		});
	}


}

function setRetailAdInventory(xmlreply) {
  var adInventory = document.getElementById("retail_ad_inventory");
  //alert(adInventory);
  if (xmlreply.status == Http.Status.OK){
    var response = xmlreply.responseText;
    //alert(response);
    adInventory.innerHTML = response;
  }  
}

function resendEnhanceEmail(orderId,customerId) {
	//alert(bfcid);
	url = "set_resend_email.cmp?";
	url += "bfcid=" + sessionId + "&";
	url += "temp_orders_id=" + orderId + "&temp_customers_id=" + customerId;
 	Http.get({
		url: url,
		callback: resendEnhanceEmailDone,
		cache: Http.Cache.GetNoCache
	});
}

function resendEnhanceEmailDone(xmlreply) {
  if (xmlreply.status == Http.Status.OK){
    var response = xmlreply.responseText;
    //alert(response);
    if (response == 'ok') {
		alert("Enhance Your Ad Email Scheduled for Resend");
	} else {
		if (response == 'fail1') {
			alert("Unable to Resend Email: Product Id Not Found");
		} else if (response == 'fail2') {
			alert("Unable to Resend Email: No Email Address for Customer");
		} else {
			alert("Unable to Resend Email: Reason Unknown");
		}
	}
  } else {
	alert("Unable to Resend Email");
  }
}
  
function resendEmail(orderId,customerId,emailType) {
	//alert(bfcid);
	url = "set_resend_email.cmp?";
	url += "bfcid=" + sessionId + "&";
	url += "temp_orders_id=" + orderId + "&temp_customers_id=" + customerId;
	url += "&email_type=" + emailType;
 	Http.get({
		url: url,
		callback: resendEmailDone,
		cache: Http.Cache.GetNoCache
	});
}

function resendEmailDone(xmlreply) {
  if (xmlreply.status == Http.Status.OK){
    var response = xmlreply.responseText;
    //alert(response);
    if (response == 'ok') {
		alert("Email Scheduled for Resend");
	} else {
		if (response == 'fail1') {
			alert("Unable to Resend Email: Product Id Not Found");
		} else if (response == 'fail2') {
			alert("Unable to Resend Email: No Email Address for Customer");
		} else {
			alert("Unable to Resend Email: Reason Unknown");
		}
	}
  } else {
	alert("Unable to Resend Email");
  }
}

function setSearchKeywords(xmlreply)
{
  var searchKeywordsDiv = document.getElementById("search_keywords_div");
//  alert (searchKeywordsDiv);
  //alert (searchKeywordsDiv.innerHTML);
  if (xmlreply.status == Http.Status.OK){
    var skresponse = xmlreply.responseText;
	if (typeof(searchKeywordsDiv) == 'undefined' || searchKeywordsDiv == null) {
		//alert('no search keywords div');
	} else {
		//alert('skresponse=' + skresponse);
		searchKeywordsDiv.innerHTML=skresponse;
	}
	//alert('done with set keywords');
  }  
}

function setWordPrices(xmlreply)
{
	//alert('response=' + xmlreply.status);
//	alert('OK=' + Http.Status.OK);
  
  if (xmlreply.status == Http.Status.OK){
    var wpresponse = xmlreply.responseText;
	alert("wpresponse2=" + wpresponse);
    var wpar = wpresponse.split("|");
    searchKeywordPrices = {};
    for (o=0; o < wpar.length; o++){
      var wordar = wpar[o].split('=');
	  word = wordar[0];
	  price = wordar[1];	
	  if (typeof(word) != 'undefined') {					
		  //alert(word + "=" + price);
		  searchKeywordPrices[word] = price;
		  
		  // Create word form input elements
		  selectedSponsoredKeyword = document.createElement("input");
		  selectedSponsoredKeyword.id = "document.placead.sponsored_keyword_" + word;
		  selectedSponsoredKeyword.name = "document.placead.sponsored_keyword_" + word;
		  selectedSponsoredKeyword.value = "";
		  selectedSponsoredKeyword.type = "hidden";
		  document.placead.appendChild(selectedSponsoredKeyword);
	  }
	  
    }
 	Http.get({
		url: "search_keywords2.cmp?bfcid=" + sessionId + "&action=get_html&rate_packages_id=" + ratePackageId + "&categories_id=" + categoryId + "&ad_text=" + escape(adText),
		callback: setSearchKeywords,
		cache: Http.Cache.GetNoCache
	});
  

  } else {
  	alert('bad return'); 
  	alert(xmlreply.responseText); 
  }  
}

function updateUsersResolution(usersRes) {
//	alert(sessionId );
//	alert(usersRes);
	url = "/set_resolution.php?";
	url += "bfcid=" + sessionId + "&";
	url += "users_res=" + usersRes;
	//alert('getting '+url);
 	Http.get({
		url: url,
		callback: updateFinished,
		cache: Http.Cache.GetNoCache
	});
}

function updateFinished(xmlreply) {
  if (xmlreply.status == Http.Status.OK){
	   //alert('got ' +  xmlreply.responseText);
  } else {
  	//alert('some error');
  }
}

function processBooleanPrintUpsellWithText(unitType, numUnits, upsellPrice,elementAssemblyOrder,adText) {
	var templateElement = document.getElementById("template_element_"+elementAssemblyOrder);
//	alert(templateElement);
	var checkBox = document.getElementById("special_charge_" + unitType + "_value");
	if (checkBox.checked) {
		templateElement.value = adText;
	} else {
		templateElement.value = '';
	}
//	alert(templateElement.value);
	processBooleanPrintUpsell(unitType, numUnits, upsellPrice);
}

function processBooleanPrintUpsellWithNewPackage(unitType, numUnits, upsellPrice,newPackageId,oldPackageId) {
	var checkBox = document.getElementById("special_charge_" + unitType + "_value");
	var ratePackagesId = document.getElementById("rate_packages_id");
	var lastRatePackagesId = document.getElementById("last_rate_packages_id");
	var calSelectedPrintDates = document.getElementById("calSelectedPrintDates");
	var calSelectedOnlineDates = document.getElementById("calSelectedOnlineDates");
//	alert('New = ' + newPackageId);
//	alert('Old = ' + oldPackageId);
	if (newPackageId != oldPackageId) {
		lastRatePackagesId.value = oldPackageId;
	}
	if (checkBox.checked) {
//		alert(newPackageId);
		ratePackagesId.value=newPackageId;
		calSelectedPrintDates.value = '';
		calSelectedOnlineDates.value = '';
	} else {
//		alert("setting to " + lastRatePackagesId.value);
		ratePackagesId.value=lastRatePackagesId.value;
		calSelectedPrintDates.value = '';
		calSelectedOnlineDates.value = '';
	}
	processBooleanPrintUpsell(unitType, numUnits, upsellPrice);
}
function processBooleanPrintUpsell(unitType, numUnits, upsellPrice) {
//	alert(unitType);
//	alert(numUnits);
	
	var checkBox = document.getElementById("special_charge_" + unitType + "_value");
	var checkBoxDiv = document.getElementById("special_charge_" + unitType + "_div");
//	specialChargeInput = document.getElementById("document.placead.special_charge_" + word);
//	if (selectedSponsoredKeyword == null || typeof(selectedSponsoredKeyword) == 'undefined') {
//		  // Create word form input elements
//		  selectedSponsoredKeyword = document.createElement("input");
//		  selectedSponsoredKeyword.id = "document.placead.sponsored_keyword_" + word;
//		  selectedSponsoredKeyword.name = "document.placead.sponsored_keyword_" + word;
//		  selectedSponsoredKeyword.value = "";
//		  selectedSponsoredKeyword.type = "hidden";
//		  document.placead.appendChild(selectedSponsoredKeyword);
//	}
	
	
	//alert(checkBoxDiv.innerHTML);
	if (checkBox.checked) {
		checkBoxDiv.innerHTML = "&nbsp;";
		checkBox.value = numUnits;
		//alert(checkBox.value);
	} else {
		if (upsellPrice > 0) {
			checkBoxDiv.innerHTML = "(+ $" + upsellPrice + ")";
		} else {
			checkBoxDiv.innerHTML = "";
		}
		checkBox.value = 0;
		//alert(checkBox.value);
	}
	refreshPreview();
}

function disableNextButton() {
	var continueButton = document.getElementById("continueButton");
	//alert(continueButton);
	if (continueButton != null) {
		//alert(imagesDirectory + "/next_button-disabled.gif");
	    continueButton.src=imagesDirectory + "/next_button-disabled.gif";
    	continueButton.style.cursor="default";
	}
}

function hideNextButton() {
	var continueButton = document.getElementById("continueButton");
	//alert(continueButton);
	if (continueButton != null) {
		//alert(imagesDirectory + "/next_button-hidden.gif");
	    continueButton.src=imagesDirectory + "/next_button-hidden.gif";
    	continueButton.style.cursor="default";
	}
}

function enableNextButton() {
	var continueButton = parent.document.getElementById("continueButton");
	//alert(continueButton);
	if (continueButton != null) {
	    continueButton.src=imagesDirectory + "/next_button.gif";
    	continueButton.style.cursor="pointer";
    }
}

