//   LEGAL NOTICE
//   PATENT NOTE:  Patent Number  7,904,335 plus 2 patents pending 12/099,782 and 13/115,959
//   Contact Steve Crim stcrim@screencrafters.com   251-990-9498


// for real production comment out the debug_box and all the alert box

//ad network domains are seperated by spaces
var ads_domains 			= new String(" casalemedia.com zope.net winacarofyourchoice.com ");
var cleanslash				= false;
var client_ip 				= null;
var cookie_persistence_secs = 15;
var popNotOpenedYet 		= true;
var link 					= "";
var absolute_link 			= "";
var target 					= "";
var jQueryScriptOutputted 	= false;
var siteencore_on_link_only = true;
var counter					= 0;
var delete_cookie			= false;
var debug_box_on			= false;

var blockurls = new Array();

blockurls[0] = "http://disney.com";
blockurls[1] = "http://www.mazdaofdanvers.com/Schedule-Mazda-Service-Massachusetts.aspx";
blockurls[2] = "http://iraaudi.com/Schedule-Audi-Service-Massachusetts.aspx";
blockurls[3] = "http://www.fairhopeopen.com/siteencore_w_blocker/destination_page_without_a_new_window.html";
blockurls[4] = "http://www.fairhopeopen.com/siteencore_w_blocker/index.html#";
blockurls[5] = "http://www.fairhopeopen.com/siteencore_w_blocker/url_list.js";
blockurls[6] = "http://candsleads.com/1stc/BMWofAnnapolis/url_list.js";
blockurls[7] = "http://candsleads.com/1stc/BMWofAnnapolis/disney.htm#";
blockurls[8] = "http://bmwofannapolis.com/#";
blockurls[9] = "http://bmwofannapolis.com/Car-Loan-Pre-Approval.aspx";
blockurls[10] = "http://www.fairhopeopen.com/siteencore_w_blocker/#";
blockurls[11] = "http://realestate.nj.com/for-rent/";
blockurls[12] = "http://www.fairhopeopen.com/siteencore_w_blocker/index.html";
blockurls[13] = "#";
blockurls[14] = "javascript:void(0)";



addSiteEncoreScript('http://ns1.screencrafters.net/siteencore_w_blocker/json.php?question=ip&callback=getIP','head');

function siteencore_window() {

	if (!mobiledetection(navigator.userAgent||navigator.vendor||window.opera)) {

		if (document.cookie.indexOf("popopened3=") != -1) { popNotOpenedYet = false; }

		if(popNotOpenedYet) {

			if (/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent) || /Firefox/.test(navigator.userAgent)) {
				popwinOBJz = window.open('http://www.candsleads.com/1stc/HondaTurnersville/2ndchance/index.html', 'nameMe11',   'toolbar=1,menubar=1,scrollbars=1,status=0,location=1,resizable=1');
				var URL = window.location;
				if (window.detwin) {
					window.detwin.close();
					window.detwin = null;
				}
				window.detwin = window.open(URL,  'mainwindow');
				window.detwin.focus();
				window.detwin.close();
			}
			else if (/iPad/.test(navigator.userAgent) || /Safari/.test(navigator.userAgent)) {
				popwinOBJz = window.open('http://www.candsleads.com/1stc/HondaTurnersville/2ndchance/index.html', 'nameMe11',   'toolbar=1,menubar=1,scrollbars=1,status=0,location=1,resizable=1');
				window.focus();
			}
			else {
				popwinOBJz = window.open('http://www.candsleads.com/1stc/HondaTurnersville/2ndchance/index.html', 'nameMe11',   'toolbar=1,menubar=1,scrollbars=1,status=0,location=1,resizable=1');
				popwinOBJz.blur();
			}
			popNotOpenedYet = false;

			var today = new Date();
			today.setTime(today.getTime()); 
			
			var expiry_date = new Date(today.getTime() + (cookie_persistence_secs * 1000)); 

			document.cookie = "popopened3=1;expires=" + expiry_date.toGMTString();
		}
	}
	else {
		//alert("do nothing for mobile");
	}

}

// initialized by callback at loading time
function getIP(json){
	client_ip = json.Body.msg;

	if (document.cookie.indexOf("popopened3=") != -1) {
		var debug_msg = "Cookie was found. New window should not be opened";
	}
	else {
		var debug_msg = "Cookie was not found. New window should be opened";
	}

	// for real production comment out the debug_box
	if (client_ip == '98.90.75.179' || debug_box_on) {
		debug_box('T', debug_msg);
	}

	document.onclick = function()
	{
		//for ie only
		if (window.event) {

			if (typeof window.event.srcElement.parentElement.href == 'undefined') {
				if (typeof window.event.srcElement.href == 'undefined') {
				//client clicked on non link
					link = '';
					target = '';
					//alert("not blocked because client clicked on a non link area so a new windows was opened. Note there is no destination page to go to.");
				}
				else {
				//client clicked on a link
					link = window.event.srcElement.href;
					target = window.event.srcElement.target;
				}
			}
			else {
				//client clicked on an image with link
				link = window.event.srcElement.parentElement.href;
				target = window.event.srcElement.parentElement.target;
			}

			if (link) {
				newwindow = false;
				if (target) {
					target = new String(target).toLowerCase();
					if (target == '_blank' || target == '_new') {
						newwindow = true;
					}
				}

				//domain = new String(link).toLowerCase().getDomain();
				//if (ads_domains.indexOf(' ' + domain + ' ') == -1 && !newwindow) {
				//alert("clicked url: " + link);
				if (blockurls.hasURL(link) > -1) {
					//alert(link + "\n is in the blocked list so no new windows was opened");

				}
				else {
					//if (!delete_cookie) 
					siteencore_window();
					//alert(link + "\n is not in the blocked list so a new windows was opened");
				}
			}
			else {
				if (!siteencore_on_link_only) {
					//if (!delete_cookie) 
					siteencore_window();
				}
			}

		}
	} // end document onclick

	if (!/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
		//alert("not ie");
		initJQuery();
	}

}

function initJQuery() {
    counter++;
    
    //alert("for not ie only " + counter);
    //if the jQuery object isn't available
    if (typeof(jQuery) == 'undefined') {
    
    
        if (! jQueryScriptOutputted) {
            //only output the script once..
            jQueryScriptOutputted = true;
            
            // http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
            addSiteEncoreScript('http://code.jquery.com/jquery-latest.pack.js','head'); 

        }
        setTimeout("initJQuery()", 50);
    } else {

	    //alert("for not ie only " + counter);
                        
        $(function() {  
            //do anything that needs to be done on document.ready
			$("a").each(function(index, element){
				if ($(element).attr("id") == '') {
					//alert("index " + index);
					$(element).attr("id", 'encoreid_' + index);
				}
				
				//alert('current id:' + $(element).attr("id") + " target=" + $(element).attr("target"));
			});


	    //alert("inside non ie function " + counter);

			jQuery('a').click(function() {
				//alert(this.id);

				var $this = $(this);
				var href = $this.attr('href');

				//alert(this.id + ' testing now 1 clicked url: ' + href);
				link = href;
				target = $this.attr('target');


				var current_dir = getDirPath(window.location.href);

				link_ob = new String(link);

				if (/http/i.test(link_ob.substr(0,4))) {}
				else if (link == '#') {
					if (window.location.href.substr(window.location.href.length-1,1) == '#') {
						absolute_link = window.location.href;
					}
					else {
						absolute_link = window.location.href + "#";
					}
				}
				else {
					absolute_link = current_dir + link;
				}

				//alert("the link clicked was " + link);

				newwindow = false;
				if (target) {
					target = new String(target).toLowerCase();
					if (target == '_blank' || target == '_new') {
						newwindow = true;
					}
				}

				//domain = new String(link).toLowerCase().getDomain();
				//if (ads_domains.indexOf(' ' + domain + ' ') == -1 && !newwindow) {
				
				//alert("clicked url: " + link);
				
				if (blockurls.hasURL(link) > -1 || blockurls.hasURL(absolute_link) > -1) {
					//alert(link + "\n is in the blocked list so no new windows was opened");

				}
				else {
					//if (!delete_cookie) 
					//alert(link + "\n is not in the blocked list so a new windows should be opened");
					siteencore_window();
					//alert(link + "\n is not in the blocked list so a new windows was opened");
				}
				
				
			});


        });
    }
            
}

function getDirPath(URL) {
    var result = unescape(URL.substring(0,(URL.lastIndexOf("/")) + 1))
    return result
}

function rtrim_slash(str) {
	return str.replace(/\/+$/, '');
}

function addSiteEncoreScript(script_name, head_or_body) {
	var script_position = document.getElementsByTagName(head_or_body)[0];
	var js = document.createElement('script');
	js.setAttribute('type','text/javascript');
	js.setAttribute('src',script_name);
	script_position.appendChild(js);
}

function debug_box(id, msg) {
	var newdiv = document.createElement('div');
	newdiv.setAttribute('id', "debug_div" + id);
	newdiv.style.width = 700;
	newdiv.style.height = 20;
	newdiv.style.position = "absolute";
	newdiv.style.right = 5;
	newdiv.style.bottom = 5;
	newdiv.style.background = "#cccccc";
	newdiv.style.border = "1px solid #000";
	newdiv.innerHTML = "Debug: cookie expires in " + cookie_persistence_secs + " secs. <a href=\"javascript:void(0)\" onClick=\"deleteAllCookies();\">delete cookies</a> <a href=\"#\" onClick=\"\alert(client_ip);\">ip.</a> " + msg;
	document.body.appendChild(newdiv);	
}

function mobiledetection(a) {

	if (/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))
	{
		return true;
	}
	else {
		return false;
	}

}

function deleteAllCookies() {
	//delete_cookie = true;
	var cookies = document.cookie.split(";");
	for (var i = 0; i < cookies.length; i++) {
		var cookie = cookies[i];
		var eqPos = cookie.indexOf("=");
		var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
		document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
		alert("cookie: " + cookie + " was deleted");
	}
}

String.prototype.getHostname = function() {
	var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
	return this.match(re)[1].toString();
}

String.prototype.getDomain = function(){
	var hostname = this.getHostname();
	return (m = hostname.match(new RegExp("([a-z,A-Z,0-9,\-]+\.[a-z,A-Z]{2,6})$") )) ? m[1] : false;
}

Array.prototype.hasURL = function(v) {
	v = rtrim_slash(v);
	if (!cleanslash) {
		cleanslash = true;
		for (i=0; i<this.length; i++) {
			this[i] = rtrim_slash(this[i]);
		}
	}
	for (i=0; i<this.length; i++) {
		if (this[i]==v) return i;
	}
	return -1;
} 

//-->
