currentelement = "";

$(document).ready(function(){
	
	//This section handles the initial setup and clearing of the search box default text on focusing and blurring
	$('.postcodeSearch input[type="submit"]').show();
	$('.postcodeSearch input[type="submit"]').css('background-image', 'url(/toyota/main/images/fl-btn-finding-a.gif)');	
	$('.postcodeSearch input[type="submit"]').attr("disabled","disabled");
	$('.postcodeSearch input[type="submit"]').css("cursor","default");	
	
	$('.postcodeSearch input[type="text"]').focus(function() {
        var value = $(this).val();
		if( value == 'Postcode / suburb') {
			$(this).val('');
		}
	});

	$('.postcodeSearch input[type="text"]').blur(function() {
		var value = $(this).val();
		if( value == '') {
        	$(this).val('Postcode / suburb');
		}
	});
	
	
	//This section handles the initial searches for a postcode
	var t = setTimeout('', 1000);
	var f = '';
	var fn = false;
	var fl = false;
	var action = {};
	var location = '';
	var dealer = '';

	action.MultipleDealers = {};
	action.HandleData = {};

	action.MultipleDealers.SuburbPostcode = function(l) {
		f = 'location';
        $(currentelement).parent().addClass('focused').append('<div class="results"><ul class="loading"></ul></div>');
		$.ajax({
	      url: '/toyota/main/actions/getPostcodeSuburbInfo',
		  data: 'suburbpostcode=' + l,
	      dataType: 'json',
	      error: function(XMLHttpRequest, textStatus, errorThrown) { action.HandleError('Please enter a valid postcode or suburb.'); },
	      success: function(data, textStatus) {
			if (textStatus === 'success') {
		  		action.HandleData.location(data);
			} else {
				action.HandleError('Please enter a valid postcode or suburb.');
			}
	      }
	    });
	};

	action.HandleData.location = function(data) {
		location = data;
		var locationLength = location.length;
		$(currentelement).parent().find('.results ul').removeClass('loading');
		for(i=0; i < locationLength; i++) {
			$(currentelement).parent().find('.results ul').append('<li rel="'+i+'">'+location[i].suburb+', '+location[i].postcode+' '+location[i].state+'</li>');
		}
                var list_height = $(currentelement).parent().find('.results ul').height();
		if (list_height >= 180) {
                        $(currentelement).parent().find('.results ul').css({'height': '180px', 'overflow': 'auto'}).addClass('overflown');
		}
		$(currentelement).parent().find('input[type="submit"]').attr("disabled","");
		$(currentelement).parent().find('input[type="submit"]').css("cursor","");	
                $(currentelement).parent().find('.results ul li').hover(
                        function() {
                                $(this).addClass('hover');
			},
			function() {
				$(this).removeClass('hover');
			}
		);
                $(currentelement).parent().find('.results ul li').click(function() {
			var e = this;
			var i = $(e).attr('rel');
			var text = $(e).text();
                        $(currentelement).val(text);
                        $(currentelement).parent().find('.results').remove();
			$(currentelement).parent().find('.suburb').val(location[i].suburb);
			$(currentelement).parent().find('.postcode').val(location[i].postcode);
                        $(currentelement).focus();
		});
	};

	action.HandleError = function(message) {
                $(currentelement).parent().find('.results ul').removeClass('loading');
                $(currentelement).parent().find('.results ul').append('<li>No results could be found. '+message+'</li>');
	}

        $('.postcodeSearch .btn.btn_go2').click(function(k) {
           currentelement = this;
        });

        $('.postcodeSearch input[type="text"]').keydown(function(k) {

		var kc = k.keyCode;
		switch(kc) {
			case 13:
				return false;
				break;
		}
	});

	$('.postcodeSearch input[type="text"]').keypress(function(k) {
		var kc = k.keyCode;
		switch(kc) {
			case 13:
				return false;
				break;
		}
	});

	$('.postcodeSearch input[type="text"]').keyup(function(k) {
		var kc = k.keyCode;
		switch(kc) {
			case 38:    //This is the key up key.  
                var st = $(this).parent().find('.results ul').scrollTop();
                var d = $(this).parent().find('.results ul li:last').attr('rel');
				if(d != null) {
                    var r = $(this).parent().find('.results ul li.hover').attr('rel');
					if(r != null) {
						r--;
						$(this).parent().find('.results ul li.hover').removeClass('hover');
						if(r < 0) {
                        	$(this).parent().find('.results ul li:last').addClass('hover');
						} else {
                        	$(this).parent().find('.results ul li[rel="'+r+'"]').addClass('hover');
						}
					} else {
                    	$(this).parent().find('.results ul li:last').addClass('hover');
					}
                    if($(this).parent().find('.results ul').hasClass('overflown')) {
                        var p = $(this).parent().find('.results ul li.hover').position();
						if (st > 0) {
                        	var pt = st - $(this).parent().find('.results ul li.hover').outerHeight();
							$(this).parent().find('.results ul').scrollTop(pt);
						} else {
							$(this).parent().find('.results ul').scrollTop('0');
						}
					}
				}
				break;
			case 40:  //This is the key down key.
	            var st = $(this).parent().find('.results ul').scrollTop();
	            var d = $(this).parent().find('.results ul li:last').attr('rel');
				if(d != null) {
                    var r = $(this).parent().find('.results ul li.hover').attr('rel');
					if(r != null) {
						r++;
						$(this).parent().find('.results ul li.hover').removeClass('hover');
						if(r > d) {
                            $(this).parent().find('.results ul li:last').addClass('hover');
						} else {
                            $(this).parent().find('.results ul li[rel="'+r+'"]').addClass('hover');
                    	}
					} else {
						$(this).parent().find('.results ul li:last').addClass('hover');
					}
                    if($(this).parent().find('.results ul').hasClass('overflown')) {
                    	var p = $(this).parent().find('.results ul li.hover').position();
						if (p.top > 120) {
                            var pt = st + $(this).parent().find('.results ul li.hover').outerHeight();
                            $(this).parent().find('.results ul').scrollTop(pt);
						} else {
                            $(this).parent().find('.results ul').scrollTop('0');
						}
					}
				}
				break;
			case 13: //The enter key has been pressed.
                var d = $(this).parent().find('.results ul li:last').attr('rel');
				if(d != null) {
                    var r = $(this).parent().find('.results ul li:hover').attr('rel');
					if(r != null) {
						var i = r;
                        var text = $(this).parent().find('.results ul li[rel="'+r+'"]').text();
                        $(this).val(text);
                        $(this).parent().find('.results').remove();
                        $(this).parent().find('.suburb').val(location[i].suburb);
                        $(this).parent().find('.postcode').val(location[i].postcode);
                        $(this).focus();
					} else {
						$(this).parent().find('.results ul li:first').addClass('hover');
                        $(this).parent().find('.results ul').scrollTop('0');
					}
				}
				return false;
				break;
			default:
				var e = this;
				var i = $(e).val().length;
                $(this).parent().find('.results').remove();
                var l = $(this).val();
				clearTimeout(t);
                currentelement = this;
				if (i >= 3 && fn == false) {
					t = setTimeout(function(){
						fn = false;
                        $(this).parent().removeClass('focused');
                        $(this).parent().find('.results').remove();
                        action.MultipleDealers.SuburbPostcode(l);
					}, 1000);
				}
				break;
		}
	});


	//This section handles the submitting of the dealer search after a postcode has been chosen.
	$('.postcodeSearch').validate({
	
    rules: {
    	location: "required"
	},
  	submitHandler: function(form) {
      
	  $(currentelement).parent().find('input.btn').toggleClass('btn-override');

      var suburb = $(currentelement).parent().find('.suburb').val();
      var postcode = $(currentelement).parent().find('.postcode').val();

      $.ajax({
	      url: '/toyota/main/actions/getDealerDetails',
	      data: 'suburb=' + suburb + '&postcode=' + postcode,
	      dataType: 'json',
	      error: function() { action.HandleError('There has been an error on the server.'); },
	      success: function(data, textStatus) {
	    	  var q = "?"; 
              if(document.location.search != "") {
                q = document.location.search + "&";
              }
              var tagging = $(currentelement).parent().find('p.tag').text();
	    	  var dealer = data;
	    	  var dealerLength = dealer.length;
			  
	    	  if (dealerLength == 1) {
		    	  $(currentelement).parent().find('input[name="dealerPostcode"]').val(dealer[0].postcode);
		    	  $('input[name="dealerPostcode"]').val(dealer[0].postcode);
		    	  $('input[name="postcode"]').val(postcode);
		    	  $('input[name="suburb"]').val(suburb);
		    	  dcsMultiTrack('WT.cg_n', '', 'WT.cg_s', '', 'DCS.dcsqry', q+'DCSext.LPLink='+trackingType+tagging);
		    	  setTimeout(function() { 
                    form.submit(); 
                  }, 1000);
	    	  } else {
					  $(currentelement).parent().find('input.btn').toggleClass('btn-override');
                      /*$(currentelement).parent().find('input.btn').css({'background-position': '0 0 !important'});*/
                      $('.dealer-popup').remove();
		    		  $('body > div').append('<div class="dealer-popup"></div>');
		    		  $('.dealer-popup').append('<h4>Select the dealership you would prefer:</h4>');
		    		  $('.dealer-popup').append('<div class="close">Close</div>');
		    		  $('.dealer-popup .close').click(function() {
		    			  $('.dealer-popup').remove();
		    		  });
		    		  $('.dealer-popup').append('<div class="dealers"></div>');
		    		  $('.dealers').append('<ol></ol>');
		    		  if (dealerLength != 1) {
			    		  for(p = 0; p<dealerLength; p++) {
			    			  $('.dealers ol').append('<li class="dealer"><label>'+dealer[p].dealerName+'<br />'+dealer[p].suburb+' '+dealer[p].postcode+'</label><div class="inputs"><input type="radio" name="dealerChoice" class="radio" rel="'+p+'" /></div></li>')
			    		  }
					  }
		    		  var top = $(window).scrollTop();
		    		  $('.dealer-popup').css('top', top + 137);
			    	  $('.dealers ol input').click(function() {
			    		  var e = this;
			    		  var r = $(e).attr('rel');
			    		  $(currentelement).parent().find('input[name="dealerPostcode"]').val(dealer[r].postcode);
	    		    	  $('input[name="dealerPostcode"]').val(dealer[r].postcode);
	    		    	  $('input[name="postcode"]').val(postcode);
	    		    	  $('input[name="suburb"]').val(suburb);

			    	  });
			    	  $('.dealer-search-results li.dealer:first input').click();
		    		  $('.dealer-popup').append('<input type="submit" value="Find" class="submit" />');
		    		  $('.dealer-popup input[type="submit"]').click(function() {
	    			  if($(currentelement).parent().find('input[name="dealerPostcode"]').val() != '') {
	    				  $('.dealer-popup .error').remove();
	    				  $('.dealer-popup input[type="submit"]').css({'background-position': '0 -20px'});
	    		    	  dcsMultiTrack('WT.cg_n', '', 'WT.cg_s', '', 'DCS.dcsqry', q+'DCSext.LPLink='+trackingType+tagging);
	    				  setTimeout(function() { 
	    					  
	                          form.submit(); 
	                        }, 1000);
	    			  } else {
	    	    		  $('.dealer-popup').append('<div class="error" style="color: red;">Please select a dealership.</div>');
	    			  }
	    		  });
	    	  }
	      }
	  });
      return false;
    }
  });
});