
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 fill2(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 + 1;
    //catelmt.length = catar.length;
	catelmt[0].value= "0";
	catelmt[0].text = "--- Select your Category ---";						
    //for (o=1; o < catar.length; o++){
    for (o=0; o < catar.length; o++){
      var itemar = catar[o].split('!');
			catelmt[o+1].value= itemar[0];
			catelmt[o+1].text = itemar[1];						
    }
  } else {
//    if (navigator.appName == 'Netscape') {
//    	  alert(xmlreply.status);
//      }
  }
}


function handledd2(dd1)
{
  var idx = dd1.selectedIndex;
  var val = dd1[idx].text;
  var par = document.forms["placead"];
  var parelmts = par.elements;
//  alert("here");
  var catsel = parelmts["categories_id_other"];
//  alert(catsel);
//  alert(catsel.style.visibility);
  catsel.style.visibility = 'visible';
  var section = dd1[idx].value;
//  alert(sessionId);
 	Http.get({
		url: "categories2.cmp?bfcid=" + sessionId + "&i=" + section,
		callback: fill2,
		cache: Http.Cache.Get
	}, [catsel]);
  
}


function getLocalRatesPackages(localZoneSelection, categoryId, testRates, advertisersType)
{
  var ratepackages = document.getElementById("local_rate_packages_html");
  ratepackages.innerHTML="<br/><br/>...Loading Available Packages...";
  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 getBannerImagePreview(bannerHTML)
{
	
	//alert("bannerHTML = " + bannerHTML);
 	Http.get({
		url: "placead_banner_preview.cmp?bfcid=" + sessionId + "&banner_preview_text=" + escape(bannerHTML),
		callback: BannerImagePreview,
		cache: Http.Cache.Get
	});
  
}

function BannerImagePreview(xmlreply)
{
  var bannerPreview2 = document.getElementById("bannerPreview2");
  if (xmlreply.status == Http.Status.OK){
    var rpresponse = xmlreply.responseText;
    //alert(rpresponse);
    bannerPreview2.innerHTML=rpresponse;
    //bannerPreview2.innerHTML="<h1>HERE</h1>";
    
  }  
}


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");
    //alert("errorDiv="+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("|"));
	//alert("priceInfo="+priceInfo);
	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);
			    if (errorDiv != null) 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);
			    if (errorDiv != null) 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);
				if (errorDiv != null) 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 != '') {
			if (errorDiv != null) 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 = '';
			if (errorDiv != null) errorDiv.innerHTML='';
		}
	} else {
		if (errorDiv != null) errorDiv.innerHTML='';
	}
//	alert("previewInfo="+previewInfo);
	
	line_count.value = lineCount;
	word_count.value = wordCount;
	
	priceDiv.innerHTML=priceInfo;
//	alert("priceDiv2="+priceDiv2);	
	if (priceDiv2 != null) {
		priceDiv2.innerHTML=priceInfo;	
	}
//	alert("stringTotalPrice="+stringTotalPrice);
	if (stringTotalPrice != null) {
		stringTotalPrice.value = priceInfo;
	}
  	previewDiv.innerHTML=previewInfo;
  	if (document.continueButton != null) {
  		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("sponsored_keyword_" + word);
//			alert("selectedSponsoredKeyword="+selectedSponsoredKeyword);
			if (selectedSponsoredKeyword == null || typeof(selectedSponsoredKeyword) == 'undefined') {
				selectedSponsoredKeyword = document.getElementById("document.placead.sponsored_keyword_" + word);
//				alert("selectedSponsoredKeyword="+selectedSponsoredKeyword);
			}			
			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");
		if (searchPropertiesDiv != null) {
			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) {
function updateCustomerSearchDiv(action, searchOnly) {
	//alert(bfcid);
	var customerSearchDiv = document.getElementById("customer_search_results");
	if (customerSearchDiv != null) {
		customerSearchDiv.innerHTML='...Searching Customer Database...';
	}
	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; 
		requestURL = "search_customers.cmp?bfcid=" + sessionId + "&name=" + nameValue + "&email=" + emailValue + "&phone=" + phoneValue + "&search_only=" + searchOnly; 
	} 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_;
//alert(sessionId);
//	alert(window.name);
//	if (window.name == "") {
//		alert("New Tab/Window");
//		window.name = "new";
//		var location = window.location.href;
//		location.replace(/bfcid/,'xfcid');
//		if (location.indexOf("?") > 0) {
//			location = location + "&new_tab=1";
//		} else {
//			location = location + "?new_tab=1";
//		}
//		window.location.href=location;
//	} else if (window.name == "new") {
//		window.name = sessionId;
//	} else if (window.name == "preview") {
//	} else {
//	}

	if (imagePath_ == '') {
            imagePath_ = 'images/';
    }
	imagesDirectory = imagePath_;
	
}

function setCookie(c_name,value,expiredays)
{
	
	var expires_date = new Date(expiredays);
	
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+expires_date.toGMTString());
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

function deleteCookie( name ) {
if ( getCookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}	

function deleteCookie(c_name)
{
document.cookie=c_name+ "=" +escape("delete")+ ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function setCurrentTabName() {
//	alert("Unloading...");
//
//	alert("Window Name="+window.name);
//	deleteCookie("mocca_test_bfcid");
//	//alert("Session Id="+sessionId);
//	alert("Cookie="+getCookie("mocca_test_bfcid_expire"));
//	alert("Cookie="+getCookie("mocca_test_bfcid"));
//	setCookie("mocca_test_bfcid",window.name,getCookie("mocca_test_bfcid_expire"));
//	alert("Cookie="+getCookie("mocca_test_bfcid"));
//	flush();
}

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 += "tabid=" + window.name + "&";
	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";
    }
}

callWindow = null;

//function initializeOrderElement(win_) {
////	alert(sessionId);
//	callWindow = win_;
//	url = "initialize_order_element.cmp?";
//	url += "bfcid=" + sessionId;
//	alert(url);
// 	Http.get({
//		url: url,
//		async: true,
//		callback: initializeOrderElementDone,
//		cache: Http.Cache.GetNoCache
//	});
// 	alert("?");
//}

function initializeOrderElement(win_) {
//	alert(sessionId);
	callWindow = win_;
	url = "initialize_order_element.cmp?";
	url += "bfcid=" + sessionId;
//	alert("Initialize Order: " + url);
 	Http.get({
		url: url,
		async: true,
		callback: initializeOrderElementDone,
		cache: Http.Cache.GetNoCache
	});
}

function initializeOrderElementDone(xmlreply) {
//  alert("Back!! " + Http.Status.OK);
  if (xmlreply.status == Http.Status.OK){
    var response = xmlreply.responseText;
//    alert(response);
//    alert(callWindow);
	callWindow.name = "placead" + response;
//	alert(callWindow.name);
  }
}

function blockNewOrder(win_) {
	alert(sessionId);
	callWindow = win_;
//	url = "set_order_element.cmp?";
//	url += "bfcid=" + sessionId;
//	url += "&placead_order_elements_id=" + orderId;
//	alert(url);
// 	Http.get({
//		url: url,
//		async: true,
//		cache: Http.Cache.GetNoCache
//	});
//	callback: setOrderElementDone,
//	var location = callWindow.location.href;
////	alert(location);
//	location = location + '&reset=1&placead_order_elements_id='+orderId;
//	alert(location);
//	callWindow.location.href=location;
}


function setOrderElement(win_,orderId) {
	alert(sessionId);
	callWindow = win_;
//	url = "set_order_element.cmp?";
//	url += "bfcid=" + sessionId;
//	url += "&placead_order_elements_id=" + orderId;
//	alert(url);
// 	Http.get({
//		url: url,
//		async: true,
//		cache: Http.Cache.GetNoCache
//	});
//	callback: setOrderElementDone,
	var location = callWindow.location.href;
//	alert(location);
	location = location + '&reset=1&placead_order_elements_id='+orderId;
	alert(location);
	callWindow.location.href=location;
}

function setOrderElementDone(xmlreply) {
  alert(xmlreply.responseText);
  if (xmlreply.status == Http.Status.OK){
    var response = xmlreply.responseText;
//    alert(callWindow);
//	callWindow.name = "placead" + response;
//	alert(callWindow.name);
    alert("Reload");
//	var location = callWindow.location.href;
//	callWindow.location.href=location;
    //callWindow.history.go(0);
  }
}

function validateUsername(username) {
//	alert(username );
//	alert(usersRes);
	url = "/username.cmp?";
	url += "username=" + username;
	//alert('getting '+url);
 	Http.get({
		url: url,
		callback: updateValidateUsername,
		cache: Http.Cache.GetNoCache
	});
}

function updateValidateUsername(xmlreply) {
  var useridAvailable = document.getElementById("userid_available");
  var updateButton = document.getElementById("update_button");
  var username = document.getElementById("customers_userid");
  
  if (xmlreply.status == Http.Status.OK){
	   //alert('got ' +  xmlreply.responseText);
	   if (xmlreply.responseText == "OK") {
		   //alert("ok");
		   //userid_available
		   useridAvailable.innerHTML='<img src="images/check.gif">';
		   updateButton.disabled = false;
	   } else {
		   //alert("not ok");
		   useridAvailable.innerHTML='(Not Available)';
		   username.focus();
		   updateButton.disabled = true;
	   }
  } else {
  	//alert('some error');
  }
}

function validateUsername2() {
    var userid = document.getElementById("customers_userid");
	//alert(username );
    if (userid == null) {
    	document.account_edit.submit();
    	return;
    }
    var username = userid.value;
	url = "/username.cmp?";
	url += "username=" + username;
	//alert('getting '+url);
 	if (username == "") {
    	document.account_edit.submit();
    	return;
 	} else {
		Http.get({
			url: url,
			callback: updateValidateUsername2,
			cache: Http.Cache.GetNoCache
		});
 	}
}

function updateValidateUsername2(xmlreply) {
  var useridAvailable = document.getElementById("userid_available");
  var username = document.getElementById("customers_userid");
  
  if (xmlreply.status == Http.Status.OK){
	   //alert('got ' +  xmlreply.responseText);
	   if (xmlreply.responseText == "OK") {
		   //alert("ok");
		   //userid_available
		   useridAvailable.innerHTML='<img src="images/check.jpg">';
		   document.account_edit.submit();
	   } else {
		   //alert("not ok");
		   useridAvailable.innerHTML='(Not Available)';
		   username.focus();
	   }
  } else {
  	alert('some error');
  }
}

function hideEmailSavedSearches() {
	animatedcollapse.toggle('saved_search_box');

	url = "/email_saved_searches.cmp?hide=1";
	//alert('getting '+url);
 	Http.get({
		url: url,
		cache: Http.Cache.GetNoCache
	});
}

function showEmailSavedSearches() {
	animatedcollapse.toggle('saved_search_box');

	url = "/email_saved_searches.cmp?hide=0";
	//alert('getting '+url);
 	Http.get({
		url: url,
		cache: Http.Cache.GetNoCache
	});
}

function emailSavedSearches(customer,category,frequency,storefronts_id) {
	if (frequency > 0) {
		url = "/email_saved_searches.cmp?hide=0&customer="+customer+"&category="+category+"&frequency=" + frequency+"&storefronts_id=" + storefronts_id;
	} else {
		url = "/email_saved_searches.cmp?hide=1&customer="+customer+"&category="+category+"&frequency=" + frequency+"&storefronts_id=" + storefronts_id;
	}
	//alert('getting '+url);
 	Http.get({
		url: url,
		callback: updateESS,
		cache: Http.Cache.GetNoCache
	});
 	//alert("done with get");
}

function updateESS(xmlreply) {
     var savedSearchUpdate = document.getElementById("email_saved_searches_update");
	 //alert(xmlreply);
	 if (xmlreply.status == Http.Status.OK){
		   //alert('got ' +  xmlreply.responseText);
		   if (xmlreply.responseText == "OK") {
			   //email_saved_searches_update
			   savedSearchUpdate.innerHTML='<img src="images/check.jpg">';
		   } else {
			   savedSearchUpdate.innerHTML='';
			   animatedcollapse.toggle('saved_search_box');			   
		   }
	 } else {
	  	alert('ajax error');
	 }
}

var fbLogonUrl = '';
var fbLogoffUrl = '';
function deactivateFB(logoffUrl) {
    var customerid = document.getElementById("edit_customer_id");
//    alert(customerid.value);
//    alert(logoffUrl);
    fbLogoffUrl = logoffUrl;
    url = "/username.cmp?";
	url += "deactivate_facebook="+customerid.value;
//	alert('getting '+url);
 	Http.get({
		url: url,
		callback: deactivateFBCallback,		
		cache: Http.Cache.GetNoCache
	});
}
function deactivateFBCallback(xmlreply) {
	 if (xmlreply.status == Http.Status.OK){
		 ///alert(xmlreply.responseText);
		 if (fbLogoffUrl == '') {
			 //alert('no logoff url');
			 document.account_edit.submit();
		 } else {
		 	 //alert(fbLogoffUrl);
			 window.open(fbLogoffUrl,'_self');
		 }
	 } else {
		 //alert('ajax error');
	 }
}
function activateFB(logonUrl) {
    var customerid = document.getElementById("edit_customer_id");
//    alert(customerid.value);
//    alert(logoffUrl);
    fbLogonUrl = logonUrl;
    url = "/username.cmp?";
    if (customerid != null) {
    	url += "activate_facebook="+customerid.value;
    }
//	alert('getting '+url);
 	Http.get({
		url: url,
		callback: activateFBCallback,		
		cache: Http.Cache.GetNoCache
	});
}
function activateFBCallback(xmlreply) {
	 if (xmlreply.status == Http.Status.OK){
		 ///alert(xmlreply.responseText);
		 if (fbLogonUrl == '') {
			 //alert('no logon url');
			 document.account_edit.submit();
		 } else {
		 	 //alert(fbLogonUrl);
			 window.open(fbLogonUrl,'_self');
		 }
	 } else {
		 //alert('ajax error');
	 }
}

function manageProperties(propertiesId) {
	if (propertiesId == null || propertiesId == 0) {
		alert("property id required");
		return;
	}
 	Http.get({
		url: "manage_properties.cmp?bfcid=" + sessionId + "&i=" + propertiesId,
		callback: setManageProperties,
		cache: Http.Cache.GetNoCache
	});
}

function setManageProperties(xmlreply) {
  if (xmlreply.status == Http.Status.OK){
    var response = xmlreply.responseText;
//	alert(response);
    var valueArray = response.split("|");
    for (o=0; o < valueArray.length; o++){
      var itemar = valueArray[o].split('!');
			placead_properties_select_value_id = itemar[0];
			parent_property_key = itemar[1];						
			select_description = itemar[2];
			select_value = itemar[3];						
			display_order = itemar[4];	
    }
  }  
}

function checkChangeLocation(locationElement) {
    var rangeField = document.getElementById("my_range_field");
    var url = "/checklocation.cmp?";
    url += "bfcid=" + sessionId;
	url += "&loc="+escape(locationElement.value);
	url += "&rng="+escape(rangeField.value);
//	alert('getting '+url);
	
//	  var changeLocationStatusDiv = document.getElementById("changeLocationStatusDiv");
//	  changeLocationStatusDiv.innerHTML = ".................</center>";
	
 	Http.get({
		url: url,
		callback: checkChangeLocationCallback,		
		cache: Http.Cache.GetNoCache
	});
}

function checkChangeLocation2(postalCode) {
    var rangeField = document.getElementById("my_range_field");
    var url = "/checklocation.cmp?";
    url += "bfcid=" + sessionId;
	url += "&loc="+escape(postalCode);
	url += "&rng="+escape(rangeField.value);
//	alert('getting '+url);

	  var changeLocationStatusDiv = document.getElementById("changeLocationStatusDiv");
		changeLocationStatusDiv.innerHTML = "...Reloading Page with New Search Parameters...<br/>Please Wait";
	
 	Http.get({
		url: url,
		callback: checkChangeLocationCallback,		
		cache: Http.Cache.GetNoCache
	});
}

function checkChangeLocationCallback(xmlreply) {
	 if (xmlreply.status == Http.Status.OK){
	
	 
		    var response = xmlreply.responseText;
		 	//alert(response);
		    if (response.indexOf("Not Found") >= 0) {
			  var changeLocationButton = document.getElementById("check_my_location");
			  var changeLocationStatusDiv = document.getElementById("changeLocationStatusDiv");
			  changeLocationStatusDiv.innerHTML = "<center>Not Found</center>";
			  changeLocationButton.enabled = true;
		    } else if (response.indexOf("Multiple") >= 0) {
				  var changeLocationButton = document.getElementById("check_my_location");
				  var changeLocationStatusDiv = document.getElementById("changeLocationStatusDiv");
				  var changeLocationDiv = document.getElementById("changeLocationDiv");
				  changeLocationButton.enabled = true;
				  //changeLocationStatusDiv.innerHTML = "<center>Not Found</center>";
				  var resultLines = response.split("\n");
				  var resultText = '<strong><u>Multiple Postal Codes Found</u></strong><br/>';
				  //alert(resultLines.length);
				  for (var i=1;i<resultLines.length;i++) {
					  //alert(resultLines[i]);
					  var resultLine = resultLines[i];
					  if (resultLine != "") {
//						  alert(resultLine);
						  
//						  resultText += resultLine + "<br/>";
						  var resultElements = resultLine.split("|");
						  resultText += '<a href="javascript://" onClick="checkChangeLocation2('+"'" + resultElements[2] + "'" +');">';
						  resultText += resultElements[0] + "," + resultElements[1];
						  //resultText += '&nbsp;&nbsp;('+resultElements[2]+')'+'<br/>';
						  resultText += '</a><br/>';
//						  alert(changeLocationDiv.style.height );
						  var curHeight = changeLocationDiv.style.height;
						  curHeight = curHeight.replace("px","");
//						  alert(curHeight);
						  var curHeightInt = parseInt(curHeight);
//						  alert(curHeightInt);
						  changeLocationDiv.style.height  = curHeightInt + 18;
//						  alert(changeLocationDiv.style.height );
					  }
				  }
				  resultText += '<br/><strong>Please select from options listed above.<br/>';
				  changeLocationStatusDiv.innerHTML = resultText;
				  changeLocationButton.enabled = true;
		    
		    } else {
//		    	alert(response);
				  var changeLocationStatusDiv = document.getElementById("changeLocationStatusDiv");
			    var locationSpan = document.getElementById("my_location_span");
			    var rangeSpan = document.getElementById("my_range_span");
			    var locationField = document.getElementById("my_location_field");
			    var rangeField = document.getElementById("my_range_field");
//			    alert(rangeSpan);
//			    alert(locationSpan);
//			    alert(locationField);
//			    alert(rangeField);
			    
			    rangeSpan.innerHTML = rangeField.value;
			    locationSpan.innerHTML = response;
			    locationField.value = response;
			    var changeLocationDiv = document.getElementById("changeLocationDiv");
				//document.body.removeChild(changeLocationDiv);
				changeLocationStatusDiv.innerHTML = "...Reloading Page with New Search Parameters...<br/>Please Wait";
				//alert(location.href + "&bfcid=" + sessionId);
//				location.href = location.href + "&bfcid=" + sessionId;
//				alert(location.href);
				location.reload(true);
//				location.reload(true);
//				location.assign(location.href + "&bfcid=" + sessionId);
				
		    }
	 } else {
		 //alert('ajax error');
	 }
}

function closeSearchSuggestions() {
	  var keyword_suggestionsDiv = document.getElementById("keyword_suggestions");
	  keyword_suggestionsDiv.innerHTML = '';
	  //	  document.body.removeChild(keyword_suggestionsDiv);
	
}


function selectKeywords(phrase) {
	
//	  alert(phrase);
//	  alert(phrase.innerText);
//	  alert(phrase.innerHTML);
	  var phraseText = phrase.innerHTML;
	  phraseText = phraseText.replace(/<[^>]*>/g,"");
//	  alert(phraseText);
	  var keywordsElement = document.getElementById("keywords");
	  var quickFindForm = document.getElementById("quick_find");
	  var search2Form = document.getElementById("search2");
	  //alert(keywordsElement);
	  if (keywordsElement != null) {
		  keywordsElement.value = phraseText;
//		  alert(keywordsElement.value);
		  if (quickFindForm != null) {
//			  alert(document.quick_find.keywords.value);
			  document.quick_find.keywords.value = phraseText;
//			  alert(document.quick_find.keywords.value);
			  closeSearchSuggestions();
			  document.quick_find.submit();
		  }
		  if (search2Form != null) {
			  
//			  alert(search2Form);
//			  alert(document.search.keywords.value);
//			  alert(phrase.innerText);
			  document.search.keywords.value = phraseText;
//			  alert(document.search.keywords.value);
			  closeSearchSuggestions();
			  document.search.submit();
		  }
	  }

}

function checkKeywordSuggestions(keywordElement, keywordValue) {
    var url = "/checkkeywords.cmp?";
    url += "bfcid=" + sessionId;
	url += "&kw="+escape(keywordValue);
//	alert('getting '+url);
	
 	Http.get({
		url: url,
		callback: checkKeywordSuggestionsCallback,		
		cache: Http.Cache.GetNoCache
	});
}

function checkKeywordSuggestionsCallback(xmlreply) {
//	alert(xmlreply.status);
//	alert(Http.Status.OK);
	var response = xmlreply.responseText;
	if (xmlreply.status == Http.Status.OK){
		    if (response == "") {
		      //alert("Empty Resonse");
		  	  closeSearchSuggestions();		    	
		    } else {
		      //alert("Response = " + response);
			  var resultLines = response.split("\n");
			  //alert(resultLines.length);
			  var keywordsElement = document.getElementById("keywords");
			  var keyword_suggestionsDiv = document.getElementById("keyword_suggestions");
			  //alert(keyword_suggestionsDiv);
			    var curleft = curtop = 0;
			    var obj = keywordsElement;
			    //alert(obj);
			    var lastLeft = 0;
			    if (obj.offsetParent) {
			    	do {
			    		if (obj.offsetLeft > 0) {
							curleft += obj.offsetLeft;
							curtop += obj.offsetTop;
							lastLeft = obj.offsetLeft;
//						    alert('curleft='+curleft);			    	
//						    alert('lastLeft='+lastLeft);
			    		}
			    	} while (obj = obj.offsetParent);	
			    }
			    //alert(keywordsElement.style.width);
				var curwidth = keywordsElement.style.width;
				curwidth = curwidth.replace("px","");
			    //alert(lastLeft);

			    curleft = curleft - curwidth - lastLeft;
//			    alert(curleft);			    	
//			    alert(curtop);
			    curtop = 0;
			  	var divHTML = '';
			  	divHTML += '<div class="box-content" id="keywordSuggestionsDiv" style="border:2px solid black;padding-top:0px;padding-left:10px;';
			  	//divHTML += 'position: absolute; left: '+curleft+'; top: '+curtop+';';
			  	divHTML += 'position: relative;';
			  	//divHTML += 'position: relative;left: '+curleft+';';
			  	//divHTML += 'margin-left:200px;';
			  	divHTML += 'text-align:left;';
			  	divHTML += 'background-color:#ffffff;;z-index:9999;">';
			  	divHTML += '<br/>';
				  for (var i=0;i<resultLines.length;i++) {
					  //alert(resultLines[i]);
					  divHTML += '<a class="small" href="javascript:" onClick="selectKeywords(this);"><font style="color:gray;">' + resultLines[i] + '</font></a><br/>';
				  }
				divHTML += '<p align="right"><a href="javascript://" onClick="closeSearchSuggestions();"><img vspace="0" hspace="0" border="0"  src="/images/close.gif"></a></p>';
					
				divHTML += '</div>';
//			  
				keyword_suggestionsDiv.innerHTML = divHTML;
//				keyword_suggestionsDiv.innerHTML = '<h1>I AM HERE</h1>';
//			  for (var i=1;i<resultLines.length;i++) {
//				  alert(resultLines[i]);
//			  }
		    }
	 } else {
		 //alert('ajax error');
	 }
}

function updateWordSynonyms(wordSynonymId,wordSynonym,synonymWord,deleteAction) {
    var url = "/updatewordsynonyms.cmp?";
    url += "bfcid=" + sessionId;
	url += "&syn_id="+escape(wordSynonymId);
	url += "&word_syn="+escape(wordSynonym);
	url += "&syn_word="+escape(synonymWord);
	if (deleteAction) {
		url += "&delete_action=1;";
	}
//	alert('getting '+url);
	
 	Http.get({
		url: url,
		callback: updateWordSynonymsCallback,		
		cache: Http.Cache.GetNoCache
	});
}

function updateWordSynonymsCallback(xmlreply) {
	location.reload(true);
}

