// 
// © 2010 - Infinity 
// By the CV Web Posse dudes
// |\___/|\___/|
// |     |     |
// |     |     |
// \-----|-----/
//  \    |    /
//   \   |   /
//    \__|__/
// 

var __address = null;
var __map = null;
var __location = null;
function _load(hash) {
  if(hash) {
    if($.browser.msie) {
      hash = encodeURIComponent(hash);
    }
    $("#" + hash).load();
  }
}

function doDirectoryTitle() {
  if ( __location == 'directory-form' ) {
    $('#main-directory .title h2').text('Directory Sign-Up');
  } else {
    $('#main-directory .title h2').text('Business Directory');
  }
  $('#main-directory').attr('class', __location);
  Cufon.replace('#main-directory .title h2');
}

jQuery(function($){
  // JQuery Unserialize v1.0 by James Campbell
  $.unserialize = function(Data){
    var Data = Data.split("&");
    var Serialised = new Array();
    $.each(Data, function(){
      var Properties = this.split("=");
      Serialised[Properties[0]] = Properties[1];
    });
    return Serialised;
  };
  
  $('#button-directory-form').attr('href','#directory-form');
  
  $('#button-directory').click(function(e){
    $('#support, #content').slideUp();
    if ( __location == 'directory-form' ) {
      $('#directory-form').slideUp();
      $('#main-directory .internal').slideDown();
    } else {
      $('#directory-form').css('display','none');
      $('#main-directory .internal').css('display','block');
      $('#main-directory').slideDown();
      $('#main-directory #directory-wrapper').load('/dir/',ajax_callback);
    }
    __location = 'directory';
    doDirectoryTitle();
    return false;
  });
  
  $('#button-directory-form, #main-directory .title a').live('click', function(e){
    if ( $(this).parents('#main-directory.directory-form').size() > 0 ) {
      $.fn.colorbox({
        href: '/dir/contact',
        innerWidth: 300,
        innerHeight: 400,
        onComplete: handleContactForm
      })
    } else {
      $('#support, #content').slideUp();
      if ( __location == 'directory' ) {
        $('#main-directory .internal').slideUp();
        $('#directory-form').slideDown();
      } else {
        $('#main-directory .internal').css('display','none');
        $('#directory-form').css('display','block');
        $('#main-directory').slideDown();          
      }
      __location = 'directory-form';
      doDirectoryTitle();
    }
    return false;
  });
  
  $('#main-directory .internal').load('/dir/?noajax=true', function(){
    $("#search").ajaxForm({
      target: '#directory-wrapper', 
      success: ajax_callback,
      beforeSerialize: function($form) {
        $.each({
          search: 'I am looking for',
          search_location: 'city/town'
        },function(k,v){
          if ( $('#search input[name=' + k + ']').val() == v ) {
            $('#search input[name=' + k + ']').val('');
          }
        })
      },
      beforeSubmit: function(data) { 
        $.each({
          search: 'I am looking for',
          search_location: 'city/town'
        },function(k,v){
          if ( $('#search input[name=' + k + ']').val() == '' ) {
            $('#search input[name=' + k + ']').val(v);
          }
        })
      }
    });
    $("#search input[type=text]").each(function(){
      $(this).autofill({
        value: this.value
      });
    })
    ajax_callback();
  });
  
  $('#main-directory .pager a, .back-to').live('click',function(e){
    var href = this.href;
    if ( !href.match(/(\/$|\?.*$)/) ) {
      href += "/";
    }
    $('#main-directory #directory-wrapper').load((href.match(/^http/) ? href : '/dir/' + href), function(){
      ajax_callback();
    });
    e.preventDefault();
  });
  
  $('#main-directory .internal h2 a, #main-directory .meta a.logo').live('click',function(e){
    var href = this.href;
    if ( !href.match(/(\/$|\?.*$)/) ) {
      href += "/";
    }

    $('#main-directory #directory-wrapper').load(href,function(){
      ajax_callback();
      $('#business').
        prepend('<a href="/dir/" class="back-to">&lt; Back to listings</a>').
        append('<a href="/dir/" class="back-to">&lt; Back to listings</a>');
      $('.google-map').click(function(){
        set_address($(this).attr('rel'));
      }).colorbox({
        inline:true, 
        innerWidth: 500, 
        innerHeight: 500, 
        href: '#map',
        onComplete: showMap,
        onCleanup: hideMap
      });
    });
    e.preventDefault();
    return false;
  });
  
  $('#event-map').click(function(){
    var obj = $.unserialize(this.href);
    set_address( obj.hq + " near " + obj.hnear );
  }).colorbox({
    inline:true, 
    innerWidth: 500, 
    innerHeight: 500, 
    href: '#map',
    onComplete: showMap,
    onCleanup: hideMap
  });
})

function ajax_callback() {
  $('.contact-link').colorbox({
    innerWidth: 300,
    innerHeight: 400,
    onComplete: handleContactForm
  });
}

function handleContactForm() {
  $('form.contact').prepend("<p style='display: none' id='contact-status'></p>");
  $('form.contact').ajaxForm({
    dataType: 'json', 
    clearForm: true, 
    success: function(data) {
      showMessage(data, true);
    },
    error: function(obj) {
      data = jQuery.parseJSON(obj.responseText);
      showMessage(data);
    }
  });
}

function showMessage(data, close) {
  close = close || false
  jQuery('#contact-status').text(data.message).removeClass().addClass(data.status).slideDown(function(){
    window.setTimeout(function(){
      jQuery('#contact-status').slideUp();
      if ( close ) {
        jQuery.fn.colorbox.close()
      }
    }, 1500);
  })
}


function set_address(a) {
  __address = a;
}

function get_address() {
  return __address;
}

function hideMap() {
  $('#map').css('display','none');
}
function showMap( _address ) {
  $('#map').css('display','');
  var address = _address ? _address : get_address();
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode(
    {
      'address': address,
      'partialmatch': true
    }, 
    geocodeResult
  ); 
}

function geocodeResult(results, status) {
  if (status == 'OK' && results.length > 0) {
    var options = {
          zoom: 17,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    if ( !__map ) {
      __map = new google.maps.Map(document.getElementById("map"), options);
    }
    __map.fitBounds(results[0].geometry.viewport);
    __map.setCenter(results[0].geometry.location);
    google.maps.event.addListener(__map, 'tilesloaded', function() {
      var marker = new google.maps.Marker({
        position: __map.getCenter(),
        map: __map
      })
      google.maps.event.clearListeners(__map, 'tilesloaded');
    });
  }
}