//By default other sites cannot access our content. Only listed hosts will change this value
var hostok = false;

//Default source directory. Can change for specific hosts in checkSBPHost
var source = 'syndication';

//Default content width. Syndicate can change by passing a number in initiateSBPContent call
var contentWidth = 350;

//Default affiliate code
var affiliate = '';

var error = '';

var hostResponse = false;

//These three arrays allow you to add javascript files, CSS files, and meta tags to the <head>
//of the document. You can add files on a site by site basis by pushing to these arrays in the
//checkSBPHost function. There might be some security issues with this that need further thought.
var addScript = new Array();
var addLink = new Array();
var addMeta = new Array();

addLink.push("http://www.bplans.com/Graphical/CSS/pas_sbp.css");
//addMeta.push("robots::NOINDEX");

//Add a style sheet so drop down menus work in IE 6
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
	var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
	if(ieversion < 7) {
		addLink.push("http://www.bplans.com/graphical/CSS/free_plans_ie6.css");
	}
}

//If set to true (in checkSBPHost) outside links to a particular plan or plan page are 
//possible by adding a query_string with plan=Plan_Name and optionally page=Page_Name
//or category=Category_Name
//I think making plans linkable will increase likelihood of search engines indexing
//(linked) content on the partner site (could add a NOINDEX meta tag to header in
//includeSBPFiles function if linkablePlan == true).
var linkableCategory = false;
var linkablePlan = false;

var host = window.location.host.toLowerCase();
var req;

var pasPageTracker;
var callback = false;
//Make sure they are coming from a site we support and set site specific variables
checkSBPHostJ();


function checkSBPHostJ() {
	var url = "http://www.bplans.com/syndication/hosts/" + host + ".js";
    var head = document.getElementsByTagName("head").item(0);
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
   	script.setAttribute("src", url);
   	head.appendChild(script);
}
function verifyHost(response){
	if(response.hostResponse.hostok == 'true') {
		hostok = true;
	}
	if(response.hostResponse.linkableCategory == 'true') {
		linkableCategory = true;
	}
	if(response.hostResponse.linkablePlan == 'true') {
		linkablePlan = true;
	}
	if(response.hostResponse.includeGAJS != 'false') {
		var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		addScript.push(gaJsHost + "google-analytics.com/ga.js");
	}
	if(response.hostResponse.includeFloatbox != 'false') {
		addScript.push("http://www.bplans.com/js/floatbox/floatbox.js");
		addLink.push("http://www.bplans.com/js/floatbox/floatbox.css");
	}
	affiliate=response.hostResponse.affiliate;
	if(response.hostResponse.callback == 'true') {
		callback = true;
	}
	if(typeof(response.hostResponse.source) == 'string') {
		source = response.hostResponse.source;
	}
	//This function is not as functional as the old XML one, cannot add arbitrary scripts, css, or meta tags yet
	
	if(linkablePlan == true) {
		addMeta.push("robots::NOINDEX");
	}
	
	hostResponse = true;
	
	//Add javascript and CSS files and meta tags to the <head> from addScript, addLink, and addMeta arrays
	includeSBPFiles();
}
function checkSBPHost() {
	try { //Internet Explorer
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	}
	catch(e) {
		try { //Firefox, Mozilla, Opera, etc.
			xmlDoc=document.implementation.createDocument("","",null);
		}
		catch(e) {
//			alert(e.message);
			return;
		}
	}

	xmlDoc.async=false;
	
	try {
		xmlDoc.load("hosts/" + host + ".xml");
	
		if(xmlDoc.getElementsByTagName("hostok")[0].childNodes[0].nodeValue == 'true') {
			hostok = true;
		}
	
		if(xmlDoc.getElementsByTagName("linkableCategory")[0].childNodes[0].nodeValue == 'true') {
			linkableCategory = true;
		}
	
		if(xmlDoc.getElementsByTagName("linkablePlan")[0].childNodes[0].nodeValue == 'true') {
			linkablePlan = true;
		}
		if(xmlDoc.getElementsByTagName("includeGAJS")[0].childNodes[0].nodeValue == 'true') {
			var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
			addScript.push(gaJsHost + "google-analytics.com/ga.js");		
		}
		if(xmlDoc.getElementsByTagName("includeFloatbox")[0].childNodes[0].nodeValue == 'true') {
			addScript.push("http://www.bplans.com/js/floatbox/floatbox.js");
			addLink.push("http://www.bplans.com/js/floatbox/floatbox.css");
		}
		affiliate=xmlDoc.getElementsByTagName("affiliate")[0].childNodes[0].nodeValue;
		if(typeof(xmlDoc.getElementsByTagName("source")[0]) != 'undefined' 
			&& typeof(xmlDoc.getElementsByTagName("source")[0].childNodes[0]) != 'undefined'
			&& xmlDoc.getElementsByTagName("source")[0].childNodes[0] != null) {
				source=xmlDoc.getElementsByTagName("source")[0].childNodes[0].nodeValue;
		}
		var x;
		if(typeof(xmlDoc.getElementsByTagName("addScript")[0]) != 'undefined') {
			for(x in xmlDoc.getElementsByTagName("addScript")) {
				addScript.push(xmlDoc.getElementsByTagName("addScript")[x].childNodes[0].nodeValue);
			}
		}
		if(typeof(xmlDoc.getElementsByTagName("addLink")[0]) != 'undefined') {
			for(x in xmlDoc.getElementsByTagName("addLink")) {
				addScript.push(xmlDoc.getElementsByTagName("addLink")[x].childNodes[0].nodeValue);
			}
		}
		if(typeof(xmlDoc.getElementsByTagName("addMeta")[0]) != 'undefined') {
			for(x in xmlDoc.getElementsByTagName("addMeta")) {
				addScript.push(xmlDoc.getElementsByTagName("addMeta")[x].childNodes[0].nodeValue);
			}
		}
	}
	catch(e) {
		var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		addScript.push(gaJsHost + "google-analytics.com/ga.js");
	}
}

function initiateSBPContent(siteContentWidth,plantype) {
	plantype = plantype || 'bplans';
	if(hostResponse == false) {
		setTimeout("initiateSBPContent(" + siteContentWidth + "," + plantype + ")",100);
	}
	else {
		initiateSBPContentReal(siteContentWidth,plantype);
	}
}

function initiateSBPContentReal(siteContentWidth,plantype) {
	if(siteContentWidth) {
		contentWidth = siteContentWidth;
	}
	else {
		contentWidth = document.getElementById('pas_sbp').offsetWidth;
	}	
	//Adjust for padding of pas_sbp_wrapper, subtract either 2*padding, or padding-left + padding-right from contentWidth
	contentWidth = contentWidth - 16;
	
	if(typeof(_gat)=='object'){
		pasPageTracker = _gat._getTracker("UA-90231-2");
	}
	
	if (hostok == false) {
		updateSBPDiv();
	}
	else if(linkableCategory && getSBPQueryString('category')){
		var category = getSBPQueryString('category');
		getSBPPage('categories',category);
	}
	else if(linkablePlan && getSBPQueryString('plan')){
		var plan = getSBPQueryString('plan')
		var page = getSBPQueryString('page');
		getSBPPage(plan,page);
	}
	else if(plantype == 'mplans') {
		getSBPPage('categories','sample_marketing_plans');		
	}
	else {
		getSBPCategories();
	}
}

function getSBPQueryString(key) {
	queryString = window.location.search.substring(1);
	pairs = queryString.split("&");
	for (i=0;i<pairs.length;i++) {
		pair = pairs[i].split("=");
		if (pair[0] == key) {
			return pair[1];
		}
	}
	return false;
}

function getSBPCategories() {
	getSBPPage('categories','categories');
}

function getSBPCategory(category) {
	getSBPPage('categories',category);
}

function getSBPPage(plan,page) {
	page = page || 'executive_summary_fc';
	if(plan.match('marketing_plan') && page == 'executive_summary_fc') {
		page = 'marketing_vision_fc';
	}
	
	var checkSource = checkVariable(source);
	var checkPlan = checkVariable(plan);
	var checkPage = checkVariable(page);
	
	if(checkSource || checkPlan || checkPage) {
		var html = "<p>It looks like you sent an illegal value to this page.</p><p><a href=\"#pas_sbp\" onClick=\"getSBPCategories()\">Start over</a>.</p>";
		document.getElementById('pas_sbp').innerHTML = html;
	}
	else {
		var url = "http://www.bplans.com/" + urlEncode(source) + "/" + urlEncode(plan) + "/" + urlEncode(page) + ".html";
	
		loadingSBP();
		loadSBPDocJ(url);
		if(typeof(pasPageTracker)=='object'){
			pasPageTracker._trackPageview("/" + urlEncode(host) + "/" + urlEncode(plan) + "/" + urlEncode(page));
		}
	}
	if(callback = true && typeof(pas_sbp_callback) == 'function') {
		pas_sbp_callback(plan,page);
	}
}

function checkVariable(suspicious) {
	var pattern = new RegExp("\\.\\.");
	return(pattern.test(suspicious));
}

function loadingSBP() {
	var divHeight = document.getElementById('pas_sbp').offsetHeight;
	var html = "<div style=\"height:" + divHeight + "px;\">loading...</div>";
	document.getElementById('pas_sbp').innerHTML = html;
}
function loadSBPDocJ(url) {
	var head = document.getElementsByTagName("head").item(0);
	var script = document.createElement("script");
	script.setAttribute("type", "text/javascript");
	script.setAttribute("src", url);
	head.appendChild(script);
}

function loadSBPXMLDoc(url) {
	req = false;
	// branch for native XMLHttpRequest object
	if(window.XMLHttpRequest) {
		try {
			req = new XMLHttpRequest();
			//req = GXmlHttp.create();
        } catch(e) {
			req = false;
        }
		// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				req = false;
			}
		}
    }
	if(req) {
		req.onreadystatechange = processSBPReqChange;
		req.open("GET", url, true);
		req.send("");
	}
}

function processSBPReqChange() {
	// only if req shows "loaded"
	if (req.readyState == 4) {
		// only if "OK"
		if (req.status == 200) {
			updateSBPDiv();
		} 
		else if (req.status == 404) {
			error = '404';
			updateSBPDiv();
		} 
		else {
			error = 'unknown';
			updateSBPDiv();
		}
	}
}

function updateSBPDiv(json) {
	if(hostok != true) {
		html = 'An error has occurred.<br /> It looks like you are accessing this service from an unauthorized site.<br />';
	}
	else if (error == '404') {
		html = "<p>The information you requested could not be found.</p><p><a href=\"#pas_sbp\" onClick=\"getSBPCategories()\">Start over</a>.</p>";
		error = '';
	}
	else if (error == 'unknown') {
		html = "<p>Sorry, an unknown error occurred..</p><p><a href=\"#pas_sbp\" onClick=\"getSBPCategories()\">Start over</a>.</p>";
		error = '';
	}
	else {
		html = json.response.replace(/&quot;/g,'"');
	}
	html = html.replace(/\[\[AFFILIATE\]\]/g, affiliate);
	document.getElementById('pas_sbp').innerHTML = html;
//If page has a div with id="pas_sbp_hidden" just before </body> the floatbox tables width will be better
	try {
		document.getElementById('pas_sbp_hidden').innerHTML = document.getElementById('pas_sbp_hidden_tables').innerHTML;
		document.getElementById('pas_sbp_hidden_tables').innerHTML = ' ';
	}
	catch(e) {}
	
	formatSBPPlanPage();
	try {
		fb.anchors.length = 0;
		fb.tagAnchors(document.body);
	}
	catch(e) {}
	
	if(callback = true && typeof(pas_sbp_postcallback) == 'function') {
		pas_sbp_postcallback();
	}

}



function formatSBPPlanPage() {
	
	document.getElementById('pas_sbp_wrapper').style.width = contentWidth + 'px';
	var count= 1;
	if(document.getElementById('pas_sbp_chart_1') !== null) {
		while(document.getElementById('pas_sbp_chart_' + count) !== null) {
			if(contentWidth < 550) {
				document.getElementById('pas_sbp_chart_' + count).style.width = contentWidth + 'px';
				document.getElementById('pas_sbp_chart_' + count).style.height = parseInt(contentWidth/550*318) + 'px';
				document.getElementById('pas_sbp_chart_' + count + '_mag').style.width = '111px';
				document.getElementById('pas_sbp_chart_' + count + '_mag').style.height = '15px';
			}
			else {
				document.getElementById('pas_sbp_chart_' + count).style.width = '550px';
				document.getElementById('pas_sbp_chart_' + count).style.height = '318px';
			}
			count++;
		}
	}
	
	var count = 1;
	if(document.getElementById('pas_sbp_promo_1') !== null) {
		while(document.getElementById('pas_sbp_promo_' + count) !== null) {
			var imageWidth = document.getElementById('pas_sbp_promo_' + count).style.width;
			imageWidth= parseInt(imageWidth.replace('px',''));
			var imageHeight = document.getElementById('pas_sbp_promo_' + count).style.height;
			imageHeight = parseInt(imageHeight.replace('px',''));
			
			if(contentWidth < imageWidth) {
				document.getElementById('pas_sbp_promo_' + count).style.width = contentWidth + 'px';
				document.getElementById('pas_sbp_promo_' + count).style.height = parseInt(contentWidth/parseInt(imageWidth)*parseInt(imageHeight)) + 'px';
			}
			count++;
		}
	}
	
	var count = 1;
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	var bigMaxWidth = myWidth * 0.85;
	var bigMaxHeight = myHeight * 0.82;
	
	if(document.getElementById('pas_sbp_table_' + count + '_big') !== null) {
		while(document.getElementById('pas_sbp_table_' + count + '_big') !== null) {
			document.getElementById('pas_sbp_table_' + count).style.minWidth = contentWidth + 'px';
			document.getElementById('pas_sbp_table_' + count + '_div').style.width = contentWidth + 'px';

			//scale the inline tables
			var fs=12;
			document.getElementById('pas_sbp_table_' + count).style.fontSize = fs + 'px';
			
			while(document.getElementById('pas_sbp_table_' + count).offsetWidth > contentWidth && fs > 2) {
				fs = fs - 1;
				document.getElementById('pas_sbp_table_' + count).style.fontSize =  fs + 'px';
			}
			fs = fs - 1;
			document.getElementById('pas_sbp_table_' + count).style.fontSize =  fs + 'px';
			
			if(fs < 11) {
				document.getElementById('pas_sbp_table_' + count + '_mag').style.width = '111px';
				document.getElementById('pas_sbp_table_' + count + '_mag').style.height = '15px';
			}
			
			//figure out how big the lightboxes should be and hide the full-size tables
			var bigTableWidth = document.getElementById('pas_sbp_table_' + count + '_big').offsetWidth + 50;
			var bigTableHeight = document.getElementById('pas_sbp_table_' + count + '_big').offsetHeight + 60;
			document.getElementById('pas_sbp_table_' + count + '_big_div').style.display = 'none';

			if(bigTableWidth > bigMaxWidth) {
				bigTableWidth = bigMaxWidth;
			}
			if(bigTableHeight > bigMaxHeight) {
				bigTableHeight = bigMaxHeight;
			}
			document.getElementById('pas_sbp_table_' + count + '_mag_link').rev = 'width:' + bigTableWidth + 'px; height:' + bigTableHeight + 'px';
			
			count++;
		}
	}
}

function includeSBPFiles() {
	var head = document.getElementsByTagName('head')[0];
	
	var x;
	for(x in addScript) {
		script = document.createElement('script');
		script.src = addScript[x];
		script.type = 'text/javascript';	
		head.appendChild(script);
	}
	
	var y;
	for(y in addLink) {
		link = document.createElement('link');
		link.type = 'text/css';
		link.rel = 'stylesheet';
		link.href = addLink[y];
		head.appendChild(link);
	}
	
	var z;
	var metaArray = new Array();
	for(z in addMeta) {
		metaArray = addMeta[z].split('::');
		meta = document.createElement('meta');
		meta.name = metaArray[0];
		meta.content = metaArray[1];
		head.appendChild(meta);	
	}
}

function urlEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}
