/* IE doesn't have this guy */
if (!Array.indexOf) {
  Array.prototype.indexOf = function (obj, start) {
    var len = this.length;
    for (var i = (start || 0); i < len; i++) {
      if (this[i] == obj) {
        return i;
      }
    }
  };
}

mexpress.commentBox = {
  init: function() {
    $("#buzz-form textarea.restrict-size").bind("keyup", function(e) {
      var text = $(this).val();

      if (text.length > maxCommentLength) {
        $(this).val(text.substr(0, maxCommentLength));
      }

      mexpress.showCharactersRemaining(this);
    }).each(function(element){
      mexpress.showCharactersRemaining(this);
    });
  }
};

mexpress.flashFromCookie = {
  init: function() {
    $(document).bind("ajaxComplete", mexpress.flashFromCookie.create);
    mexpress.flashFromCookie.create();
  },

  create: function() {
    $.each(['flashmessage', 'flashnotice', 'flasherror'], function( i, cookie ) {
      var domSelector = "div." + cookie.replace(/flash/, '');
      if(readCookie(cookie)) {
        var message = readCookie(cookie);
        var elem = $(domSelector);
        eraseCookie(cookie);
        message = unescape(message.replace(/\+/g, " "));

        if(elem.is(":has(p:empty)")) {
          elem.filter(":has(p:empty):last").show().find("p").html(message);
        } else {
          elem.filter(":last").show().find("p").html(message);
        }
      }
    }); 
  }
};

mexpress.replaceWithLink = function() {
  $('input.replace-with-link').each(function(element) {
    var $element = $(this);
    $element.hide();
    var link = $('<a href="#"></a>')
                 .text( $element.attr('value') )
                 .click(function(e) { 
                   e.preventDefault();
                   $element.click();
                 });

    $element.parent().append(link);
  });
};

mexpress.updateFragments = function(fragments) {
  for(var selector in fragments) {
    $(selector).replaceWith(fragments[selector]);
  }
};

mexpress.initIfExists = function(module) {
  if(mexpress.hasOwnProperty(module)) { 
    mexpress[module]['init'].call();
  }
};

function scoped(fn, scope) {
  return function () {
    return fn.apply(scope, arguments);
  }
}

$(function() {
  var modules = [
    'ads',
    'advancedFilterMenu',
    'buzzInput',
    'buzzModule',
    'calendar',
    'columns',
    'commentBox',
    'contest',
    'datepicker',
    'eventPage',
    'flashFromCookie',
    'infiniteCarousel',
    'latestPulse',
    'listingPhotos',
    'mapAdmin',
    'mapFilterFlyouts',
    'mapUI',
    'paginate',
    'photoGallery',
    'plan', 
    'planEdit',
    'planit',
    'plans', // yes there are both
    'planYourNight',
    'prettySearch',
    'profilePage',
    'rater',
    'seoLinks',
    'shareIt',
    'slider',
    'stash',
    'structuredFeedback',
    'tabs',
    'userSession'
  ];
  var length = modules.length;
  for(var i = 0; i < length; i++) {
    mexpress.initIfExists(modules[i]);
  }

  mexpress.replaceWithLink();

  if(document.getElementById('map') && mexpress.hasOwnProperty('mapOverlay')) {
    // AH: this must happen before the map is initialized, so that the onload map render
    // will be caught and the error overlay applied if there were no results
    $(mexpress.mapOverlay.init);
    mexpress.mapUtil.loadApi(mexpress.map.init);
  }
});

jQuery(function() {
  jQuery("#try_deals_finder_link").click(function() {
    s.events = "event30";
    s.t();
  });
});

//The following code is used to handle the issue with a pencil ad not scrolling properly with the iphone browser,
//Whenever it was scrolled up or down - as a workaround, it responds to scrolling by manually repositioning the ad
//after each scroll.  Also we're assuming that the div id begins with ATStickybanner, but if that changes this code becomes obsolete.

function changeFooterPosition(){
	//For now we're assuming that all of the banner ads are 40 pixels high - if it needs to change, the following code gets the style of the 
	//div element where it can be parsed:
	//jQuery('div[id^=ATStickybanner] div').attr('style')
	top.jQuery('div[id^=ATStickybanner]').css('top', window.innerHeight + window.scrollY - 40 + "px");
}

var ua = navigator.userAgent;
var isiPadOriPhone = (/iPad/i.test(ua) || /iPhone/i.test(ua));
if(isiPadOriPhone){
	top.jQuery(document).bind('scroll', function() {
		changeFooterPosition();
	})
}

MMX.Singlemenu = {
  loadMenu: function(id, api_key) {
    var api = new MenusApi(api_key);
    api.setPrimaryFontFamily("Helvetica");
    api.setPrimaryFontColor("#333");
    api.setPrimaryBackgroundColor("#E1F1FC");
    api.setSecondaryBackgroundColor("#fff");
    api.setSectionTitleBackgroundColor("#f8f8f8");
    api.loadMenusForLocation(id, id);
  },

  init: function(api_key, $) {
    $('.view-menu').click(function(e) {
      e.preventDefault();
      e.stopPropagation();

      sendOmnitureEvents('event40');

      var smId = $(this).attr('data-singlemenu-id');
      MMX.Singlemenu.loadMenu(smId, api_key);

      var modalDiv = $('#' + smId).parent();
 
      modalDiv.dialog({width: 500, modal: true, height: 500, dialogClass: 'singlemenu-dialog', closeOnEscape: false, resizable: false, zIndex: 9700 });
      modalDiv.dialog('open');
      
    });

    $('a.close-menu').click(function() {
      $(this).parent().dialog('close');
    });

    $('.ui-widget-overlay').live("click", function() {
        $('.sp-menus-api').dialog('close');
    });

    if (window.location.search.match(/showmenu=true/))
      $('.view-menu').click();
  }
};
