/*!!!!!!!!!!!!!!! IMPORTANT !!!!!!!!!!!!!!!!!!
This is jQuery javascript (http://jquery.com). Please use jQuery to write your javascript as to keep everything uniform.*/

$(document).ready(function(){
  /*
 		<input type="button" name="select_all" value="Select All" class="select_all"/>
  	<input type="button" name="select_none" value="UnSelect All" class="select_none"/>
	*/
  // - When buttons are placed anywhere inside a table will allow the buttons to only select checkboes inside that table as to not select checkboxes in other tables.
  // - If you have any checkboxs that SHOULD NOT BE CHECKED add the class ".no_check" and it will be ignored.
  // Select all
  $(".select_all").live("click", function(){
    $(this).parents("table").find("input[type='checkbox']:not('.no_check')").attr("checked", true);
  });

  // Select none
  $(".select_none").live("click", function(){ 
    $(this).parents("table").find("input[type='checkbox']:not('.no_check')").attr("checked", false)
  });

  // Hub specific things
  $("#customize_table .hub_steps li label img").click(function(){
    $(this).addClass("selected")
    $(this).parents("li").siblings('li').find("img").removeClass("selected")
  });
  
  $("#order_form").submit(function(){
    $("#place_order").attr("disabled", true);
  });

  //== Facebox Conditional Refresh Code ==//
  // This page specific variable will be used to determine if the page should refresh after closing the facebox
  var refresh_on_facebox_close = false;

  // Check for refresh indicator
  $('a[rel*=facebox]').click(function(){
    // var should_refresh = $(this).attr('class').match(/refresh/);
		var should_refresh = $(this).hasClass('refresh');
    if(should_refresh){
      refresh_on_facebox_close = true;
    }else{
      refresh_on_facebox_close = false;
    };
  });

  // bind refresh to facebox close
  $(document).bind('close.facebox', function() {
    if(refresh_on_facebox_close)
    document.location.reload(true);
    refresh_on_facebox_close = false;
  });
  //== End Facebox Conditional Refresh Code ==//

  $("p.notice, p.success, p.error").click(function(){
    $(this).animate({ margin: "-42px 0 0" }, 500, function(){$(this).hide()})
  })

  // Save Message For Assigning Roles
  $("input[id*='user_role_ids_']").click(function(){
    $(".save_message").fadeIn("slow");
    $(".edit_saved").fadeIn("slow").text("Loading Permissions");
    setTimeout('$(".edit_saved").fadeOut("slow")', 800);
  });

  // Swap Value in input fields
  swapValues = [];
  $(".swap_value").each(function(i){
    swapValues[i] = $(this).val();
    $(this).focus(function(){
      if ($(this).val() == swapValues[i]) {
        $(this).val("").css({ color: "#111"});
      }
    }).blur(function(){
      if ($.trim($(this).val()) == "") {
        $(this).val(swapValues[i]).css({ color: "#999"});
      }
    });
  });

  // Awesome one-liner zebra stripes
  $(".stripe tbody tr:odd, #roles_list tbody tr:odd").css("background-color", "#EEE");
  $(".qty_by_location_table tbody tr:odd, #billing_table tbody tr:even, #credit_table tbody tr:even, .CofirmationTable tbody tr:odd, .product_pricing table tbody tr:even, #receipt_table tbody tr:even").addClass("stripe_table");
  // converted from "A list apart zebra stripes"
  $(".discount_pricing tbody tr:odd, .regular_pricing tbody tr:odd, .billing_table tbody tr:odd, .credit_table tbody tr:odd, .receipt_table tbody tr:odd").css("background-color", "#EDF3FE");

  // To expand one row at a time in user section
  $(".user_list_users, .coupon_list_users, .promotion_list_users").click(function(){
    $(this).children("li.user_list_edit_parent, li.coupon_list_edit_parent, li.promotion_list_edit_parent").children("ul.user_list_edit, ul.coupon_list_edit, ul.promotion_list_edit").toggle("fast");
  })

  // This is for toggleing edit tools in admin Users section
  $("#toggle_admin_tools").toggle(
    function(){
      $(".user_list_edit").show("fast");
      $("#toggle_admin_tools").text("Hide user management tools");
    },
    function(){
      $(".user_list_edit").hide("fast");
      $("#toggle_admin_tools").text("Show user management tools");
    }
  );
  
  if ($("#wrapper").hasClass("test")){
    $("#tree").acts_as_tree_table({
      indent: 12
    });
  };

  // FaceBox
  $('a[rel*=facebox]').facebox();
});

// Keywords
// --------------------------------------------------------------------------

// Function for applying new keywords to a list
function addKeyword(value){
  $("#selected_keywords").append($("<li>"+ value +"</li>").append("<input type= 'hidden' value='"+ value +"' name='product[keywords][]'/>").prepend($("<a class = 'remove_keyword' href='#'>Remove</a>").click(function(){removeSelected(this); return false;})));
}

// Function for removing parent franchise
function removeSelected(element){
  $(element).parent("li").remove();
}

$(document).ready(function(){
  // Button to submit keywords
  $("#add_keyword").click(function(){
    var value = $('#new_keyword').val();
    if($.trim(value) != "Enter New Keyword & Press Enter"){
      addKeyword(value);
    }
  });
  // Input enters keyword on keypress
  $('#new_keyword').keypress(function(e){
    // 13 = Return / Enter on keyboard
    if(e.keyCode == 13){
      var value = $('#new_keyword').val();
      if($.trim(value) != ""){
        addKeyword(value);
        $(this).attr("value",""); 
      }
      return false;
    }
  });
});


//################ Product Specification Keywords
function addProdSpecKeyword(value){
  $("#selected_keywords").append($("<li>"+ value +"</li>").append("<input type= 'hidden' value='"+ value +"' name='product_specification[keywords][]'/>").prepend($("<a class = 'remove_keyword' href='#'>Remove</a>").click(function(){removeSelected(this); return false;})));
}

$(document).ready(function(){
  // Button to submit keywords
  $("#add_keyword_for_product_spec").click(function(){
    var value = $('#new_keyword_for_product_spec').val();
    if($.trim(value) != "Enter Keyword & Press Enter"){
    	addProdSpecKeyword(value);
    	$("#new_keyword_for_product_spec").attr("value",""); 
    }
  });
 
   // Input enters keyword on keypress
  $("#new_keyword_for_product_spec").keypress(function(e){
    if(e.keyCode == 13){
      var value = $(this).val();
      if($.trim(value) != ""){
        addProdSpecKeyword(value);
        $(this).attr("value",""); 
      }
      return false;
    }
  });
});

// Fixes img wrapped in label not triggering label 'for' input -- also triggers radiobutton change event (ie fail #2)
function ie_fix_radio_buttons() {
  if(document.all && navigator.appVersion.indexOf("MSIE")>-1 && navigator.appVersion.indexOf("Windows")>-1)
  {
    var a = document.getElementsByTagName("label");
    for(var i=0,j=a.length;i<j;i++){
      if(a[i].hasChildNodes && (a[i].childNodes.item(0).tagName == "IMG" || a[i].childNodes.item(0).className == "submit_label" || a[i].childNodes.item(0).className == "submit_headline"))
      {
            //if(a[i].childNodes.item(0).className == "submit_label")
            //    alert("submit_label");
        a[i].childNodes.item(0).forid = a[i].htmlFor;
        a[i].childNodes.item(0).onclick = function(){
          var e = document.getElementById(this.forid);
          switch(e.type){
            case "radio": e.checked|=1;break;
            case "checkbox": e.checked=!e.checked;break;
            case "text": case "password": case "textarea": e.focus(); break;
          }
		  // Now, also trigger the change event to submit the ajax
		  $(e).trigger('change');
        }
      }
    }
  }
}

//Retrieve and display Keywords from Product Specification 
/*
function get_keywords_for_prod_spec (prod_spec_name) {
	// var class_with_id = edited_element.attr('class').match(/place_holder_(\d+)/);
	var class_with_id = edited_element.attr('class').match(/place_holder_(\d+)/);
	if(class_with_id && class_with_id.length == 2){
		$.ajax({
			type: "POST",
			url: '/contents/save',
			data: 'place_holder_id='+ class_with_id[1] +"&content="+encodeURI($('#placeholder_edit').val()),
			dataType: 'json',
			beforeSend: function(){ $('#placeholder_loader').show(); },
			complete: function(){ $('#placeholder_loader').hide(); },
			success: save_successful
		});
	};
}*/



// Request Access - Franchises
// --------------------------------------------------------------------------

function selectedFranchise(value){
  $("#selected_franchises").append($("<li>"+ value +"</li>").append("<input type= 'hidden' value='"+ value +"' name='selected_franchise[]'/>").prepend($("<a class = 'remove_franchises' href='#'>Remove</a>").click(function(){removeSelected(this); return false;})));
}

// Function for removing parent franchise
function removeSelected(element){
  $(element).parent("li").remove();
}

function addFranchise (){
  // Button to submit keywords
  $("#add_franchise").click(function(){
    var value = $('#market_area_name').val() + ' > ' + $('#franchise__name').val();
    if($.trim(value) != ""){
      selectedFranchise(value);
    }
	$('#market_area_name').val('');
	$('#franchises').text('');
  });
}

addFranchise();

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


function display_estimated_ship_notice(text) {
	$("#estimated_ship_notice").text(text);
}
