var a9_sl_ui_item_order = "tlu";
var a9_sl_pubkey = "6013637636857743891";
var a9_sl_include_css = "http://sl.a9.com/ttr/ttr.css";
var a9_sl_picture_baseurl = "http://sl.a9.com/ttr/";
var a9_sl_showchangelocation = true;
var a9_sl_showfooter = true;

function a9_sl_punt_callback(divId) {
	var div = document.getElementById(divId);
	div.style.display = 'none';
}



function a9_sl_weighted_random_select(array) {
     var total_weight = 0;
     var length = array.length;
     for (var i = 1; i < length; i=i+2) {
        total_weight += array[i];
     }
     var rand = Math.random() * total_weight;
     var previous_weights = 0;
     for (var i = 1; i < length; i=i+2) {
        if(rand < previous_weights + array[i]) return array[i-1];
        previous_weights += array[i];
     }          
     return array[length-1];          
}


function A9AdsChangeLocationDisplay(response) {
	var divId = response.divid;
    var div = document.getElementById(divId + '_changelocation_div');
    if(div!=null) a9_sl_changelocation_onresponse(response);
    else a9_sl_render_ads(response);
}


function a9_sl_fixencoding(str) {
    str = str.replace(/\u0080/g, '\u20ac');
    str = str.replace(/\u0082/g, '\u201a');
    str = str.replace(/\u0084/g, '\u201e');
    str = str.replace(/\u0085/g, '\u2026');
    str = str.replace(/\u0089/g, '\u2030');
    str = str.replace(/\u008b/g, '\u2039');
    str = str.replace(/\u0091/g, '\u2018');
    str = str.replace(/\u0092/g, '\u2019');
    str = str.replace(/\u0093/g, '\u201c');
    str = str.replace(/\u0094/g, '\u201d');
    str = str.replace(/\u0096/g, '\u2013');
    str = str.replace(/\u0097/g, '\u2014');
    str = str.replace(/\u0099/g, '\u2122');
    str = str.replace(/\u009b/g, '\u203a');
    str = str.replace(/\u00c2\u00ae/g, '\u00ae');
    return str;
}

function a9_sl_getlines(line1,line2, merge) {
    if(line2=='') return line1;
    if(merge) return line1 + ' ' + line2;
    else return line1 + '<br/>' + line2;  
}

function a9_sl_wrappable_text(text) {
    var zerospace = (navigator.userAgent.match(/MSIE/) ? '' : '&#8203;');    
    var result = text.replace(/\./g, zerospace + '.');
    result = result.replace(/\//g, zerospace + '/');
    result = result.replace(/-/g, zerospace + '-');
    result = result.replace(/_/g, zerospace + '_');
    return result;
}




function a9_sl_punt(divId) {
	var shouldBubbleUp = a9_sl_punt_callback(divId);
	
	if (shouldBubbleUp && a9_sl_bpx_punt) {
	    var script = document.createElement('script');
	    script.language = 'javascript';
	    script.src= "http://bpx.a9.com/amzn/defaultad.js";
	    document.getElementById(divId).appendChild(script);
	    return true;
	} else {
		return false;
	}
}


function a9_sl_getElementByClassName(container, tagName, className) {
  var elements = container.getElementsByTagName(tagName);
  for(var i=0;i<elements.length;i++) {
    var element = elements[i];
    if (element.className == className) return element;
  }
}  


function a9_sl_changelocation_popup(element, timerid, divId) {

    if(timerid==null) return setTimeout(function() { a9_sl_changelocation_popup(element, 1, divId)}, 500);
    var container = document.getElementById(divId);
    var div = document.getElementById(divId + '_changelocation_div');
    
    if(div==null) {
       div = document.createElement('div');
       div.className = "changelocation_popup";
       
       element.onmouseout = function() {  div.timerid = setTimeout( function() {a9_sl_changelocation_hide(divId);}, 500); };
       div.onmouseout = function() {  div.timerid = setTimeout(function() {a9_sl_changelocation_hide(divId);}, 500); };
       div.onmouseover = function() { clearTimeout(div.timerid); };
       
       div.id = divId + '_changelocation_div';
       var html = "Enter a Zip Code to see service <br/> providers in another area.";
       html += "<span class='error_msg'></span><br>";
       html += "<input id='zip' name='zip' onkeypress='a9_sl_changelocation_onsubmit(event, \"" + divId + "\")' onclick='this.value=\"\"' value='Enter Zip Code'>";
       html += "<span class='gobutton' onclick='a9_sl_changelocation_onsubmit(event, \"" + divId + "\")'>&nbsp;<span>";
       div.innerHTML = html;
       document.body.appendChild(div);
     } else {
       
     }
     
    div.style.display = 'block';
    var pos = a9_sl_findposition(element);
    var container_pos = a9_sl_findposition(container);
    
    pos[0] = pos[0] + element.offsetWidth-div.clientWidth;
    pos[1] = pos[1] + element.offsetHeight; 
    if(pos[0]<=container_pos[0]) pos[0] = container_pos[0];
    
    div.style.left = pos[0] + "px";
    div.style.top =  pos[1] + "px"; 
        
}

  

function a9_sl_changelocation_onsubmit(event, divId) {
    if (event.type == 'keypress' && event.keyCode != 13) {
        return false;
    }    
    
    var div = document.getElementById(divId + '_changelocation_div');
    var zip = document.getElementById("zip").value;
    if(! zip.match(/^[0-9]{5}$/)) { 
        var span = a9_sl_getElementByClassName(div, "span", "error_msg");
        span.innerHTML = "<br>You must enter a valid U.S. Zip Code.";
        return;
    }
    a9_sl_userlocation = zip;
    a9_sl_refreshads(divId);
    
}

function a9_sl_changelocation_onresponse(response) {
    var div = document.getElementById(response.divid + '_changelocation_div');
    if(response.ads.length==0) { 
        div.getElementsByClassName("error_msg")[0].innerHTML = "<br>No services found in this area";
    } else {
        div.style.display = "none";    
        a9_sl_render_ads(response);
    }    
    
}


function a9_sl_changelocation_hide(divId) {
    var div = document.getElementById(divId + '_changelocation_div');
    div.style.display = "none";   
}



function a9_sl_findposition(obj) {
        var curleft = 0;
        var curtop = 0;
        if (obj.offsetParent) {
                curleft = obj.offsetLeft;
                curtop = obj.offsetTop;
                while (obj = obj.offsetParent) {
                        curleft += obj.offsetLeft;
                        curtop += obj.offsetTop;
                }
        }
        if(curleft < 10) curleft = 10;
        return [curleft,curtop];
}

function a9_sl_render_ads(response) {
	var divId = response.divid;
    if(response.ads.length==0) return a9_sl_punt(divId);

    var container = document.getElementById(divId);

    container.className = "ad ad_" + a9_sl_adsize + " " + (a9_sl_design ? "ad_" + a9_sl_adsize + "_" + a9_sl_design : "") + " " + (a9_sl_showpicture ? "ad_" + a9_sl_adsize + "_wgr" : "");
    var category = response["categories"][0];
    a9_sl_category = category["tag"];
    a9_sl_refreshid = response["refresh"];
        
    var ads_html = '';    
    //var location = response.location_string;
    //if(location!='') location = 'in ' + location;
    ads_html += '<div class="header"><span>' + category["title"] + '</span>';
    if(a9_sl_showchangelocation && category.isLocationUserChangeable == 'true') {
      ads_html += ' <span class="changelocation" onmouseover="a9_sl_changelocation_popup(this, null, \'' + divId + '\')">Change Location</span>';
    }
    ads_html += '</div>';  

    if(a9_sl_showpicture) { 
        var picture = a9_sl_picture_baseurl + category["tag"] + "_" + a9_sl_adsize + ".jpg";        
        ads_html += '<div class="picture" style="background-image:url('+picture+')"></div>';    
    }
    
    ads_html += '<div class="content"><table><tr><td><ul>';
  
    
    for (var i = 0, length = response.ads.length; i < length; ++i) {

      ads_html += '<li>';        
      var ad = response.ads[i];
      var adTitle = a9_sl_fixencoding(ad.line1);
      var adLines = a9_sl_fixencoding(a9_sl_getlines(ad.line2,ad.line3, a9_sl_mergelines));
      ad.visible_url = a9_sl_wrappable_text(ad.visible_url);

      for (var ii=0; ii<a9_sl_ui_item_order.length;ii++) {  
       var item = a9_sl_ui_item_order.charAt(ii);
        if(item=="t") ads_html += '<div class="title"><a href="' + ad.url + '" target="_blank">' + adTitle + '</a></div>';
        if(item=="u") ads_html += '<div class="url"><a href="' + ad.url + '" target="_blank">' + ad.visible_url + '</a></div>';
        if(item=="l") ads_html += '<div class="lines"><span>' + adLines + '</span></div>';
        if(item=="-") ads_html += '<br/>';                
      }
      
      ads_html += '</li>';
      
    }
    
    // End of the inner table
    if (a9_sl_showfooter) {
    	if (a9_sl_makefooterclickable) {
    		ads_html += '<a class="footerlink" href="http://clickriver.com/" target="_blank">';
    	}
    	ads_html += '<div class="footer">Clickriver Ads</div>';
    	if (a9_sl_makefooterclickable) {
    		ads_html += '</a>';
    	}
    }
    ads_html += '</ul></td></tr></table></div><div class="bottom" style="display: none;"></div>';
    container.innerHTML = ads_html;
    
    if (typeof a9_sl_post_render_function == 'string') {
    	var content = a9_sl_post_render_function + '("' + divId + '");';
    	eval(content);
    	/*var script = document.createElement('script');
    	script.type = 'text/javascript';
    	script.charset = 'UTF-8';
		if (typeof script.text != 'undefined') {
			script.text = content;
		} else {
			script.innerHTML = content;
		}
		container.appendChild(script);*/
    }
        
}


function a9_sl_getads(retry, divId) {

        if (document.getElementById(divId)==null && retry < 5) {
        	setTimeout(
        		function() {
        			a9_sl_getads(retry + 1, divId);
        		},
        		10
        	);
            return;
        }

        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.language = 'javascript';
        script.charset = 'UTF-8';

        var baseurl = "http://sl.a9.com";      
        
        if(typeof a9_sl_categories !='undefined') a9_sl_category = a9_sl_weighted_random_select(a9_sl_categories);                   
        if(typeof a9_sl_get_channel =='function') a9_sl_channel = a9_sl_get_channel();
        if(typeof a9_sl_ui_item_order =='undefined') a9_sl_ui_item_order = "tul-";         

        if(typeof a9_sl_mergelines == 'undefined') a9_sl_mergelines = true;
        if(typeof a9_sl_picture_baseurl == 'undefined')  a9_sl_picture_baseurl = "";
        if(typeof a9_sl_bpx_punt == 'undefined')  a9_sl_bpx_punt = false;      

        if(typeof a9_sl_design == 'undefined')  a9_sl_design = '';
        if(typeof a9_sl_showpicture == 'undefined')  a9_sl_showpicture = false;
        if(typeof a9_sl_showfooter  == 'undefined')  a9_sl_showfooter = false;        
        if(typeof a9_sl_makefooterclickable  == 'undefined')  a9_sl_makefooterclickable = true;        
        if(typeof a9_sl_showchangelocation == 'undefined') a9_sl_showchangelocation = false;
        if(typeof a9_sl_punt_callback == 'undefined') {
        	a9_sl_punt_callback = function(divId) { return true; };
        }

              
        if(a9_sl_channel==false) return a9_sl_punt(divId);          

        script.src= baseurl + '/synd?oenc=UTF-8&pub=cfp&pubKey='+a9_sl_pubkey+'&cat=' + escape(a9_sl_category) + '&ch=' + escape(a9_sl_channel) + '&url=' + escape(document.location) + '&useragent=' + escape(navigator.userAgent) + '&jsv=1a&adspercat=' + a9_sl_adcount + "&divid=" + divId + "&rnd=" + (new Date()).getTime() + "&numretr=" + retry;    

        document.getElementById(divId).appendChild(script);

}



function a9_sl_refreshads(divId) {

        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.language = 'javascript';
        script.charset = 'UTF-8';
        var baseurl = "http://sl.a9.com";                
        script.src= baseurl + '/js?oenc=UTF-8&rnd='+ (new Date()).getTime()+ '&userLocationInput='+a9_sl_userlocation+'&r=' + a9_sl_refreshid + "&requestedCat=" + a9_sl_category;
        document.getElementById(divId).appendChild(script);

}

function a9_sl_generateDivId() {
	var idx = 0;
	while (idx < 100) {
		var el = document.getElementById("a9_sl_div" + idx);
		if (el == null) {
			return "a9_sl_div" + idx;
		} else {
			idx++;
		}
	}
}

var baseurl = "http://sl.a9.com";

if(typeof a9_sl_include_css != 'undefined') {
  document.write('<link rel="stylesheet" href="'+a9_sl_include_css +'" type="text/css">');
}

var divId = a9_sl_generateDivId();
document.write('<div id="' + divId + '"></div>\n');
document.write('<scr' + 'ipt>setTimeout(function() { a9_sl_getads(0, "' + divId + '"); }, 0);</scr' + 'ipt>\n');
document.close(); 
