$(document).ready(function() {});

$.fn.getClient = function (p,q,l) {
	return this.each(function() {
		var parent = $(this);
		$.post(
			directory_api_url,
			{
				type: 'Client',
				vertical: vertical,
				servicecode: servicecode,
				header: header,
				country: country,
				state: state,
				city: city,
				zip: zip,
				quad: q,
				limit: l
			},
			function(json) {
				if (json.status) {
					var output = '<div class="directory">';
					output += '<div class="dir_header">';
					if (json.header) {
						output += '<h2>'+json.header+'</h2>';
					}
					if (zip) {
						output += '<div class="dir_geo">Zip <span>' + zip + '</span> <a href="#" onClick="$(\'#'+p+'\').changeGeo(\''+p+'\',\''+q+'\',\''+l+'\'); return false;">(change)</a></div>';
					}
					output += '</div>';
					output += '<div class="dir_body">';
					output += '<ul>';
					for(var i=0; i<json.data.length; i++) {
						output += '<li>';
						output += '<img src="' + json.data[i]['logoPath'] + '"/>';
						output += '<span class="dir_name">' + json.data[i]['companyCode'] + '</span>';
						output += '<span class="dir_distance">' + json.data[i]['dealerDistance']+ ' mi</span>';
						output += '<br/>';
						output += '<span class="dir_address">';
						if (json.data[i]['city']) {
							output += json.data[i]['city'] + ', ';
						}
						output += json.data[i]['state'];
						output += '</span>';
						output += '<br/>';
						output += '<a class="dir_link" href="' + json.data[i]['url'] + '" target="_blank">Find out more &raquo;</a>';
						output += '</li>';
					}
					output += '</ul></div></div>';
					parent.hide();
					parent.html(output);
					parent.slideDown('normal');
				}
			},
			'json'
		);
	});
}

$.fn.changeGeo = function(p,q,l) {
	return this.each(function() {
		var parent = $(this);
		var g = parent.find('.dir_geo span');
		if (g.html().length==5) {
			g.html('<input type="text" size="5" maxLength="5" value="'+g.html()+'"/>');
			g.children('input').keyup(function(e) {
				if (e.which==13) {
					var v = $(this).val();
					if (v.match(/\d{5}/g)!=null) {
						g.html(v);
						zip = v;
						parent.find('.dir_body').css('padding','30px').html('Loading...');
						parent.getClient(p,q,l);
					} else {
						alert('Please enter your 5-digit zip code.');
					}
				}
			});
		}
	});
}