// restore control of $ away from jquery to prototype (or whatever)
$.noConflict();

// Include Rails authenticity token in each ajax request. For reference:
// http://henrik.nyh.se/2008/05/rails-authenticity-token-with-jquery (read comments)
// http://www.viget.com/extend/ie-jquery-rails-and-http-oh-my/
jQuery(document).ajaxSend(function(event, request, settings) {
  if (settings.type == 'GET' || settings.type == 'get' || typeof(AUTH_TOKEN) == "undefined") return;
  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
  request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
});

// function to toggle element text
jQuery.fn.toggleText = function(a, b) {
  return this.each(function() {
    jQuery(this).text(jQuery(this).text() == a ? b : a);
  });
};

// function to set default values in text fields
// http://www.jason-palmer.com/2008/08/jquery-plugin-form-field-default-value/
jQuery.fn.defaultValue = function(text){
  return this.each(function() {
    // make sure we're dealing with text-based form fields
    if(this.type != 'text' && this.type != 'password' && this.type != 'textarea')
      return;
    // store field reference
    var current_field = this;
    // set value initially if none are specified
    if(this.value == '') {
      this.value = text;
    } else {
    // ignore any other value
    return;
    }
    // Remove values on focus
    jQuery(this).focus(function() {
      if(this.value == text || this.value == '')
      this.value = '';
    });
    // restore values on blur
    jQuery(this).blur(function() {
      if(this.value == text || this.value == '')
      this.value = text;
    });
    // capture parent form submission
    // remove field values that are still default
    jQuery(this).parents("form").each(function() {
      // bind parent form submit
      jQuery(this).submit(function() {
        if(current_field.value == text) {
          current_field.value = '';
        }
      });
    });
  });
};

// function to check if any elements exist with given selector
jQuery.fn.exists = function() {
  if (jQuery(this).length > 0) {
    return true;
  } else {
    return false;
  }
};

// function to check if any elements exist with given selector
jQuery.fn.selectTab = function() {
  //Remove any "active" class
  jQuery("ul.tabs li").removeClass("active");
  //Add "active" class to selected tab
  jQuery(this).addClass("active");
  //Hide all tab content
  jQuery(".tab_content").hide();
  //Find the rel attribute value to identify the active tab + content
  var activeTab = jQuery(this).find("a.tabname").attr("href");
  //Fade in the active content
  jQuery(activeTab).fadeIn();
  // set open-tab form variable
  // TODO: remove once fully dynamic
  tab_id = jQuery(this).attr('id');
  jQuery("[name='open_tab']").remove();
  html = "<input type='hidden' name='open_tab' value='"+tab_id+"'</input>";
  jQuery('#mainsearch_text_outer').append(html);
};

// function to update a tab's altered state
jQuery.fn.updateAlteredState = function() {
  // if tab has any 'on' descendants, mark as 'altered'
  var activeTab = jQuery(this).find("a.tabname").attr("href");
  if (jQuery(activeTab).find(".on").exists()) {
    jQuery(this).addClass("altered");
  } else {
    jQuery(this).removeClass("altered");
  }
};

// function to update a tab's altered state
jQuery.fn.clearTabSelections = function() {
  var activeTab = jQuery(this).find("a.tabname").attr("href");
  jQuery(activeTab).find(".on").removeClass("on");
  jQuery(this).removeClass("altered");
  // remove field from search form
  switch (activeTab) {
    case "#brand": jQuery("[name='brands[]']").remove();
    break;
    case "#size": jQuery("[name='sizes[]'], [name='gender']").remove();
    break;
    case "#price": jQuery("[name='max_price']").remove();
    break;
  }
};

jQuery(document).ready(function(){
  
  // FILTER FORM
  
  // INSTRUCTIONS
  jQuery(".refine_intro a.close").click(function() {
    jQuery(".refine_intro").addClass("hidden");
    jQuery.get("/shopper/hide_filter_instructions");
    return false;
  });
  
  // INITIAL SETUP
  //Only show once loaded
  jQuery("div.refine").show();
  //Slider
  jQuery("#slider_brand").easySlider();
  //Default Action
  jQuery(".tab_content").hide();
  
  // FILTER BUTTON (temporary)
  jQuery("a.button_filter").click(function() {
    jQuery("#mainsearch").submit();
  });
  
  // TABS
  // if open_tab element in search bar, open it, else open brands tab
  if (jQuery("[name='open_tab']").exists()) {
    open_tab_id = jQuery("input[name='open_tab']").val();
    open_tab_selector = "#" + open_tab_id;
    jQuery(open_tab_selector).selectTab();
  } else {
    jQuery("#brand-tab").selectTab();
  }
  // then when any of the tabs are clicked on...
  jQuery("ul.tabs li").click(function() {
    jQuery(this).selectTab();
    return false;
  });
  // ensure tab clear links above the tabs
  jQuery(function() {
    var zIndexNumber = 10000;
    jQuery('ul.tabs>li>a.clear').each(function() {
      jQuery(this).css('zIndex', zIndexNumber);
      zIndexNumber -= 10;
    });
  });
  // when any tab's clear link is clicked...
  jQuery("ul.tabs>li>a.clear").click(function() {
    jQuery(this).parent().clearTabSelections();
    return false;
  });
  
  // BRANDS
  // if any brands selected for this search, highlight them
  if (jQuery("[name='brands[]']").exists()) {
    jQuery("[name='brands[]']").each(function() {
      brand_id = jQuery(this).val();
      jQuery("#slider_brand a"+"#brand-"+brand_id).addClass("on");
    });
    jQuery("#brand-tab").updateAlteredState();
  }
  jQuery("#slider_brand a").click(function() {
    var brand_id = jQuery(this).attr('id').match(/\d+/)[0];
    var brand_form_field_selector = "input[name='brands[]'][value='"+brand_id+"']";
    if (jQuery(this).is('.on')) {
      // un-highlight brand
      jQuery(this).removeClass("on");
      // remove brand from search
      jQuery(brand_form_field_selector).remove();
    } else {
      // highlight brand
      jQuery(this).addClass("on");
      // add brand to search
      var html = "<input type='hidden' name='brands[]' value='"+brand_id+"'</input>";
      jQuery('#mainsearch_text_outer').append(html);
    }
    jQuery("#brand-tab").updateAlteredState();
    return false;
  });
  jQuery("#brand-tab a.clear").click(function() {
    jQuery("#brand-tab").clearTabSelections();
    return false;
  });
  
  // SIZES
  // if any sizes selected for this search, highlight them
  if (jQuery("[name='sizes[]']").exists()) {
    jQuery("[name='sizes[]']").each(function() {
      size = jQuery(this).val();
      jQuery("#size>.sizes>li"+"#size-"+size).addClass("on");
    });
    jQuery("#size-tab").updateAlteredState();
  }
  jQuery("#size>.sizes>li").click(function() {
    size_id = jQuery(this).attr('id').match(/\d+/)[0];
    if (jQuery(this).is('.on')) {
      // un-highlight size
      jQuery(this).removeClass("on");
      // remove size from search
      jQuery("input[name='sizes[]'][value='"+size_id+"']").remove();
    } else {
      // highlight size
      jQuery(this).addClass("on");
      // add size to search
      var html = "<input type='hidden' name='sizes[]' value='"+size_id+"'</input>";
      jQuery('#mainsearch_text_outer').append(html);
    }
    jQuery("#size-tab").updateAlteredState();
    return false;
  });
  // GENDERS
  // highlight gender selected in this query
  if (jQuery("[name='gender']").exists()) {
    jQuery("[name='gender']").each(function() {
      gender_id = jQuery(this).val();
      jQuery("#size>ul.gender>li>a"+"#gender-"+gender_id).addClass("on");
    });
    jQuery("#size-tab").updateAlteredState();
  }
  jQuery("#size>ul.gender>li>a").click(function() {
    if (jQuery(this).is('.on')) {
      // update highlighting
      jQuery("#size>ul.gender>li>a").removeClass("on");
      jQuery("input[name='gender']").remove();
    } else {
      // update highlighting
      jQuery("#size>ul.gender>li>a").removeClass("on");
      jQuery(this).addClass("on");
      // update search form gender fields
      jQuery("input[name='gender']").remove();
      var gender_id = jQuery(this).attr('id').match(/\d+/)[0];
      var html = "<input type='hidden' name='gender' value='"+gender_id+"'</input>";
      jQuery('#mainsearch_text_outer').append(html);
    }
    jQuery("#size-tab").updateAlteredState();
    return false;
  });
  jQuery("#size-tab a.clear").click(function() {
    jQuery("#size-tab").clearTabSelections();
    return false;
  });
  
  // PRICES
  // highlight max price in this query, or "all" if none selected
  if (jQuery("[name='max_price']").exists()) {
    price = jQuery("input[name='max_price']").val();
    jQuery("#max_price-"+price).addClass("on");
    jQuery("#price-tab").updateAlteredState();
  } else {
    jQuery("#price>ul>li.all>a").addClass("on");
  }
  // specific max-price links (excluding "all" link)
  jQuery("#price>ul>li:not(.all)>a").click(function() {
    // update highlighting
    jQuery("#price>ul>li>a").removeClass("on"); // deactive all links
    jQuery(this).addClass("on");  // active this link only
    // update search form
    jQuery("input[name='max_price']").remove();
    price = jQuery(this).attr('id').match(/\d+/)[0];
    html = "<input type='hidden' name='max_price' value='"+price+"'</input>";
    jQuery('#mainsearch_text_outer').append(html);
    jQuery("#price-tab").updateAlteredState();
    return false;
  });
  // "all" max-price link
  jQuery("#price>ul>li.all>a").click(function() {
    // clear tab selections
    jQuery("#price-tab").clearTabSelections();
    jQuery(this).addClass("on");
    // update search form
    jQuery("input[name='max_price']").remove();
    return false;
  });
  jQuery("#price-tab a.clear").click(function() {
    // clear tab selections
    jQuery("#price-tab").clearTabSelections();
    // re-highlight "All" default selection
    jQuery("#price>ul>li.all>a").addClass("on");
    return false;
  });
  
  
  // clear search field upon focus
  jQuery("#superword_token").defaultValue('Search for authentic kix...');
  
  // mouseover/out toggles inventory display
  jQuery(".result-size-display").mouseover(function() {
    jQuery(this).children('*.result-size-popup').removeClass('hidden');
    return false;
  });
  jQuery(".result-size-display").mouseout(function() {
    jQuery(this).children('*.result-size-popup').addClass('hidden');
    return false;
  });
  
  // link on single-shoe profile that toggle additional inventories
  jQuery(".toggle_retailers").click(function() {
    jQuery(this).parent().children('.retailers').toggleClass('hidden');
    jQuery(this).toggleClass('open');
    jQuery(this).toggleText('Less', 'More');
    return false;
  });
  
  // popup links
  jQuery(".popup").click(function() {
    window.open(this.href);
    return false;
  });
  
  // notification links
  jQuery("a.notify_me").click(function() {
    shoe_id = jQuery(this).parents('div.item').attr('id').replace(/shoe-/,'');
    size_display_id = jQuery(this).parents('li').attr('id'); // eg, shoe-40648-size-35-display
    size = size_display_id.replace(/shoe-\d+/,'').replace(/-size-/,'').replace(/-display/,'');
    path = "/notifications/add?shoe_id="+shoe_id+"&size="+size;
    // execute request
    jQuery.ajax({
       type: "GET",
       url: path,
       success: function(msg){
         size_display_selector = "#"+size_display_id;
         jQuery(size_display_selector).addClass('pressed');
         message = "We'll notify you when they're available";
         jQuery(size_display_selector+" "+".notification_message").text(message);
       }
     });
    return false;
  });
  jQuery("ul.notifications>li>a.remove").click(function() {
    parent_li_id = jQuery(this).parent().attr("id");
    parent_li_selector = "#" + parent_li_id;
    jQuery.ajax({
       type: "GET",
       url: this.href,
       success: function(msg){
         jQuery(parent_li_selector).remove();
       }
     });
    return false;
  });
  
  // heart links
  jQuery("a.heart.lovable").click(function() { return false; }); // default
  jQuery("a.heart.lovable").click(function(event) {
    var shoe_id = jQuery(this).attr('id').match(/\d+/)[0];
    var this_selector = "#like-" + shoe_id;
    // highlight heart
    jQuery(this_selector).addClass('pressed');
    // update vote count
    var this_count_selector = (this_selector + ">span.count");
    var old_count = jQuery(this_count_selector).text().match(/\d+/)[0];
    var new_count = parseInt(old_count) + 1;
    jQuery(this_count_selector).text(new_count);
    // update the database
    params = ("shoe_id=" + shoe_id);
    jQuery.get("/hearts/add", params);
    // remove this binding
    jQuery(this).unbind(event);
    return false;
  });
  
  // save links
  jQuery("a.savable").click(function() { return false; }); // default
  jQuery("a.savable").click(function(event) {
    shoe_id = jQuery(this).attr('id').match(/\d+/)[0];
    jQuery("#save-"+shoe_id).addClass('pressed');
    params = ("shoe_id=" + shoe_id);
    jQuery.get("/shoe_subscriptions/add", params);
    // remove this binding
    jQuery(this).unbind(event);
    return false;
  });
  jQuery("ul.icon_overlay>li.remove>a").click(function() {
    jQuery.get(this.href, function() { 
      window.location.reload();
    });
    return false;
  });
  
  
  // redirects
  jQuery("a.redirect").click(function() {
    url = jQuery(this).attr('href');
    id = jQuery(this).attr('id').match(/\d+/)[0];
    params = {redirect: {destination_url: url, inventory_id: id}};
    jQuery.get("/redirects/create_via_get", jQuery.param(params) );
    return false;
  });
  
  // reporting
  jQuery('select#month').change(function() {
    jQuery("#year_month").submit();
    return false;
  });
  
  jQuery("a.export").click(function() {
    window.print();
    return false;
  });
  
  // Fix for IE7 to fix z-index bugs on size buttons
  jQuery(function() {
    var zIndexNumber = 5000;
    jQuery('div.extras, .sizes>li').each(function() {
      jQuery(this).css('zIndex', zIndexNumber);
      zIndexNumber -= 10;
    });
  });
  
  // SIGNUP FORM
  // password fields are initially displayed as text fields with instructive 
  // values, but are swapped with 'true' password fields upon focus
  jQuery("#signup_dropdown #fake_password").focus(function() {
    jQuery(this).addClass("hidden");
    jQuery("#signup_dropdown #signup_password").removeClass("hidden").focus();
  });
  jQuery("#signup_dropdown #fake_passconf").focus(function() {
    jQuery(this).addClass("hidden");
    jQuery("#signup_dropdown #signup_passconf").removeClass("hidden").focus();
  });
  // clear signup email field upon focus
  jQuery("#signup_dropdown #signup_email").focus(function() {
    jQuery(this).val("");
    return false;
  });
  // links that display, and scroll to, the signup form
  jQuery(".reveal_signup_dropdown").click(function() {
    jQuery('#signup_dropdown').removeClass('hidden');
    jQuery.scrollTo('#signup_dropdown', 1000); 
    return false;
  });
  
  // LOGIN FORM
  // set default value for login form, clear both it and password on focus
  jQuery("#login_email").defaultValue('Email address');
  jQuery("#login_email").focus(function() {
    jQuery("#login_password").val("");
    return false;
  });
  
  // PASSWORD RESET
  // links that display, and scroll to, the signup form
  jQuery(".reveal_forgot_password_dropdown").click(function() {
    jQuery('#forgot_password_dropdown').removeClass('hidden');
    jQuery.scrollTo('#forgot_password_dropdown', 1000); 
    return false;
  });
  
  // set default value for login form, clear both it and password on focus
  jQuery("#forgot_email").defaultValue('Email address');
  jQuery("#forgot_email").focus(function() {
    jQuery("#forgot_email").val("");
    return false;
  });
  
  jQuery("#forgot_password_dropdown>form").submit(function() {
    var path = this.action;
    var forgot_email = jQuery(this).find("#forgot_email").attr("value");
    var params = {"forgot_email": forgot_email};
    jQuery.ajax({
      type: "GET",
      url: path,
      data: params,
      success: function(msg){
        // jQuery("form#forgot>fieldset").children().addClass('hidden');
        jQuery("#email-missing").addClass('hidden');
        jQuery("#email-found").removeClass('hidden');
      },
      error: function(msg){
        jQuery("#email-found").addClass('hidden');
        jQuery("#email-missing").removeClass('hidden');
      }
    });
    return false;
  });
  
  // password fields are initially displayed as text fields with instructive 
  // values, but are swapped with 'true' password fields upon focus
  jQuery("#reset #fake_password").focus(function() {
    jQuery(this).addClass("hidden");
    jQuery("#reset_password").removeClass("hidden").focus();
  });
  jQuery("#reset #fake_passconf").focus(function() {
    jQuery(this).addClass("hidden");
    jQuery("#reset_passconf").removeClass("hidden").focus();
  });
  jQuery("#reset #fake_password").defaultValue('Password');
  jQuery("#reset #fake_passconf").defaultValue('Confirm');
  
  // // centered vertical alignment of images
  // jQuery(document).ready(function(i) {
  //   jQuery('.img_resize img').each(function() {
  //     var imageHeight = -(jQuery(this).height() / 2);
  //     jQuery(this).css({'marginTop':imageHeight, 'position':'absolute','top':'50%','left':'0px'});              
  //   });
  // });
    
});
