function getHostname(str) {
	var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
	if ((str.match(re))) 
		return str.match(re)[1].toString();
	else
		return str;
}

function stripos (f_haystack, f_needle, f_offset) {
    // *         example 1: stripos('ABC', 'a');
    // *         returns 1: 0
    var haystack = (f_haystack + '').toLowerCase();
    var needle = (f_needle + '').toLowerCase();
    var index = 0;

    if ((index = haystack.indexOf(needle, f_offset)) !== -1) {
        return index;
    }
    return false;
}

//regex selector for jquery
jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ? 
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

all_rules = new Array();
index	  = 0;

//parse JSON response
$(document).ready(function(){
	$.getJSON(json_url, 
	function(data) {})
	.success(function(data, textStatus, jqXHR) { 
		var temp = "";
		$.each(data.Rules, function(i,item){
			var client_id			= unescape(item.client_id).replace(/\+/g," ").replace(/\?/g,"\\\?");
			var internal_links		= unescape(item.internal_links).replace(/\+/g, " ").replace(/\?/g,"\\\?");
			var parent_url 			= unescape(item.parent_url).replace(/\+/g," ").replace(/\?/g,"\\\?");
			var site_href 			= unescape(item.site_href).replace(/\+/g," ").replace(/\?/g,"\\\?");
			var form_input			= unescape(item.form_input).replace(/\+/g," ").replace(/\?/g,"\\\?");
			var href_id				= unescape(item.href_id).replace(/\+/g," ").replace(/\?/g,"\\\?");
			var href_class			= unescape(item.href_class).replace(/\+/g," ").replace(/\?/g,"\\\?");
			var custom_key			= unescape(item.custom_key).replace(/\+/g," ").replace(/\?/g,"\\\?");
			var custom_value		= unescape(item.custom_value).replace(/\+/g," ").replace(/\?/g,"\\\?");
			var category 			= unescape(item.category).replace(/\+/g," ").replace(/\?/g,"\\\?");
			var google_code 		= unescape(item.google_code).replace(/\+/g," ").replace(/\?/g,"\\\?");

			all_rules[index] = new Array();
			all_rules[index]['client_id'] 			= client_id;
			all_rules[index]['internal_links'] 		= internal_links;
			all_rules[index]['parent_url'] 			= parent_url;
			all_rules[index]['site_href'] 			= site_href;
			all_rules[index]['form_input'] 			= form_input;
			all_rules[index]['href_id'] 			= href_id;
			all_rules[index]['href_class'] 			= href_class;
			all_rules[index]['custom_key'] 			= custom_key;
			all_rules[index]['custom_value']		= custom_value;
			all_rules[index]['category'] 			= category;
			all_rules[index]['google_code'] 		= google_code;
			index = index + 1;
		});
		
//-------------------------------------------------------
// parse the rules
//-------------------------------------------------------
		ext_link_array 	= new Array();
		ext_googlecode	= "";
		documents_gcode	= "";			//not working

		for (j=0;j<=index-1;j++)
		{
			switch (all_rules[j]['category'])
			{
				case "EXTERNAL":
					if (all_rules[j]['internal_links'].length > 0 && all_rules[j]['internal_links'] != undefined)
					{
						var temp_array = all_rules[j]['internal_links'].split(",");
						for (k=0;k<=temp_array.length-1;k++)
						{
							ext_link_array.push(temp_array[k]);
						}
						ext_googlecode = all_rules[j]['google_code'];
					}
					break;
				case "HREFREGEX":
					if (all_rules[j]['site_href'].length > 0 && all_rules[j]['site_href'] != undefined )	// not parent_URL specific
					{
						$('a:regex(href,'+all_rules[j]['site_href']+')')
						.data("parent_url", all_rules[j]['parent_url'])
						.data("site_href", all_rules[j]['site_href'])
						.data("form_input", all_rules[j]['form_input'])
						.data("google_code", all_rules[j]['google_code']);

						if ((typeof debug !== "undefined") && debug == true)
							$('a:regex(href,'+all_rules[j]['site_href']+')').removeClass('standard').addClass('external');
						$('a:regex(href,'+all_rules[j]['site_href']+')').click(function(e) {
							eval($(this).data("google_code").replace('%PAGEURL%',this.href));
							if ((typeof debug !== "undefined") && debug == true)
								e.preventDefault();	//uncomment to prevent following link for testing
						});
					}				
					break;					
				case "HREFMATCHPARENT":
					if (all_rules[j]['site_href'].length > 0 && all_rules[j]['site_href'] != undefined && all_rules[j]['parent_url'].localeCompare(location.href) == 0)	// parent_URL specific
					{
						$('a:regex(href,'+all_rules[j]['site_href']+')')
						.data("parent_url", all_rules[j]['parent_url'])
						.data("site_href", all_rules[j]['site_href'])
						.data("form_input", all_rules[j]['form_input'])
						.data("google_code", all_rules[j]['google_code']);

						if ((typeof debug !== "undefined") && debug == true)
							$('a:regex(href,'+all_rules[j]['site_href']+')').removeClass('standard').addClass('external');
						$('a:regex(href,'+all_rules[j]['site_href']+')').click(function(e) {
							eval($(this).data("google_code").replace('%PAGEURL%',this.href));
							if ((typeof debug !== "undefined") && debug == true)
								e.preventDefault();	//uncomment to prevent following link for testing
						});
					}				
					break;
 				case "FORMSNAMEPARENT":
					if (all_rules[j]['parent_url'].length > 0 && all_rules[j]['parent_url'] != undefined && all_rules[j]['parent_url'].localeCompare(location.href) == 0)
					{
						$('input[name="'+all_rules[j]['form_input']+'"]')
						.data("parent_url", all_rules[j]['parent_url'])
						.data("site_href", all_rules[j]['site_href'])
						.data("form_input", all_rules[j]['form_input'])
						.data("google_code", all_rules[j]['google_code']);
						if ($('input[name="'+all_rules[j]['form_input']+'"]').data("parent_url").localeCompare(location.href) == 0) //true
						{
							if ((typeof debug !== "undefined") && debug == true)
								$('input[name="'+all_rules[j]['form_input']+'"]').removeClass('standard').addClass('external');
							$('input[name="'+all_rules[j]['form_input']+'"]').click(function(e) {
								eval($(this).data("google_code").replace('%PAGEURL%',this.href));
							if ((typeof debug !== "undefined") && debug == true)
								e.preventDefault();	//uncomment to prevent following link for testing
							});
						}
					}				
					break;
				case "HREFCLASS":
					if (all_rules[j]['site_href'].length > 0 && all_rules[j]['site_href'] != undefined)
					{
						$("[href='"+all_rules[j]['site_href']+"']."+all_rules[j]['href_class'])
						.data("parent_url", all_rules[j]['parent_url'])
						.data("site_href", all_rules[j]['site_href'])
						.data("form_input", all_rules[j]['form_input'])
						.data("href_class", all_rules[j]['href_class'])
						.data("google_code", all_rules[j]['google_code']);
						if ((typeof debug !== "undefined") && debug == true)
							$("[href='"+all_rules[j]['site_href']+"']."+all_rules[j]['href_class']).removeClass('standard').addClass('external');
						$("[href='"+all_rules[j]['site_href']+"']."+all_rules[j]['href_class']).click(function(e) {
							eval($(this).data("google_code").replace('%PAGEURL%',this.href));
							if ((typeof debug !== "undefined") && debug == true)
								e.preventDefault();	//uncomment to prevent following link for testing
						});
					}	
					break;
 				case "CLASSIDPARENT":
					if (all_rules[j]['parent_url'].length > 0 && all_rules[j]['parent_url'] != undefined && all_rules[j]['parent_url'].localeCompare(location.href) == 0)
					{
						$("."+all_rules[j]['href_class']+"#"+all_rules[j]['href_id'])
						.data("parent_url", all_rules[j]['parent_url'])
						.data("site_href", all_rules[j]['site_href'])
						.data("form_input", all_rules[j]['form_input'])
						.data("form_input", all_rules[j]['form_input'])
						.data("href_id", all_rules[j]['href_id'])
						.data("href_class", all_rules[j]['href_class'])
						.data("google_code", all_rules[j]['google_code']);
						if ((typeof debug !== "undefined") && debug == true)
							$("."+all_rules[j]['href_class']+"#"+all_rules[j]['href_id']).removeClass('standard').addClass('external');
						$("."+all_rules[j]['href_class']+"#"+all_rules[j]['href_id']).click(function(e) {
							eval($(this).data("google_code").replace('%PAGEURL%',this.href));
							if ((typeof debug !== "undefined") && debug == true)
								e.preventDefault();	//uncomment to prevent following link for testing
						});
					}	
					break;
 				case "CUSTOMDATAPARENT":
					if (all_rules[j]['parent_url'].length > 0 && all_rules[j]['parent_url'] != undefined && all_rules[j]['parent_url'].localeCompare(location.href) == 0)
					{
						$('a:regex('+all_rules[j]['custom_key']+','+all_rules[j]['custom_value']+')')
						.data("parent_url", all_rules[j]['parent_url'])
						.data("site_href", all_rules[j]['site_href'])
						.data("form_input", all_rules[j]['form_input'])
						.data("google_code", all_rules[j]['google_code']);

						if ((typeof debug !== "undefined") && debug == true)
							$('a:regex('+all_rules[j]['custom_key']+','+all_rules[j]['custom_value']+')').removeClass('standard').addClass('external');
						$('a:regex('+all_rules[j]['custom_key']+','+all_rules[j]['custom_value']+')').click(function(e) {
							eval($(this).data("google_code").replace('%PAGEURL%',this.href));
							if ((typeof debug !== "undefined") && debug == true)
								e.preventDefault();	//uncomment to prevent following link for testing
						});
					}	
					break;					
				default:
					break;
			}
		}

//-------------------------------------------------------
// external link handler - below, as this handler is universal and run only once per page
//-------------------------------------------------------
		$('a').each(function(){
			theelement 	= $(this);
			thelink 	= $(this).attr('href');
			extlink		= true;	//external
			jQuery.each(ext_link_array, function() {
				if (this.localeCompare(getHostname(thelink)) == 0)	 //internal
				{
					extlink		= false;	//found internal matching link
				}
		   	});
			//internal links CANT have http(s)://, ftp, or mailto
			if (extlink === true && (stripos(thelink,"http://") !== false || stripos(thelink,"https://") !== false || stripos(thelink,"ftp://") !== false || stripos(thelink,"mailto:") !== false))
			{
				if ((typeof debug !== "undefined") && debug == true)
					theelement.removeClass('standard').addClass('external');
				// Manage clicks on external links
				theelement.click(function(e) {
					eval(ext_googlecode.replace('%PAGEURL%',this.href));
					if ((typeof debug !== "undefined") && debug == true)
						e.preventDefault(); 	//uncomment to prevent following link for testing
					//return false;
				});
			}
		});
	})
	.error(function(jqXHR, textStatus, errorThrown) { 
		console.log("ERROR: textStatus: " + textStatus);
		console.log("ERROR: errorThrown: " + errorThrown);
		console.log("ERROR: responseText: " + jqXHR.responseText);
	});
//	.complete(function() { alert("complete"); });
});
