(function($){ 
		var debug = {
			current_id: false,
			check: function ( id ){
				var ajax_options = {
					mode:'json',
					request:'check',
					id: debug.current_id || 0
				};
				$.get('/www/scripts/storelocator.php', ajax_options, debug.process_postcode, 'json');
			},
			process_postcode: function(data){
				if(!data.error){
					var json_options = {
						tg_format: 'json',
						postcode: data.postcode
					}
					var ajax_options = {
						url: 'http://6pp.kvdb.net/services/lookup',
						type: 'get',
						dataType: 'jsonp',
						jsonp:'jsonp',
						data: json_options,
						success: debug.process_jsonp,
						cache:false
					}
					debug.current_id = data.id;
					$.ajax(ajax_options);

				}else{
					window.location.href = '/cms/scripts/dealer_import.php?message=Het bestand is geimporteerd.';
				}
			},
			process_jsonp: function(data){
				var ajax_options = {
					mode:'json',
					request:'change',
					id: debug.current_id,
					status: (data.result[0] == undefined || data.result[0]['geo_lat'] == "") ? 1 : 2
				};
				$.get('/www/scripts/storelocator.php', ajax_options, debug.check, 'json');
			}
		}
	//debug.check();
	$.fn.storelocator = function(options) {
		var s = {
			codes: false,
			matched_codes: {
				codes: Array()
			},
			store_codes: function( data ){
				s.codes = data.codes;
				return;
			},
			get_codes: function(){
				var selected = new Array();
				$.each( $("fieldset.selector :checkbox:checked"), function(){ selected.push($(this).val()) })
				var ajax_options = {
					mode:'json',
					request:'store_postal_codes',
					time:new Date().getTime(),
					fields: $.toJSON(selected)
				};
				$.get('/www/scripts/storelocator.php', ajax_options, s.store_codes, 'json');
			},
			get_matches: function( postcode ){	
				s.matched_codes.codes = new Array();
				if(s.codes == undefined) {
					log('Geen resultaten gevonden, verfijn uw zoekopdracht a.u.b.');
					$('img.ajax-image').remove();
					return false;
				}else{
					var json_options = {
						tg_format: 'json',
						destination_postcodes: s.codes.join(','),
						per_page: 10
					}
					var ajax_options = {
						url: 'http://6pp.kvdb.net/services/distance',
						type: 'get',
						dataType: 'jsonp',
						jsonp:'jsonp',
						data: json_options,
						success: s.process_matched,
						cache:false
					}
					var postcode_regexp = new RegExp(/^\d{4}[\s-]?([a-zA-Z]{2})?$/);
					if( postcode.match( postcode_regexp ) ){
						json_options.start_postcode = postcode;
					}else{
						json_options.start_city = postcode;
					}
					log("");
					$.ajax(ajax_options);
					return false;
				}

			},
			process_matched: function( data ){

				if(data.result.distances){
					$.each(data.result.distances, (function(i){
						s.matched_codes.codes.push( {s:this.postcode,c:this.postcode2,d:this.distance,u:this.unit} );
					}));
					var selected = new Array();
					$.each( $("fieldset.selector :checkbox:checked"), function(){ selected.push($(this).val()) })					
					var ajax_options = {
						url: '/www/scripts/storelocator.php',
						type: 'get',
						dataType: 'json',
						cache: false,
						data: {
							mode:'json',
							request:'match_postal_codes',
							codes: $.toJSON(s.matched_codes.codes),
							time:new Date().getTime(),
							fields: $.toJSON(selected),
							land: $('select[name=land] option:selected').val()
						},
						success: function(data){
							if(data.dealers){
								$.each( data.dealers, function(i){
									options.target.append(
										'<tr><td>'+this.plaatsnaam+"</td><td>"
										// START TR VISIBLE
										+'<a href="javascript:void(0);"  id="dealer_'+this.id+'" class="dealer_click" title="'
										+this.naam
										+"\">"
										+this.naam
										+"</a></td><td>"
										+this.straat+" "+this.huisnummer+"<br />"
										+"</td><td class=\"services\">"
										+((this.fietsen) 			? '<img src="www/images/storelocator/fietsen.png" alt="Fietsen" title="Fietsen" /> ' : "" )
										+((this.scooters) 			? '<img src="www/images/storelocator/scooters.png" alt="Scooters" title="Scooters" /> ' : "" )
										+((this.online_winkel) 		? '<img src="www/images/storelocator/online_winkel.png" alt="Online winkel"  title="Online winkel" /> ' : "" )
										+((this.thuisbezorgen) 		? '<img src="www/images/storelocator/thuis_bezorgen.png" alt="Thuis bezorgen" title="Thuis bezorgen" /> ' : "" )
										<!-- +((this.eco_subsidie_actie) ? '<img src="www/images/storelocator/eco_subsidie.png" alt="Eco subsidie"  title="Eco subsidie" /> ' : "" ) -->
										<!-- +((this.tnt) 				? '<img src="www/images/storelocator/tnt.png" alt="TNT"  title="TNT" /> ' : "" ) -->
										+'</td></tr>'
										// END TR VISIBLE
										// START TR HIDDEN
										+'<tr class="hidden">'
										+'<td width="75">&nbsp;</td>'
										+'<td width="200"><strong>adresgegevens</strong><br />'
										+this.straat+" "+this.huisnummer+"<br />"
										+this.postcode+" "+this.plaatsnaam+"<br />"
										+this.land+"<br />"
										+(this.telefoonnummer ? this.telefoonnummer+"<br />" : "")
										+(this.faxnummer ? this.faxnummer+"<br />" : "")
										+(this.website ? '<a href="http://'+this.website.replace("http://","")+'" target="_blank">'+this.website.replace("http://","")+'</a><br />' : "")
										+(this.email ? '<a href="mailto:'+this.email+'">'+this.email+'</a><br />' : "")
										+'</td>'
										+'<td width="145"><strong>openingstijden</strong><br />'
										+"<span>ma.</span>"+this.ma+"<br />"
										+"<span>di.</span>"+this.di+"<br />"
										+"<span>wo.</span>"+this.wo+"<br />"
										+"<span>do.</span>"+this['do']+"<br />"
										+"<span>vr.</span>"+this.vr+"<br />"
										+"<span>za.</span>"+this.za+"<br />"
										+"<span>zo.</span>"+this.zo+"<br />"
										+'<td width="165"><strong>overigen</strong><br/>'
										+((this.overige_informatie) ? this.overige_informatie : "<em>geen informatie</em>")
										+"</td></td></tr>"
										// END TR HIDDEN

									);
								});
								$("table tr:nth-child(4n):not(.header)").addClass("odd");
								$("table tr:nth-child(2n):not(.header)").addClass("even");
								
							}
							options.target.slideDown(500, function(){
								obj.removeAttr("disabled");
							});
						}
					}
					$.ajax(ajax_options);
				}else if(data.result){
					log("Geen geldig postcode / plaatsnaam ingevoerd!");
				}else{
					log(data);
				}
				$('img.ajax-image').remove();
				return;
			},
			click_dealer: function(){
				$('tr.hidden').hide();
				$(this).parents('tr').next('tr.hidden').show();
				var ajax_data = {
					mode: 'update_dealer_count',
					id: $(this).attr('id').replace('dealer_','')
				};
				$.post('/www/scripts/koop_online.php', ajax_data);
			}
		};
		var default_options = {
			postcode: 'input[name="postcode"]',
			ajaximage: 'www/images/storelocator/ajax-loader.gif',
			laadtext: "Loading...",
			target: $('.store-table')
		};
		options = $.extend(default_options, options || {});
		$("a.dealer_click").live("click", s.click_dealer);
		$("fieldset.selector :checkbox").change( s.get_codes );

		return this.each(function() {
			obj = $(this);
			obj.removeAttr("disabled");
			log("Vul hierboven uw postcode of plaatsnaam in.");
			$(options.postcode).removeAttr("disabled");
			//$.post('/www/scripts/storelocator.php', {mode:'json', request:'store_postal_codes', time:new Date().getTime()}, s.store_codes, 'json');			
			s.get_codes();
			
			var zoek = (function( event ){
				if( $('img.ajax-image').length == 0){
					if( $(options.postcode).val().length >= 2 ){					
						$('<img class="ajax-image" src="'+options.ajaximage+'" alt="'+options.laadtext+'" /> '+options.laadtext).appendTo( options.target.parent() );
						options.target.slideUp(500, (function(){
							$("table tr:not(.header)").remove();
							s.get_matches.call(this, $(options.postcode).val() );
						}));						
					}else{
						log("U heeft minder dan 2 karakters ingevoerd.");
					}
				}else{
					log("Er is al een zoekopdracht bezig, een moment geduld a.u.b.");
				}
				return false;
			})			
			obj.click( zoek );
			$(options.postcode).keydown(function(event){
				if (event.keyCode == 13) { // enter 
					obj.trigger("click");
					return false;
				}
			});
		});
	}
	
	function log() {
		/*  
		if( window.console ) console.debug.apply( console, arguments );
		else alert( [].join.apply( arguments, [' '] ) );
		*/
		if($('p#log').length == 0) $('.store-table').before( $('<p id="log"></p>').hide().click(function(){$(this).hide()}));
		$('p#log').html( [].join.apply( arguments, [' '] ) ).show();
		
	}	
})(jQuery);


