// Set locale's beginning of week to Sunday, instead of Monday
Date.firstDayOfWeek = 0;

Function.prototype.bind = function(object) {
  var __method = this;
  return function() {
    return __method.apply(object, arguments);
  }
}

//prevent js errors in browsers w/o firebug when console.log accidentally left in the code
if (!window.console) {
  window.console = {
    log: function() {
      //alert(arguments[0]);
    }
  }
}

function addCommas(nStr) {
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

$.SetImpromptuDefaults({
  show: 'fadeIn',
  opacity: 0.7,
  overlayspeed: 'fast'
});

//setup a global ajax error handler
$(function() {
  $(window).ajaxError(function (event, xhr, ajaxOptions, errorThrown) {
    //for full html, grab just the body
    var body = xhr.responseText.replace(/^[\s\S]*<body[\s\S]*?>/gi, "").replace(/<\/body>[\s\S]*$/gi, "");
    ModalController.system_error(body);
  });
});

$.originalAjax = $.ajax;

$.railsAjax = function(s) {
  s = jQuery.extend(true, {}, jQuery.ajaxSettings, s);

  var type = s.type.toLowerCase();

  if (s.processData && (type == 'delete' || type == 'put' || type == 'post')) {
    if (s.data && typeof s.data != "string")
      s.data = $.param(s.data);

    var rails_data = {};

    if (window.AUTHENTICITY_TOKEN && (!s.data || (s.data.indexOf('authenticity_token=') < 0)))
      rails_data.authenticity_token = window.AUTHENTICITY_TOKEN;

    if (type == 'delete' || type == 'put') {
      s.type = 'POST';

      if (!s.data || (s.data.indexOf('_method=') < 0))
        rails_data._method = type;
    }

    rails_data = $.param(rails_data);

    if (rails_data)
      s.data = (s.data) ? [s.data, rails_data].join('&') : rails_data;
  }

  return $.originalAjax(s);
}

$.ajax = $.railsAjax;


// Replaces the contents with a spinner
$.fn.spinnerReplace = function() {
  return this.html('<img src=\'/images/spinner.gif\' class=\'spinner\'/>');
};

$.fn.spinner = function() {
  //  note: we hide the current contents - there are situations where the content must stick around until explicitely replaced
  // eg. FileUpload forms need the form to persist for some time period to do its work
  return this
    .children().hide().end()
    .prepend('<img src=\'/images/spinner.gif\' class=\'spinner\'/>');
}

$.fn.deSpinner = function() {
  return this
    .find('.spinner').remove().end()
    .children().show();
}


$.fn.ajaxLink = function(target, options) {
  options = $.extend({}, $.fn.ajaxLink.defaults, options)

  if (target) {
    options.success = options.success || function(data) {
      $(target).html(data);
    };

    options.beforeSend = options.beforeSend || function() {
      $(target).spinner();
    };

    if (!options.error) {
      var starting_html = $(target).html();
      options.error = function() {
        $(target).html(starting_html);
      };
    }
  }

  //allow binding as livequery if requested
  var handler = (options.livequery) ? 'livequery' : 'bind';

  this[handler]('click', function(e) {
    //use the href of the link as the target if not specified in the options
    var link_specific_options = $.extend({}, options)
    if (!link_specific_options['url'] && this.href) {
      link_specific_options['url'] = this.href;
    }

    $.ajax(link_specific_options);
    return false;
  });

  return this;
}

$.fn.ajaxLink.defaults = {
  livequery: false
}

$.fn.toggler = function(options) {
  options = $.extend({}, $.fn.toggler.defaults, options);

  this.click(function() {
    var $clickedToggle = $(this).parents(options.toggleContainer).eq(0);
    if ($clickedToggle.parents(options.accordionContainer).length > 0) {
      if ($clickedToggle.hasClass(options.closedToggleClass)) {
        var openToggleSelector = '.' + options.openToggleClass;
        var $openToggle = $clickedToggle.parents(options.accordionContainer).eq(0).find(openToggleSelector);
        if ($openToggle.hasClass(options.openToggleClass) || $openToggle.hasClass(options.closedToggleClass)) {
          $openToggle.toggleClass(options.openToggleClass);
          $openToggle.toggleClass(options.closedToggleClass);
        }
        $openToggle.find(options.togglee).eq(0).slideToggle('fast');
      } else {
        return false;
      }
    }
    if ($clickedToggle.hasClass(options.openToggleClass) || $clickedToggle.hasClass(options.closedToggleClass)) {
      $clickedToggle.toggleClass(options.openToggleClass);
      $clickedToggle.toggleClass(options.closedToggleClass);
    }
    $clickedToggle.find(options.togglee).eq(0).slideToggle('fast');
    return false;
  });

  return this;
}

$.fn.toggler.defaults = {
  togglee: '.togglee',
  toggler: '.toggler',
  toggleContainer: '.toggle',
  openToggleClass: 'open_toggle',
  closedToggleClass: 'closed_toggle',
  accordionContainer: '.accordion'
};

$.fn.popups = function(options) {
  options = $.extend({}, $.fn.popups.defaults, options);
  if (!options.ajaxSettings)
    options.ajaxSettings = {};
  if (!options.ajaxSettings.data)
    options.ajaxSettings.data = {};
  if (!options.ajaxSettings.data.format)
    options.ajaxSettings.data.format = 'popup';

  this.cluetip(options);

  return this;
}

$.fn.popups.defaults = {
  showTitle: false,
  titleAttribute: 'dummy',
  positionBy: 'mouse',
  width: '651px',
  cluetipClass: 'marker-popup',
  sticky: true,
  activation: 'click',
  dropShadow: false,
  cluezIndex: 3001
}

$.fn.reload_img = function() {
  this.each(function () {
    var curSrc = $(this).attr('src');
    var newSrc = curSrc.replace(/\?.*?$/, '?' + Math.floor(Math.random() * 0xFFFFFFFF))
    $(this).attr('src', newSrc);
  });
};

function wire_image_popups(parent) {
  $('img.photo', parent).popups();
}

/*These behaviors are applied by livequery selectors which persist across dom changes (eg. ajax); therefore,
 they do not have to be reapplied after a change in dom (eg. modals)
 */
function behaviors() {
  //popup calendar widgets
  $('.datepicker').livequery(function() {
    $(this).datePicker({startDate:'1970-01-01'});
  });

  $('.attraction_link').livequery(function() {
    $(this).popups();
  });

  //tooltips
  $('a.tip').livequery(function() {
    $(this).cluetip({
      splitTitle: '|',
      showTitle: false,
      positionBy: 'mouse',
      width: '300px',
      dropShadow: false,
      cluezIndex: 3001
    });
  });

  //curved corners
  $('.curved').livequery(function() {
    $(this).corner({
      tl: { radius: 5 },
      tr: { radius: 5 },
      bl: { radius: 5 },
      br: { radius: 5 }
    });
  });

  $('.multiselectable').livequery(function() {
    $(this).multiSelect({
      select_all_min: 100,
      no_selection: "Select one or more",
      selected_text: " selected"
    });
  });

  $('.toggler').livequery(function() {
    $(this).toggler();
  });

  $('input.currency').livequery(function() {
    $(this).formatAsCurrency();
    $(this).bind('blur', function() {
      $(this).formatAsCurrency();
    });
  });
}

function wire_up_nav() {
  $('ul.secondary_nav').each(function() {
    var self = this;
    //var parent = $(this).prev();
    var drop_down = $(this).prev();
    drop_down.click(function() {
      $(self).toggle();
      $(drop_down).toggleClass('selected');
      return false;
    });
  });
}

function wire_up_close_messages() {
  $('#notice .close_messages').click(function() {
    close_notice();
  });
  $('#error .close_messages').click(function() {
    close_error();
  });
  wire_up_auto_close_messages();
}

function wire_up_auto_close_messages() {
  window.setTimeout(close_notice, 5000);
  window.setTimeout(close_error, 10000);
}

function close_notice() {
  var $notice = $('#notice');
  if ($notice.css('display') != 'none')
    $('#notice').slideToggle('fast');
}

function close_error() {
  var $error = $('#error');
  if ($error.css('display') != 'none')
    $('#error').slideToggle('fast');
}

function video_player(href, container_id, width, height) {
  var so = new SWFObject(href, container_id + '_player', width, height, '9');

  so.addParam('wmode', 'transparent');
  if (href.toLowerCase().indexOf('travelistic') >= 0) {
    so.addParam('allowFullScreen', 'true');
    so.addParam('allowScriptAccess', 'always');
  }

  so.useExpressInstall('/flashmovies/expressinstall.swf');
  so.write(container_id);
}

function wire_up_media_carousels() {
  $('.media_viewer').livequery(function() {
    var $selected_frame = null;
    var $displayed_photo = $(this).find('.displayed_photo');
    var $displayed_video = $(this).find('.displayed_video');
    var $caption = $(this).find('.caption');
    var $attribution = $(this).find('.attribution');

    function select_frame(link) {
      var $frame = $(link).parents('.frame').eq(0);
      $frame.addClass('selected_frame');

      if ($selected_frame)
        $selected_frame.removeClass('selected_frame');

      $selected_frame = $frame;
    }

    function update_caption_and_attribution(link) {

      var caption_text = $(link).find('input').val() || '&nbsp;';
      if (caption_text.length > 40)
        caption_text = caption_text.substring(0, 40) + '...';
      $caption.html(caption_text);
			
			$displayed_photo.attr('title', caption_text);
			$displayed_photo.attr('alt', caption_text);
			
      var attribution_text = $(link).find('img').attr('title') || '&nbsp;';
      if (attribution_text.length > 20)
        attribution_text = attribution_text.substring(0, 20) + '...';
      $attribution.html(attribution_text);
    }

    var $carousel = $(this).find('.carousel');

    $carousel.simple_carousel()
      .find('a.photo_link').click(function() {
      $displayed_photo.attr('src', this.href);
      update_caption_and_attribution(this);

      select_frame(this);
      $displayed_video.parents('.frame').eq(0).hide();
      $displayed_photo.parents('.frame').eq(0).show();

      return false;
    }).end()
      .find('a.video_link').click(function() {
      update_caption_and_attribution(this);
      var href = $(this).attr('href');
      video_player(href, $displayed_video.attr('id'), 251, 187);

      select_frame(this);
      $displayed_photo.parents('.frame').eq(0).hide();
      $displayed_video.parents('.frame').eq(0).show();

      return false;
    }).end()
      .find('li a:first').click(); //click on the first to ensure all the show behavior is properly reproduced on setup

  });
}

var init_photo_edit_page = function() {
  var toggle_crop = function() {
    if ($('#photo_do_crop').attr('checked')) {
      $('.jcrop-holder').show();
      $('.crop_target').hide();
    } else {
      $('.jcrop-holder').hide();
      $('.crop_target').show();
    }
  };

  $('.photo_crop img').Jcrop({
    aspectRatio: 1.333,
    setSelect: [
      parseInt($('#photo_crop_ulx').val()),
      parseInt($('#photo_crop_uly').val()),
      parseInt($('#photo_crop_lrx').val()),
      parseInt($('#photo_crop_lry').val())
    ],
    onSelect: function(c) {
      $('#photo_crop_ulx').val(c.x);
      $('#photo_crop_uly').val(c.y);
      $('#photo_crop_lrx').val(c.x2);
      $('#photo_crop_lry').val(c.y2);
    }
  });

  $('#photo_do_crop').change(function() {
    toggle_crop();
  });

  setTimeout(toggle_crop, 260);
};

var set_property_search_type = function(val) {
  if (val == 'Sale') {
    $('#property_search_eq_sale').val('true')
    $('#property_search_eq_rental').val('false')
  } else {
    $('#property_search_eq_rental').val('true')
    $('#property_search_eq_sale').val('false')    
  }
  $('#properties_search_form').submit();
}

$(function() {
  wire_up_nav();
  $('a.modal').modal_link({livequery: true});
  $('a.confirm, input.confirm, button.confirm').confirm('<h2 class="warning">Warning</h2><p class="warning">This operation cannot be undone. Do you wish to proceed?</p>');
  behaviors();
  wire_up_media_carousels();
  wire_up_close_messages();
  $('ul.button_bar li').mouseover(function () {
    $(this).addClass('hover');
  });
  $('ul.button_bar li').mouseout(function () {
    $(this).removeClass('hover');
  });

  $('div.multiSelect').livequery(function(){
    str = $(this).attr('id') + '-content'
    $(this).parent('li.field').click(function(){
      el = $(this);
      if(el.children('div.multiSelectContent').is(':visible')){
        el.addClass('opened')
      } else {
        el.removeClass('opened')
      }
    })
  })
});