var Engine = {
  init: function() {		
    $('.signup label, .where label, .add-area label').compactLabels();
    
    // ie7 fix
    $('label#where-label').css('z-index', 1);
    
    this.menuFix();
    this.searchOptions();
    this.contentNav();
    var obj = this;
    this.initAreaMap(this);
    this.countryDropdown();
  },

  menuFix: function(){
    $('.second-level li').hover(
      function(){
        $(this).addClass('hover');
      },
      function(){
        $(this).removeClass('hover');
      }
    )
  },
	
  searchOptions: function() {
    $('#search-menu').click(function(e) {
      e.preventDefault();
      $('#search-area-wrapper .second-row').slideDown("slow");
      $('#options-trigger').removeClass('more').addClass('fewer').html('<span>Fewer search options</span>');      
      $('ul.second-level li a').removeClass('current');
      $(this).addClass('current');
    })
    
    $('#options-trigger').toggle(
      function(){
        $(this).removeClass('more').addClass('fewer').html('<span>Fewer search options</span>');
        $('#search-area-wrapper .second-row').slideDown("slow");
      },
			
      function(){
        $(this).removeClass('fewer').addClass('more').html('<span>More search options</span>');
        $('#search-area-wrapper .second-row').slideUp("quick");
      }
    );
  },
  
  contentNav: function() {
    $('ul.subnav li.second-level span.menu-arrow').click(function() {
      var id =  $(this).parents('li.second-level').attr('id'); 
      if($(this).hasClass('open')) {
        $('ul.subnav ul.third-level-'+id).hide();
        $(this).removeClass('open')        
      } else {
        $('ul.subnav ul.third-level-'+id).show();
        $(this).addClass('open')                
      }         
    })
  },

  initAreaMap: function(obj) {
    $('div#search-area-wrapper div.map-area a.change').click(function(e){
      e.preventDefault();
      
      $(this).closest('div#search-area-wrapper').find('a.search-map').trigger('click');
    });
    
    $('div#search-area-wrapper div.map-area a.remove').click(function(e){
      e.preventDefault();
      
      var form     = $(this).closest('div#search-area-wrapper');
      var area     = form.find('div.map-area');
      var misc     = form.find('div.where');
      var surround = form.find('input.surround');
      
      area.find('input').remove();
      area.hide();
      misc.show();
      surround.val(1);
      misc.find('input').trigger('blur');
    });
        
    
    $('div#search-area-wrapper').bind('suburbSelect', function(e, suburbs, names){
      if(!suburbs.length)
        return;
      
      obj.mappingArea(suburbs, names, 'suburb');
    });
    
    $('div#search-area-wrapper').bind('regionSelect', function(e, region, name){
      if(!region)
        return;
      
      obj.mappingArea([region], [name], 'region');
    });
    
    $('div#search-area-wrapper').bind('stateSelect', function(e, state, name){
      if(!state)
        return;
      
      obj.mappingArea([state], [name], 'state');
    });
    
    $('form.search-form').submit(function() {
       var searchTerm = $('input[name="a4"]').val(); 
       
       if(!searchTerm && $('div.where').is(":visible")) {
         alert('Please enter a search term');
         return false;
       }
       
       return true;
    });

    $('div.area-desc a.remove-area').click(function(e) {
      e.preventDefault();
      $(this).parents('div.area-desc').remove();
      if($('div.area-desc a.remove-area').length == 1) {
        $('div.area-desc a.remove-area').remove();
      }
    });     
  },
  
  mappingArea: function(codes, names, type){
    var area     = $('div#search-area-wrapper div.map-area');
    var misc     = $('div#search-area-wrapper div.where');
    var surround = $('div#search-area-wrapper input.surround');
    
    area.find('input').remove();
    
    var fieldName;
    
    if(type == 'state'){
      surround.checked = false;
      fieldName = area.attr('class').match(/state-(\w+)/)[1];
      area.find('span.text').html(names[0]);
    } else if(type == 'region'){
      surround.checked = false;
      fieldName = area.attr('class').match(/region-(\w+)/)[1];
      area.find('span.text').html(names[0]);
    } else {
      surround.checked = true;
      fieldName = area.attr('class').match(/suburb-(\w+)/)[1];
      if(names.length > 3){
        area.find('span.text').html(''+names.length+' suburbs selected');
      } else {
        area.find('span.text').html(names.join(", "));
      }
    }
    
    $.each(codes, function(){
      area.append('<input type="hidden" name="'+fieldName+'[]" value="'+this+'" />');
    });
    
    area.show();
    misc.hide();
    misc.find('input[type="text"]').val('');
  },
  
  countryDropdown: function() {
    var dropDown = false;
    $('#header li.country').click(function() {
        $('#header div.country-links').slideDown('fast');
        $('#header div.country-links').show();
    });
    
    $('#header div.country-links').live('mouseover', function() {
        dropDown = true;
    });
    
    $('#header div.country-links').live('mouseout', function() {
        dropDown = false;
    });
    
    $('#header li.country').focusout(function() {
        if(!dropDown){
          $('#header div.country-links').slideUp('fast',function() {
          $('#header div.country-links').hide();
          });
        }   
    });            
  }
}

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

// DD_belatedPNG fix for IE6
if (typeof DD_belatedPNG !== 'undefined') {
  var PNG_fix_selectors = [
  'a.browse',
  '.property-module .image-container .badge',
  '#content .blog-post .image-container .badge-my',
  '#content .blog-post .image-container .video',
  '.scrollable-container-big .caption .tag',
  '.scrollable-container-big .tag',
  '.signup .myljhooker span',
  '.single-search-result a.browse',
  '.first-level li.residential a.current span'
  ];
  DD_belatedPNG.fix(PNG_fix_selectors.join(','));
}

function processResponse(response){
  if(response.match(/OK: (.*)/)){
    return { result: 'ok', message: response.match(/OK: (.*)/)[1] };
  } else if(response.match(/ERROR: (.*)/)){
    return { result: 'error', error: response.match(/ERROR: (.*)/)[1] };
  } else {
    return { result: 'unknown' };
  }
};

function standardResponse(response){
  var errSelector = (arguments.length > 1 && arguments[1]) ? arguments[1] : 'p.error';
  var msgSelector = (arguments.length > 2 && arguments[2]) ? arguments[2] : 'p.message';
    
  $(errSelector).hide();
  $(msgSelector).hide();
  
  var detail  = processResponse(response);

  if(detail.result == 'ok'){
    $(msgSelector).html(detail.message).show();
    return true;
  } else if(detail.result == 'error'){
    $(errSelector).html(detail.error).show();
    return false;
  } else {
    $(errSelector).html('An unknown error occurred').show();
    return false;
  }
};

function idResponse(response){
  var error   = $('p.error');
  var message = $('p.message');
  
  error.hide();
  message.hide();
  
  var detail  = processResponse(response);
  var info;
  
  if(detail.result == 'ok' && (info = detail.message.match(/([^\;]*); *ID: (.*)/))){
    message.html(info[1]).show();
    return info[2];
  } else if(detail.result == 'ok'){
    error.html('No identity returned when one expected');
    return false;
  } else if(detail.result == 'error'){
    error.html(detail.error).show();
    return false;
  } else {
    error.html('An unknown error occurred').show();
    return false;
  }
};

function redirectResponse(response, url){
  $('p.error').hide();
  $('p.message').hide();
  
  var detail  = processResponse(response);

  if(detail.result == 'ok'){
    window.location.href = ((url.match(/\?/)) ? url + '&message=' : url + '?message=') + encodeURIComponent(detail.message);
    return true;
  } else if(detail.result == 'error'){
    $('p.error').html(detail.error).show();
    return false;
  } else {
    $('p.error').html('An unknown error occurred').show();
    return false;
  }
};

var activityLevel = 0;

function showActivity(){
  activityLevel++;
  $('html').addClass('wait');
};

function hideActivity(){
  activityLevel--;

  if(activityLevel < 0)
    activityLevel = 0;
  
  if(activityLevel == 0)
    $('html').removeClass('wait');
};

jQuery(function(){
  $('body').ajaxStart(showActivity);
  $('body').ajaxStop(hideActivity);
  
  $('body').ajaxError(function(){
    $('p.error').html('An unexpected error was encountered').show();
  });
});
