// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};


/* dynamic toll-free numbers */

/* map code to tfn */
function DynTfn(url) {
	this.url = url;
	this.parseMap = function(data, code) {
		var lines = data.replace(/\r/g, "").split(/\n/g);
		lines.shift(); /* remove header line */
		for (var i=0; i<lines.length; i++) {
			var line = lines[i];
			var fields = line.split("|");
			if (fields[4] == code)
				return fields[2];
		}
	};
	this.getTfn = function(code, callback) {
		var parser = this.parseMap;
		var handler = function(data, textStatus) {
			var number = parser(data, code);
			if (number) {
				var first = number.substring(0, 3);
				var second = number.substring(3, 6);
				var third = number.substring(6);
				number = '1.' + first + '.' + second + '.' + third;
				callback(number.replace(/-/g, "."));
			} else {
				/* show hidden default number */
				$('.expert-tfn').css("visibility", "visible");
			} 
				
		};
		jQuery.get(url, handler, "text");
	};
	this.load = function(url, callback) {
		jQuery.get(url, callback, "text");
	}
	
}
var DTFN = new Object();

DTFN.init = function(queryKey, selector, mapUrl) {
	var url=String(window.location).toLowerCase();
	var uri=parseUri(url.toLowerCase());
	var code = uri.queryKey[queryKey];
	if (code){
		DTFN.showNumber(mapUrl, code, selector);	
	} else {
		//$('.mloContact').html('1.888.866.6702');
		$('.mloContact').html('');
	}
		
}
DTFN.showNumber = function(mapUrl, code, selector) {
	if (code !== undefined) {
		var tfn = new DynTfn(mapUrl);
		tfn.getTfn(code, function(number) {
			jQuery(selector).html(number);
			/* show custom number */
			$('.expert-tfn').css("visibility", "visible");
		});
	}
};

