jQuery.ajaxSetup({
    'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript"); }
});

function userIsAgent () {
  if (user['type'] == 'Agent' || user['type'] == 'FreeAgent') return true;
  return false;
}

// Shortlist controls

function addShortlistControls (format) {
  if (userIsAgent()) return false;
  jQuery('.favlink').each(function() {
    var property_id = jQuery(this).attr('id');
    if (property_id) {
      property_id = property_id.replace(new RegExp('favorite_'), '');
      if (user['shortlist'].include(property_id)) {
        jQuery(this).html(removeFromShortlistLink(property_id, format));
      } else {
        jQuery(this).html(addToShortlistLink(property_id, format));
      }
    }
  });
}

function addToShortlistLink (property_id, format) {
  var indicator = jQuery('<span />')
    .addClass('add')
    .html(translate['javascript.save_to_shortlist']);

  var link = jQuery('<a />')
    .attr('id', 'add_to_shortlist_link_' + property_id)
    .attr('href', '/shortlists/create/' + property_id + '?method=post')
    .addClass('button')
    .html(indicator)
    .bind('click', function() {
      jQuery(this).toggleClass('loading');
      indicator
        .toggleClass('add')
        .toggleClass('spin');
        
      if (format == 'js') {
        jQuery.ajax({type:'post', url:jQuery(this).attr('href'),
          error:function() {
            jQuery(this).toggleClass('loading');
            indicator
              .toggleClass('add')
              .toggleClass('spin');},
          success:function() {
            jQuery('#add_to_shortlist_link_' + property_id).replaceWith(removeFromShortlistLink(property_id, 'js'));}
        });
        return false;
      }
    });

  return link;
}

function removeFromShortlistLink(property_id, format) {
  var indicator = jQuery('<span />')
    .addClass('true')
    .html(translate['javascript.saved_in_shortlist']);

  var link = jQuery('<a />')
    .attr('id', 'remove_from_shortlist_link_' + property_id)
    .attr('href', '/shortlists/destroy/' + property_id)
    .addClass('undo')
    .html(translate['javascript.undo'])
    .bind('click', function() {
      
      jQuery(this).hide();
      indicator
        .toggleClass('true')
        .toggleClass('spin');
      
      if (format == 'js') {
        jQuery.ajax({type:'post', url:jQuery(this).attr('href'),
          error:function() {
            indicator
              .toggleClass('true')
              .toggleClass('spin');
            link.show();},
          success:function() {
            jQuery('#favorite_' + property_id + ' .favorite').replaceWith(addToShortlistLink(property_id, 'js'));}
        });
        return false;
      }
    });
    
  return jQuery('<div />')
    .addClass('favorite')
    .append(indicator)
    .append(link);
}

// Property enquiry controls

function addSimilarEnquiryPrompt () {
  jQuery('#enquiry_tell_about_similar_properties').click(function() {
    if (jQuery(this).is(':checked')) {
      var confirmed = window.confirm(translate['javascript.are_you_sure'] + "\n\n" + translate['javascript.similar_enquiry_checkbox_explanation']);
      if (!confirmed) jQuery('#enquiry_tell_about_similar_properties').attr('checked', false);
    }
  });
}

// Recording property stats

function recordPropertyExternalLink (property_id) {
  jQuery.ajax({url:"/property/external_url/" + property_id});
}

function addPropertyExternalLinkRecording () {
  jQuery('.external_property_link').click(function() {
    var result = jQuery(this).attr('id').match(/external_property_link_(\d+)/);
    if (result != null && result[1] != null) {
      recordPropertyExternalLink(result[1]);
    }
  })
}

function handleNewBuildCheckbox() {
  var wrapper = jQuery('#new_build_checkbox_wrapper'),
      checkBox = jQuery('#new_build');

  jQuery('#payment_schemes_dropdown').change(function () {
    if (jQuery(this).val() === '0') {
      wrapper.show();
    } else {
      checkBox.attr('checked', false);
      wrapper.hide();
    }
  }).change();
}

function handleLanguageSelector() {
  var selector   = jQuery('.language_selector'),
      popup      = jQuery('.language_selector_popup'),
      link       = jQuery('.language_selector .trigger'),
      forms      = popup.find('form'),
      popupTimer;

  popup.hide();

  selector.mouseenter(function (event) {
    event.preventDefault();
    clearTimeout(popupTimer);
    newpos = jQuery(document).width() - link.offset().left - Math.floor(link.width() * 1.5);
    popup.css('right', newpos);
    popup.show();
  });

  selector.mouseleave(function (event) {
    event.preventDefault();
    popupTimer = setTimeout(function () { popup.hide(); }, 400);
  });

  forms.append('<input type="hidden" name="remember" value="0">');

  jQuery('#remember_locale').change(function (e) {
    var value = this.checked ? '1' : '0';
    forms.find(':hidden').val(value);
  }).change();
}

jQuery(document).ready(function() {
  redirect_locale_if_required();
  addSimilarEnquiryPrompt();
  addPropertyExternalLinkRecording();
  handleNewBuildCheckbox();
  handleLanguageSelector();
});

// helpers

jQuery.fn.reorder = function() {
 
  // random array sort from
  // http://javascript.about.com/library/blsort2.htm
  function randOrd() { return(Math.round(Math.random())-0.5); }
 
  return(jQuery(this).each(function() {
    var $this = jQuery(this);
    var $children = $this.children();
    var childCount = $children.length;
 
    if (childCount > 1) {
      $children.remove();
 
      var indices = new Array();
      for (i=0;i<childCount;i++) { indices[indices.length] = i; }
      indices = indices.sort(randOrd);
      jQuery.each(indices,function(j,k) { $this.append($children.eq(k)); });
 
    }
  }));
}

