// Remove the need to append .js to ajax urls yet still fire controller format.js blocks
jQuery.ajaxSetup({
  'beforeSend': function (xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});

$(document).ready(function($) {
  // Attach main menu behavior.
  $('#menu > li, #user_menu > li').bind('mouseover', jsddm_open);
  $('#menu > li').bind('mouseout',  jsddm_timer);
  $('#user_menu > li').bind('mouseout',  jsddm_close);
  document.onclick = jsddm_close;

  // Attach the fancybox behavior to the CMS bar.
  $('a[rel*=cms]').fancybox({ height: 700,
                              width: 960,
                              showNavArrows: false,
                              type: 'iframe'
                            });

  $("#cms_home_page_feature_featurable_type").replaceFeaturableIdSelectListOnChange();

  $("#cms_home_page_feature_featurable_id").replaceFeaturableDescriptionFieldOnChange();

  $('a[rel*=marketo]').fancybox({ height: 300,
                            width: 400,
                            showNavArrows: false,
                            type: 'iframe',
                            scrolling: 'no',
                            onClosed: function() {document.location.reload(true);}
                          });

  // check for fancybox_iframe classed links and apply fancybox to them
  if ( $('.fancybox_iframe').exists() ) {

    $('.fancybox_iframe').click(function() {
      $.fancybox(
        $(this).attr("href"),
        {
          'type'		          : 'iframe',
          'width'             : 800,
          'height'            : 600,
          'title'             : $(this).attr("title")
        }
      );
      return false;
    });

  }

});

// This is a little convenience function to determine the existence of matching elements on a page
// http://stackoverflow.com/questions/920236/jquery-detect-if-selector-returns-null
jQuery.fn.exists = function () {
  return this.length !== 0;
}

// This function observes the select list of Featurable types in cms/home_page_features/_form.html.haml.
// It requests a set of <option>s for #cms_home_page_featurable_id.
jQuery.fn.replaceFeaturableIdSelectListOnChange = function() {
  this.change(function() {
    if (this.value == "") {
      $("#cms_home_page_feature_featurable_id").html("<option>Please choose a type of feature.</option>");
      return false;
    }
    $.get("/admin/" + this.value + "s", function(data) {
      $("#cms_home_page_feature_featurable_id").html(data);
    }, "html");
    $("#cms_home_page_feature_featurable_id").parent().effect("highlight", {}, 1500);
    return false;
  })
  return this;
};

// This function observes the select list in cms/home_page_features/_form.html.haml.
// It requests and displays the Featurable object's description in the textarea.
jQuery.fn.replaceFeaturableDescriptionFieldOnChange = function() {
  this.change(function() {
    var url = "/admin/" + $("#cms_home_page_feature_featurable_type").attr("value") + "s/" + this.value;
    $.get(url, function(data){
      $("#cms_home_page_feature_description").html(data);
    });
    $("#cms_home_page_feature_description").parent().effect("highlight", {}, 1500);
    return false;
  })
  return this;
};

// this function takes a 'selection' value (text), compares it to the 'compare' value (text),
// and slides/hides the 'elements' if they don't match. If they match the elements will be shown again.
function slideHide ( selection, compare, elements ) {
  // alert('got selection: '+selection);
  if ( compare == 'checked' ) {
    test = $(selection).is(':checked');
  } else {
    test = (selection != compare)
  }
  if ( test ) {
    $(elements).slideUp();
  } else {
    $(elements).slideDown();
  }
}

// Menubar behavior. http://javascript-array.com/scripts/jquery_simple_drop_down_menu/
var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;

function jsddm_open(){
  jsddm_canceltimer();
  jsddm_close();
  ddmenuitem = $(this).find('ul').css('visibility', 'visible');
}

function jsddm_close() {
  if (ddmenuitem) ddmenuitem.css('visibility', 'hidden');
}

function jsddm_timer() {
  closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer() {
  if (closetimer) {
    window.clearTimeout(closetimer);
    closetimer = null;
  }
}


