var testMode = false;
/**
 * Search form class
 * @constructor
 * @returns {SearchForm}
 */
function SearchForm (){
    this.init();
};

SearchForm.categoryFields = ['category','product','service']; 
SearchForm.nameFields = ['name','phone','store'];

/**
 * Bind  preconfigured autocamplete
 * @param  {String} selector
 * @param {Object} options
 * @returns {JQuery}
 */
SearchForm.prototype.setAutocomplete = function(selector, options) {
    return $(selector).autocomplete(options.url, {
        delay: 100,
        extraParams: {
            name: function() {
                return $(selector).val();
            }
        },
        resultsClass: options.resultsClass || 'category-autocomplit',
        minChars: 3,
        formatItem: options.format|| function(item) {
            return item.name;
        },
        dataType: 'json',
        parse: function(data) {
            var parsed = [];
            $.each(data.data || [] , function(){
                parsed.push({
					data: this,
					value: this[options.name || 'name'],
					result:this[options.name || 'name']
                });
            });
            return parsed;
        }
    });
};

/**
 * Observe changes in fields and clean other
 * @param {String} selector
 * @param {Function} callback 
 * 	Called  for event target element 
 */
SearchForm.prototype.observeChanges = function(selector, callback) {
	var callback = callback || function(){};
	$(selector).bind('keyup change autocomplete', function(e){
		var el = $(this);
		if ($(this).val().length) {
			$(selector).each(function(){
				if ($(this).attr('id') != el.attr('id')) {
					$(this).val('');
				} else {
					callback.call(this, this);
				};
			});
		}
	});
};

SearchForm.unquote = function(str) {
	return str
		.replace(/&amp;/g,'&')
		.replace(/&quot;/g,'"')
		.replace(/&#039;/g,'\'')
		.replace(/&lt;/g,'<')
		.replace(/&gt;/g,'>');
};

/**
 * Init events
 */
SearchForm.prototype.init = function() {
	var self = this;
	this.lang = '/' + location.href.replace('://','').split('?')[0].split('/')[1].replace(/\//g,'');
	this.lang += this.lang.length>2?'/':'';
	this.observeChanges('#category, #name, #phone, #product, #service, #store', function() {
		$('#n-step-1').removeClass('e-empty');
		$("#category, #product, #service").removeAttr('selected');
		$("#category, #product, #service").removeClass('ac-notfound');
		if ($('#all-biz:checked').length) {
			$('#all-biz')
				.removeAttr('checked')
				.trigger('change');
			$('#category, #name, #phone, #product, #service, #store').removeClass('b-trigger-all');
		}
		
	});
	
	this.observeChanges('#zip, #city, #state', function() {
		$('#n-step-2').removeClass('e-empty');
		$('#city').removeClass('ac-notfound');
		$('#state').removeClass('ac-notfound');
		$('#city').removeAttr('selected');
	});
	
	$('#zip').bind('change keyup', function() {
		if (/\D/.test(this.value) || this.value.length > 5) {
			this.value = this.value.replace(/[^0-9]/g,'').substring(0,5);
		}
	});
	
	var step1_suggested_fields = SearchForm.categoryFields; 
	for(field_i in step1_suggested_fields) {
		this.suggest("#"+step1_suggested_fields[field_i], this.lang +'suggest/category/name/', {callback: function(text, url, selector) {
			$(selector).val(text);
			$(selector)
				.attr('selected', 'selected')
				.removeClass('ac-notfound')
				.trigger('change');
		}});
	}
    this.suggest('#city', 
    	function() {
    		var category = search_form.getCategory();
    		return self.lang +'suggest/city'+
    			(category.length>=3 
    				? '/by-category/'+encodeURIComponent(category) 
    				: '/by-name/'+encodeURIComponent($('#name').val()))
 				+'/name/';
    	}, {
    		callback: function(text) {
    			$('#city')
		        	.val(text)
		        	.attr('selected', 'selected')
		        	.trigger('change');
    		}
    	}
    );

    this.suggest('#state', this.lang +'suggest/state/name/',{
    	minlength: -1,
    	callback: function(text) {
	        $('#state')
	        .val(text.replace(/^.*\((.*)\)$/,'$1'))
	        .attr('selected', 'selected')
	        .trigger('change');
    	}
    });

    
    $('#all-biz').bind('click change', function(){
    	var $name = $('#name'); 
    	$('#n-step-1').removeClass('e-empty');
    	if (this.checked) {
    		$('#category, #phone, #product, #service, #store').val('').addClass('b-trigger-all');
    		$name.val($(this).val())
    		  .attr('readonly', 'readonly')
    		  .addClass('b-trigger-all');
    	} else {
    		$('#category, #phone, #product, #service, #store').removeClass('b-trigger-all');
    		$name.val('')
    		  .removeAttr('readonly')
    		  .removeClass('b-trigger-all');
    	}
    });
    
    $('#n-step-3').click(function(){ return self.submit.apply(self, arguments); });

    $('body, body *').live('keyup', function(event) { //"live", not "bind""
        if (event.keyCode == 13) {
            $('#n-step-3').trigger('click');
        }
    });

    $('.b-pw-item').click(function() {
    	$("#category, #name, #phone, #product, #service, #store").val('')
        $("#category")
        	.trigger('focus')
	       	.trigger('autocomplete', [{ 	       		
	       		searchString: SearchForm.unquote($(this).find('span').attr('title'))
	       	}]);
    });
    
    $('.b-error-message').click(function(){
    	$('.e-empty').removeClass('e-empty');
    });
    
    $('#b-frame .b-frame-text').click(function(){
    	try{
    		if ($.browser.msie) {
    			window.document.execCommand('Stop');
    			if (typeof window.stop == 'function') {
    				window.stop();
    			}
    		}else {
    			window.stop();	
    		}
    		$('#b-frame').addClass('hidden');
    	} catch(e) {}
    });
};


SearchForm.prototype.removeACBlock = function() {
	this.initTabIndexes();
	this.binded_suggests = new Array;	
	$('#ac-block').remove();
}

SearchForm.prototype.suggest = function(selector, url, options) {
	var options = options || {};
	var $element = $(selector);
	var callback = options.callback || function(text){ $element.val(text);};
	$element.bind('keyup autocomplete', function(e, params){
		var params = params || {};
		if (e.type == 'keyup' 
			&& '27'.indexOf(e.which) != -1 
		){
			this.removeACBlock();
			return;
		}  
		
		if (e.type == 'blur') {
			if ($element.timeOut) {
				window.clearTimeout($element.timeOut);
				return;
			}
		}
		if ($element.timeOut) {
			window.clearTimeout($element.timeOut);
		}
		var  searchString = params.searchString || $element.val().toString();
		$element.timeOut = window.setTimeout(function() {
			if (searchString.length >= (options.minlength || 3)) {
				if ($element.ajax && $element.ajax.abort) {
					$element.ajax.abort();
				}
				$element.addClass('ac_loading');
				$element.ajax = $.get(
					((typeof url == 'function') ? url() : url) + encodeURIComponent(searchString), 
					function(data) {
						$element.removeClass('ac_loading');
						if ($element.val().indexOf(searchString) == -1
							&& !params.searchString) {
							return;
						}
						if(data.length) {
							search_form.removeACBlock();
							var $div = $('<div id="ac-block"/>');
							$div.addClass('b-autocomplit');
							
							var img ='<img class="b-close" src="/static/img/close_ico.png" '+
                                'align="right" onclick="$(\'#ac-block\').remove();"/>';
							
							$div.html(img+data);
							$div.click(function(e){
								if (e.target && $(e.target).is('a')) {
									var $a = $(e.target);
									if ($a.attr('href') == "#"
										|| $a.is('.b-ac-item')
									) {
										search_form.removeACBlock();
										e.preventDefault();
										
										var val = SearchForm.unquote($a.attr('title'));
										callback.call(this, val, $a, selector);
										return false;
									}
								}
							});
 
							if ($div.find('.b-suggest-notfound').length) {
								$element.addClass('ac-notfound');
							} else {
								$element.removeClass('ac-notfound');
							}
							
							$element.parent().append($div);

							search_form.initTabIndexes();
							search_form.binded_suggests = new Array;							
						}
					}
				);
			}
		}, 200);
	});
};

/*
 * Get category parameter value (from on of the category fields (category/product/service/store))
 */
SearchForm.prototype.getCategory = function() {
	var val = '';
	for(i in SearchForm.categoryFields) {
	  val = $('#'+SearchForm.categoryFields[i]).val();
	  if(val.length>0) return val;
	}
	return '';
}

/*
 * Get name parameter value (from on of the name fields (name/phone))
 */
SearchForm.prototype.getName = function() {
	var val = '';
	for(i in SearchForm.nameFields) {
	  val = $('#'+SearchForm.nameFields[i]).val()
	  if(val.length>0) return val;
	}
	return '';
}

/**
 * Check and submit form 
 * @returns {Boolean}
 */
SearchForm.prototype.submit = function() {
	
    // cancel submit if focus is not on the inputs or not "submit button"
    if (!testMode) {
		if ($.browser.msie) {
			if(!($(document.activeElement).is("input") || $(document.activeElement).attr("id")=='n-step-3')) {
				return false;
			}
		} else {
		  if(!($("*:focus").is("input") || $("*:focus").attr("id")=='n-step-3')) {
			return false;	
		  }
		}
	}

    if (this.getCategory().toString().length < 3
    	&& this.getName().toString().length < 3
    ) {
        $('#n-step-1').addClass('e-empty');
        return false;
    }
        
    if ($('#category.ac-notfound, #product.ac-notfound, #service.ac-notfound').length) {
    	$('#n-step-1').addClass('e-empty');
    	return false;
    }

    var form = $('#index-search');
    
    
   	//if(!$(e.target).is('input, dd')) {
//   		e.preventDefault();
  // 	}    
    
    var name = $('#all-biz:checked').length ? 'ALL BUSINESSES' : $('#name').val();
    var phone = $('#phone').val();
    var store = $('#store').val();
    
    var phone_reg = /\+?1?[0-9 \-\(\)\*]{10}/;

    if( phone_reg.test(phone) ) {
    	phone = phone.replace(/[^\d]/g,'');
    	// cut "1" on the beginning (if needed) 
        if(phone.length > 10 && phone.charAt(0)=='1') {
            phone = phone.substr(1,10);    
        } else {
            phone = phone.substr(0,10);
        }    	
    } else {
    	phone = '';
    }

    if($('#phone').val().toString().length>0 && phone.length==0) {
        $('#n-step-1').addClass('e-empty');
        return false;   	
    }

    if (($('#city').val().toString().length < 3 
    		|| ($('#city').val().toString().length >= 3 && $('#city').is('.ac-notfound')))
    	&& !($('#zip').val().toString().length in {3:1, 5:1})
    	&& ($('#state').val().toString().length <2 ||
    			$('#state').val().toString().length > 2 && $('#state').is('.ac-notfound'))
    	&& $('#phone').val()==''
    ) {
        $('#n-step-2').addClass('e-empty');
        return false;
    }
    
    var category_val = encodeURIComponent( this.getCategory());
    switch(true)
    {
      case $('#category').val().toString().length >0: category_field = 'category'; break; 
      case $('#product').val().toString().length >0: category_field = 'product'; break;
      case $('#service').val().toString().length >0: category_field = 'service'; break;
      default: category_field = ''; break;
    }
    
    var url = this.lang +'search'+
        (this.getCategory().toString().length>=3 ? '/by-' + category_field + '/'+ category_val : (phone.length>0 ? '/by-phone/'+phone :  (store.length>0 ? '/by-store/'+encodeURIComponent(store) : '/by-name/'+encodeURIComponent(name) )) )
        +($('#zip').val()?'/by-zip/'+encodeURIComponent($('#zip').val()):'')
        +($('#city').val()?'/by-city/'+encodeURIComponent($('#city').val()):'')
        +($('#state').val()?'/by-state/'+encodeURIComponent($('#state').val()):'')
        +'/';
    
	location.href = url; //ie gif frize workground 
	if ($.browser.msie && $.browser.version < 9) {
		$('#b-frame .b-frame-frame').css({opacity: 0.7});
		$('#b-frame').css('height', $(document).height());
		if($.browser.version < 8){
			window.scrollTo(0,0);
		}
	};
	$('#b-frame').removeClass('hidden');
};

SearchForm.prototype.current_focused_element = null;
SearchForm.prototype.binded_suggests = new Array();
SearchForm.prototype.event2key = {'37':'left', '39':'right', '38':'up', '40':'down', '13':'enter', '27':'esc', '32':'space', '107':'+', '109':'-', '33':'pageUp', '34':'pageDown'};
SearchForm.prototype.suggest_names = [ 'b-suggest-categories', 'b-suggest-cities', 'b-suggest-states' ];

SearchForm.prototype.keyDownHandler = function(e) {
   	var tab_elements;
   	var suggest_opened = false;
   	for(suggest_name_i in search_form.suggest_names) {
   		if($('#index-search .' + search_form.suggest_names[suggest_name_i]).length) {
	   		tab_elements = $('#index-search .' + search_form.suggest_names[suggest_name_i]).find('a');
	   		suggest_opened = true;
	   	}
   	}
   	
   	if(suggest_opened) {
   			
   		var tab_elements_length = tab_elements.length;
   		
   		if ( tab_elements[0] ) {
   			text_for_key = $.browser.msie ? tab_elements[0].innerText : tab_elements[0].text;
   		}   		
   		
   		if( tab_elements[0] 
   		                 && text_for_key 
   		                 && $.inArray(text_for_key,search_form.binded_suggests)==-1 ) {
   		  search_form.binded_suggests.push(text_for_key);
   		  
   		  $(tab_elements).focus(function (e) { 
   			search_form.current_focused_element = this;
   		  });
   		}
   		
   	    k = search_form.event2key[e.keyCode || e.which];
   	    if(k == 'down' || k == 'right') {
   	    	current_index = tab_elements.index(search_form.current_focused_element);
   	    	new_index = current_index + 1;
   	    	new_index = (new_index >= tab_elements_length) ? 0 : new_index;
   	    	tab_elements.eq( new_index ).focus();
   	    	e.preventDefault();
   	    }
   	    if(k == 'up' || k == 'left') {
   	    	current_index = tab_elements.index(search_form.current_focused_element);
   	    	new_index = current_index - 1;
   	    	new_index = (new_index < 0) ? tab_elements_length-1 : new_index;
   	    	tab_elements.eq( new_index ).focus();
   	    	e.preventDefault();
   	    }
   	}
}

SearchForm.prototype.initTabIndexes = function() {
	   var tabindex = 1;
	   var css_selector = '#index-search input, a.b-ac-item, #n-step-3, .b-pw-items li';
	   $.each($(css_selector), function (i,element) {
		   $(element).attr("tabindex", tabindex++);
	   });
	   zip_tabindex = $('#zip').attr("tabindex");
	   state_tabindex = $('#state').attr("tabindex");
	   $('#zip').attr("tabindex",state_tabindex);
	   $.each($(css_selector), function (i,element) {
		   t = $(element).attr("tabindex");
		   if( t > state_tabindex && t < zip_tabindex ) {
		     $(element).attr("tabindex", t*1+1);
		   }
	   });
	   $('#state').attr("tabindex",state_tabindex*1 + 1);	
}

var search_form; 
	
$(function(){ //bind function on DomReady
   $('#category').focus();
   search_form = new SearchForm();
   
   search_form.initTabIndexes();
   $("#index-search").keydown(search_form.keyDownHandler);
});

function startSearch() {
	testMode = true;
	$('#n-step-3').trigger('click');
}

