var queue = false;
var lock = false;
var currentKeyword = '';
var currentKeywordCount = 0;
var arrKW = new Array();
var mouseX = 0;
var mouseY = 0;
var timer = 0;
var thisEl;
var options = {
	 settings : {
		scope : document.body,
		width : 400, // 400
		height : 302, // ++
		colors : {
			title : '#1C377F',
			q1 : 'black',
			q2 : 'black',
			bg : '#fff',
			email : 'green'
		},
		linkStyle : {
			textDecoration : 'underline',
			borderBottom : '1px solid #080',
			paddingBottom : '1px',
			color : '#080',
			cursor : 'pointer'
		} 
	}
};

var browser = '';
if (document.all) {browser = "ie";} 
else if (navigator.userAgent.indexOf("Opera")>-1) {  browser = "opera";} 
else { browser = "mozilla"; }

// Loading span
var loading_span = document.createElement('div');

String.prototype.trim = function () {
   return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function setUrl(el, url) {

	urlColors = '&titleColor=' + escape(options.settings.colors.title) + '&' +
	'question1Color=' + escape(options.settings.colors.q1) + '&' +
	'question2Color=' + escape(options.settings.colors.q2) + '&' +
	'emailColor=' + escape(options.settings.colors.email) + '&' +
	'backgroundColor=' + escape(options.settings.colors.bg);
	
	if (el.src == 'about:blank') {
		el.src = url + urlColors;
	} else {
		el.onload = '';
	}
}

function getMousePos(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (browser == "mozilla")     {
		posx = e.pageX;
		posy = e.pageY;
    } else {
        posx = e.clientX + document.body.scrollLeft
                + document.documentElement.scrollLeft;
        posy = e.clientY + document.body.scrollTop
                + document.documentElement.scrollTop;
    }
    return {x:posx, y:posy}
}


function getBodyScrollTop() {
   return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || 
      (document.body && document.body.scrollTop);
}

function setStyles(element, styles) {
    for(var s in styles) {
        element.style[s] = styles[s];
    }
}

function findText(element, pattern, callback) {
	for (var childi = element.childNodes.length; childi-->0;) {
		var child = element.childNodes[childi];
      // links are ignored
      if (child.nodeName == 'A') continue;

      //Excludes spans
      if (child.nodeName == 'SPAN' && child.className.indexOf('sppc_exclude') > -1) {       
         continue;        
      }
      //Excludes divs
      if (child.nodeName == 'DIV' && child.className.indexOf('sppc_exclude') > -1) {       
         continue;        
      }

		if (child.nodeType == 1) {
			findText(child, pattern, callback);
		} else if (child.nodeType==3) {
			var matches= [];
			var match;
			var text = html_entity_decode(child.data);
			text = text.replace("’", "'").replace("“", '"').replace("”", '"');
			while (match = pattern.exec(text)) {
			   matches.push(match);
			}
			for (var i = matches.length; i-->0;) {
			   callback.call(window, child, matches[i]);
			}
		}
	}
}


function hasClass (obj, className) {
	if (typeof obj == 'undefined' || obj==null || !RegExp) { return false; }
		var re = new RegExp("(^|\\s)" + className + "(\\s|$)");
		if (typeof(obj)=="string") {
			return re.test(obj);
		} else if (typeof(obj)=="object" && obj.className) {
			return re.test(obj.className);
		}
	return false;
}



function applyElActions(el, url) {
	setStyles(el, options.settings.linkStyle);
   el.onmouseover = function(e) {
   	if (lock) {
   	   return false;
   	}

   	mouse = getMousePos(e);
   	mouseX = mouse.x;
   	mouseY = mouse.y;


   	if (1 == 1) {
   		if (queue) {
   		   return false;
   		}
   		removeBox();
	   	
         // Loading
         loading_span.style.display = 'block';
	   	loading_span.style.left = mouseX + 'px';
	   	loading_span.style.top = (mouseY - 10) + 'px';
	   	queue = true;
	   	
	   	thisEl = this;
	   	// Load script
	   	var scr = document.createElement('script');
	   	scr.src = url;
	   	scr.type = 'text/javascript';
	   	document.getElementsByTagName('head')[0].appendChild(scr);
   	}
   }
}


function replaceWords(opt) {
	findText(options.settings.scope, new RegExp('\\b' + opt.keyword + '\\b', 'gi'), function(node, match) {
		
		currentKeywordCount++;
		
		var span= document.createElement('span');
	   span.className= 'sppclink';
	   span.id = 'sppclink' + currentKeywordCount;

	   arrKW[arrKW.length] = {keyword : opt.keyword, id : span.id, url: opt.url}; 
	   root = document.body;
	   root.onclick = function(evt) {
	   	target = (browser == 'ie') ? event.srcElement : evt.target;
	   	if (target.nodeName!='HTML' && !(hasParent(target, 'sppc_box') || hasClass(target.parentNode, 'sppc_content'))) {
   			removeBox();
   		}
	   } 
	   
		node.splitText(match.index + opt.keyword.length);
	   span.appendChild(node.splitText(match.index));
	   node.parentNode.insertBefore(span, node.nextSibling);
	});
}

function removeBox() {
	lock = false;
	el = document.getElementById('sppc_box');
	if (el) {
		el.style.display = 'none';
		el.parentNode.removeChild(el);
	}
}



function hasClass(el,className) {
	return el.className.match(new RegExp('(\\s|^)'+className+'(\\s|$)'));
}

 

function hasParent(el, classname) {
	try {
		if (el.nodeName == 'BODY') return false;
		if (hasClass(el, classname)) return true 
		else return hasParent(el.parentNode, classname);
	} catch (e) {}
}

function buildBox(config) { 



	var box = document.createElement('div');
	var title = document.createElement('div');
	var close = document.createElement('a');
	var content_title = document.createElement('div');
	var footer_href = document.createElement('a');
	// var content_iframe = document.createElement('div');
	var content = document.createElement('div');
	var footer = document.createElement('div');

	setStyles(box, {
		width: (options.settings.width + 'px'),
		//height: (options.settings.height + 'px'),
		position: 'absolute',
		zIndex: 999
	});

	box.id = 'sppc_box';
	//box.style.height = '800px';
	// box.style.marginTop = '-200px';
	

	close.style.backgroundImage = 'url(' + options.settings.base_url + 'images/inline/close_icon.gif)';
	close.style.backgroundRepeat = 'no-repeat';
	close.style.width = '16px';
	close.style.height = '16px';
	close.style.display = 'block';
//	close.style.cssFloat = 'right';
//	close.style.styleFloat = 'right';
//	close.style.marginRight = '10px';
//	close.style.marginTop = '0px';
   close.style.position = 'absolute';
   close.style.top = '9px';
   close.style.right = '16px';
	
	close.style.cursor = 'pointer';
	close.id = 'close-btn';

	if (config.direction == 'tl') {
		title.style.backgroundImage = 'url(' + options.settings.base_url + 'images/inline/box-tl-arr.png)';
		title.style.height = '31px';
		footer.style.backgroundImage = 'url(' + options.settings.base_url + 'images/inline/box-b-close.png)';
		footer.style.height = '6px';
	} else if (config.direction == 'tr') {
		title.style.backgroundImage = 'url(' + options.settings.base_url + 'images/inline/box-tr-arr.png)';
		title.style.height = '31px';
		footer.style.backgroundImage = 'url(' + options.settings.base_url + 'images/inline/box-b-close.png)';
		footer.style.height = '6px';
	} else if (config.direction == 'bl') {
		title.style.backgroundImage = 'url(' + options.settings.base_url + 'images/inline/box-t-close.png)';
		title.style.height = '6px';
		title.style.fontSize = '2px';
		title.style.lineHeight = '2px';
		footer.style.backgroundImage = 'url(' + options.settings.base_url + 'images/inline/box-bl-arr.png)';
		footer.style.height = '31px';
	} else if (config.direction == 'br') {
		title.style.backgroundImage = 'url(' + options.settings.base_url + 'images/inline/box-t-close.png)';
		title.style.height = '6px';
		title.style.fontSize = '2px';
		title.style.lineHeight = '2px';
		footer.style.backgroundImage = 'url(' + options.settings.base_url + 'images/inline/box-br-arr.png)';
		footer.style.height = '31px';
	}
	
	content.style.backgroundImage = 'url(' + options.settings.base_url + 'images/inline/box-bg.png)';
	//content.style.height = '265px';
	content.style.paddingTop = '0';
	content.style.marginTop = '0';
	
	//content_title.style.backgroundImage = 'url(' + options.settings.base_url + 'images/inline/box-ico.png)';
	content_title.style.backgroundRepeat = 'no-repeat';
	//content_title.style.height = '23px';
	content_title.style.height = '0';
	content_title.style.marginLeft = '10px';
	content_title.style.paddingLeft = '22px';
	content_title.style.paddingTop = '2px';
	content_title.style.position = 'relative';
	content_title.innerHTML = '';
	content_title.insertBefore(close, content_title.firstChild);
	

	
	
	
	footer_href.style.backgroundImage = 'url(' + options.settings.base_url + 'images/inline/box-ico.png)';
	footer_href.style.display = 'block';
	footer_href.style.backgroundRepeat = 'no-repeat';
	footer_href.style.backgroundPosition = 'right top';
	footer_href.style.height = '23px';
	footer_href.style.marginRight = '7px';
	footer_href.style.paddingTop = '0px';
	footer_href.href = 'http://www.capchure.com';
	footer_href.target = '_blank';
	footer_href.innerHTML = '';
	
	
	
	
	title.style.backgroundRepeat = 'no-repeat';
	footer.style.backgroundRepeat = 'no-repeat';
	content.style.backgroundRepeat = 'repeat-y';
	content.className = 'sppc_content';
	content.appendChild(content_title);
	content.appendChild(config.element);
	content.appendChild(footer_href);
	


	// content_iframe.innerHTML = config.content;

	box.appendChild(title);
	box.appendChild(content);
	box.appendChild(footer);
	
	
	return box;
}

function sppcCPA(userOpts) {

	for (attrname in userOpts.settings) { options.settings[attrname] = userOpts.settings[attrname]; }
	
	// options.settings = options.settings || userOpts.settings ;
	options.settings.scope = userOpts.settings.scope || options.settings.scope;
	options.settings.linkStyle.borderBottom = '1px solid ' + sppc_linkColor || options.settings.linkStyle.borderBottom;

	
	options.settings.linkStyle.color = 	(typeof sppc_linkColor != 'undefined') ? sppc_linkColor.trim() : options.settings.linkStyle.color;
	options.settings.colors.title = 		(typeof sppc_titleColor != 'undefined') ? sppc_titleColor.trim() : options.settings.colors.title;  
	options.settings.colors.q1 = 			(typeof sppc_question1Color != 'undefined') ? sppc_question1Color.trim() : options.settings.colors.q2;
	options.settings.colors.q2 = 			(typeof sppc_question2Color!= 'undefined') ? sppc_question2Color.trim() : options.settings.colors.q1;
	options.settings.colors.email = 		(typeof sppc_emailColor != 'undefined') ? sppc_emailColor.trim() : options.settings.colors.email;  
	options.settings.colors.bg =  		(typeof sppc_backgroundColor != 'undefined') ? sppc_backgroundColor.trim() : options.settings.colors.bg;
	
	// Loading span
	setStyles(loading_span, {
	   backgroundImage : "url(" + options.settings.base_url + "/images/inline/loading.gif)",
	   backgroundRepeat : "no-repeat",
	   width : "16px",
	   height : "16px",
	   left : '0px',
	   top : '0px',
	   position : "absolute",
	   zIndex : 999,
	   display : "none"
	});
	loading_span.className = "sppc_loading";
	loading_span.id = "sppc_loading";
	document.body.appendChild(loading_span);

	for (i = 0; i < userOpts.keywords.length; i++) replaceWords(userOpts.keywords[i])
	
	var cKeywords = new Array();
	for (var i = arrKW.length; i-->0;) {
		if (!cKeywords[arrKW[i].keyword]) {
		   cKeywords[arrKW[i].keyword] = 1;
		} else {
		   cKeywords[arrKW[i].keyword]++;
		}
		if (cKeywords[arrKW[i].keyword] > options.settings.num) {
		   continue;
		}
		applyElActions(document.getElementById(arrKW[i].id), arrKW[i].url);
	}
	return false;
}

// html_entity_decode
function get_html_translation_table(table,quote_style){var entities={},hash_map={},decimal=0,symbol='';var constMappingTable={},constMappingQuoteStyle={};var useTable={},useQuoteStyle={};constMappingTable[0]='HTML_SPECIALCHARS';constMappingTable[1]='HTML_ENTITIES';constMappingQuoteStyle[0]='ENT_NOQUOTES';constMappingQuoteStyle[2]='ENT_COMPAT';constMappingQuoteStyle[3]='ENT_QUOTES';useTable=!isNaN(table)?constMappingTable[table]:table?table.toUpperCase():'HTML_SPECIALCHARS';useQuoteStyle=!isNaN(quote_style)?constMappingQuoteStyle[quote_style]:quote_style?quote_style.toUpperCase():'ENT_COMPAT';if(useTable!=='HTML_SPECIALCHARS'&&useTable!=='HTML_ENTITIES'){throw new Error("Table: "+useTable+' not supported');}
entities['38']='&amp;';if(useTable==='HTML_ENTITIES'){entities['160']='&nbsp;';entities['161']='&iexcl;';entities['162']='&cent;';entities['163']='&pound;';entities['164']='&curren;';entities['165']='&yen;';entities['166']='&brvbar;';entities['167']='&sect;';entities['168']='&uml;';entities['169']='&copy;';entities['170']='&ordf;';entities['171']='&laquo;';entities['172']='&not;';entities['173']='&shy;';entities['174']='&reg;';entities['175']='&macr;';entities['176']='&deg;';entities['177']='&plusmn;';entities['178']='&sup2;';entities['179']='&sup3;';entities['180']='&acute;';entities['181']='&micro;';entities['182']='&para;';entities['183']='&middot;';entities['184']='&cedil;';entities['185']='&sup1;';entities['186']='&ordm;';entities['187']='&raquo;';entities['188']='&frac14;';entities['189']='&frac12;';entities['190']='&frac34;';entities['191']='&iquest;';entities['192']='&Agrave;';entities['193']='&Aacute;';entities['194']='&Acirc;';entities['195']='&Atilde;';entities['196']='&Auml;';entities['197']='&Aring;';entities['198']='&AElig;';entities['199']='&Ccedil;';entities['200']='&Egrave;';entities['201']='&Eacute;';entities['202']='&Ecirc;';entities['203']='&Euml;';entities['204']='&Igrave;';entities['205']='&Iacute;';entities['206']='&Icirc;';entities['207']='&Iuml;';entities['208']='&ETH;';entities['209']='&Ntilde;';entities['210']='&Ograve;';entities['211']='&Oacute;';entities['212']='&Ocirc;';entities['213']='&Otilde;';entities['214']='&Ouml;';entities['215']='&times;';entities['216']='&Oslash;';entities['217']='&Ugrave;';entities['218']='&Uacute;';entities['219']='&Ucirc;';entities['220']='&Uuml;';entities['221']='&Yacute;';entities['222']='&THORN;';entities['223']='&szlig;';entities['224']='&agrave;';entities['225']='&aacute;';entities['226']='&acirc;';entities['227']='&atilde;';entities['228']='&auml;';entities['229']='&aring;';entities['230']='&aelig;';entities['231']='&ccedil;';entities['232']='&egrave;';entities['233']='&eacute;';entities['234']='&ecirc;';entities['235']='&euml;';entities['236']='&igrave;';entities['237']='&iacute;';entities['238']='&icirc;';entities['239']='&iuml;';entities['240']='&eth;';entities['241']='&ntilde;';entities['242']='&ograve;';entities['243']='&oacute;';entities['244']='&ocirc;';entities['245']='&otilde;';entities['246']='&ouml;';entities['247']='&divide;';entities['248']='&oslash;';entities['249']='&ugrave;';entities['250']='&uacute;';entities['251']='&ucirc;';entities['252']='&uuml;';entities['253']='&yacute;';entities['254']='&thorn;';entities['255']='&yuml;';}
if(useQuoteStyle!=='ENT_NOQUOTES'){entities['34']='&quot;';}
if(useQuoteStyle==='ENT_QUOTES'){entities['39']='&#39;';}
entities['60']='&lt;';entities['62']='&gt;';for(decimal in entities){symbol=String.fromCharCode(decimal);hash_map[symbol]=entities[decimal];}
return hash_map;}
function html_entity_decode(string,quote_style){var hash_map={},symbol='',tmp_str='',entity='';tmp_str=string.toString();if(false===(hash_map=this.get_html_translation_table('HTML_ENTITIES',quote_style))){return false;}
delete(hash_map['&']);hash_map['&']='&amp;';for(symbol in hash_map){entity=hash_map[symbol];tmp_str=tmp_str.split(entity).join(symbol);}
tmp_str=tmp_str.split('&#039;').join("'");return tmp_str;}
