//jQuery.noConflict();

//$(document).ready(function() {
//jQuery(document).ready(function($){
var inside_draggable_area = true;
var min_x, min_y, max_x, max_y;
var last_x, last_y;

jQuery(document).ready(function(){

  editing_faqs_events();
  jQuery('.dp-category:odd').addClass('odd');

  // leog: Prepare sortable stuff only for admin
  if (jQuery('#faq.admin').size()) {
    //console.log('leog: Prepare sortable stuff only for admin');
    makeFaqsSortable();
    
    // leog: what position i'am
    recalculate_boundaries();
    $().mousemove(function(e){
      update_inside_draggable_area(e);
    });
  }

  makeCategoriesSortable();

});

// leog: this function should be called on remove raq / move faq
function recalculate_boundaries() {
  var div_cat = jQuery('.category-list');
  var add_faq_anchors = jQuery('div.category-list a span');
  var botoncitos = jQuery('.draggable');

  // leog: Only if we have these elements
  if (botoncitos.length > 0 && add_faq_anchors.length > 0) {
    var boton_1 = jQuery(botoncitos[0]);
    var last_add_faq = jQuery(add_faq_anchors[add_faq_anchors.length-1]);

    //var boton_final = jQuery(botoncitos[botoncitos.length-1]);
    min_x = div_cat.offset().left;
    min_y = div_cat.offset().top;
    max_x = boton_1.offset().left + 200;
    max_y = last_add_faq.offset().top + 40;

  }

}

// leog: Used to update global variable inside_draggable_area
function update_inside_draggable_area(e) {
  // var xx = e.pageX; var yy = e.pageY;
  // var texto = xx + ', ' + yy + 'min: ' + min_x + ', ' + min_y + 'max: ' + max_x + ', ' + max_y;
  inside_draggable_area = true;
  last_x = e.pageX;
  last_y = e.pageY;
  if (last_x < min_x)
    inside_draggable_area = false; // texto += " afuera 1";
  if (last_x > max_x)
    inside_draggable_area = false; // texto += " afuera 2";
  if (last_y < min_y)
    inside_draggable_area = false; // texto += " afuera 3";
  if (last_y > max_y)
    inside_draggable_area = false; // texto += " afuera 4";
  // jQuery('h3.fw-title span.pageTitle').html(texto);
}

//This function hides a row and mark the delete textarea text as 'true'
function deleteCategory(order) {
  var rowId = "category"+order;
  var textarea_id =  'delete_' + order;

  //We put the delete value in true so Ruby can process that
  jQuery('textarea#'+textarea_id).val('1');
  //We hide the row to the user
  jQuery('tr#'+rowId).hide();

  return false;
};

//Test function, hasn't utility really'
function get_area(id) {
  var textarea_id =  id + '\\[delete\\]';
  return jQuery('#t'+textarea_id).val();

  return false;
}

function editing_faqs_events() {
  if (!jQuery('#choosen_category')) return;

  jQuery('#choosen_category').change(function () {
    jQuery('#ch_existent').click();
    jQuery('#category_name').attr("value","");
  });
  jQuery('#category_name').keydown(function () {
    jQuery('#ch_create').click();
    jQuery("#choosen_category").val(0);
  });
  jQuery('#ch_existent').change(function () {
    jQuery('#category_name').attr("value","");
  });
}

function hide_and_show_faqs() {
  jQuery('.dp-answer').hide();
  jQuery('.dp-faq').css("cursor","pointer").click(function(){
    jQuery('.dp-answer').hide();
    jQuery(this).next().show();
  });
}

function delete_faq(id) {
  var msg = 'Do you want to remove this question and answer permanently?';
  if (confirm(msg)) {
    var faq = jQuery("#li-faq-" + id);
    var cat_id = faq.parent().parent().attr('id').replace("cat-detail-", "");
    //alert("faq_id_html: " + faq.attr('id') + " cat_id: " + cat_id);
    faq.remove();
    jQuery("#link-" + id).remove();

    jQuery.post(url_del+id, null, null, "json");

    // Verify if cat_id should show "This Category has no FAQ yet" message
    var faq_ids = new Array();
    var faqs = jQuery("#cat-"+cat_id + " li");
    faqs.each(function(){
      faq_ids.push(jQuery(this).attr('id').replace("link-", ""));
    });
    var mi_cat = jQuery("#nofaqmsg-" + cat_id);
    if (faq_ids.length > 0) {
      mi_cat.css('display','none');
    } else {
      mi_cat.css('display','block');
    }

    // leog: recalculate draggable boundaries area
    recalculate_boundaries();
  }
}

function deleteCategoryOnBackground(cat_id, empty_category) {
  var msg;
  if (empty_category)
    msg = 'Do you want to delete this category?';
  else
    msg = 'This category is not empty. All FAQ in this category will be deleted. Are you sure you want to continue?';

  if (confirm(msg)) {
    jQuery.post("categories/delete/"+cat_id, null, function(){
      }, "json");
    var cat = jQuery('#' + cat_id);
    var order = cat.prevAll().size();
    var cat_list = jQuery("#faq > div:first");
    jQuery(jQuery(".category", cat_list).get(order)).remove();
    cat.remove();
    return false;
  }
  return true;
}

function toggleAddNewFaqLink(cat_id) {
  var faqs = jQuery("#cat-" + cat_id + " ol");
  var link1 = jQuery("#cat-" + cat_id + " .empty");
  var link2 = jQuery("#" + cat_id + " .empty");

  if (faqs.children().size()) {
    link1.hide();
    link2.hide();
  } else {
    link1.show();
    link2.show();
  }
}

// leog: some validation to avoid an strange error
function IsNumeric(sText) {
  if (isNaN(parseFloat(sText)))
    return false;
  else
    return true;
}

//function IsNumeric(sText)
//{
//   var ValidChars = "0123456789.";
//   var IsNumber=true;
//   var Char;
//
//
//   for (i = 0; i < sText.length && IsNumber == true; i++)
//      {
//      Char = sText.charAt(i);
//      if (ValidChars.indexOf(Char) == -1)
//         {
//         IsNumber = false;
//         }
//      }
//   return IsNumber;
//}

// Makes FAQ list sortable with drag and drop while editing
function makeFaqsSortable() {
  if(jQuery('.category-list .category ol').size() == 0) return;

  var elemsortable = jQuery('.category-list .category ol');
  elemsortable.sortable({
    //jQuery('.ol-category-links').sortable({
    handle: jQuery(".draggable"),
    cursor: 'move',
    axis: 'y',
    placeholder: 'sort-placeholder',
    connectWith: '.category-list .category ol',
    //containment: jQuery(".category-list"),
    stop: function(event, ui) {
      if (jQuery.browser.msie) {
        // leog: always refresh on IE
        var cat = jQuery(event.target).parent();
        var cat_id = cat.attr('id').replace("cat-", "");
        // Ocultar y mostrar botones add faq
        var button_id = 'cat-button-'+cat_id;
        jQuery('#'+button_id).hide();
        //var llamada = "$('#cat-button-" + cat_id + "'" + ").show();";
        var llamada = "$('#" + button_id + "'" + ").show();";
        setTimeout(llamada, 400);
        // Ocultar y mostrar cada faq link
        var faqs = jQuery("#cat-"+cat_id + " li");
        faqs.each(function(){
          var faq_id = jQuery(this).attr('id');
          jQuery('#'+faq_id).hide();
          var llamada = "$('#" + faq_id + "'" + ").show();";
          setTimeout(llamada, 700);
        });

        //elemsortable.sortable('refresh');
        //elemsortable.sortable('refreshPositions');
      }
    },
    update: function(event, ui) {
      // leog: According to whether i am, if in or out of the div i should cancel de drag and drop
      //alert("mouse_category_position: " + mouse_category_position);
      if (!inside_draggable_area) {
        if (ui.sender) {
          $(ui.sender).sortable('cancel');
        } else {
          $(this).sortable('cancel');
        }
        //alert(print_r(event));
        //alert(print_r(ui.sender));
        // Cancela el drop entre distintos ul
        //alert('cancelled!!! last_x: ' + last_x +' last_y: ' + last_y + ' min_x: ' + min_x + ' min_y: ' + min_y + ' max_x: ' + max_x + ' max_y: ' + max_y);
        //$(ui.reciever).sortable('cancel');
        // Cancela el drop dentro del mismo ul
        //elemsortable.sortable('cancel');
        //alert("cancelled");
        //setTimeout("makeFaqsSortable();", 200);
      } else {
        var cat = jQuery(event.target).parent();
        var cat_id = cat.attr('id').replace("cat-", "");

        var faq_ids = new Array();
        var faqs_elements = new Array();

        var faqs = jQuery("#cat-"+cat_id + " li");
        faqs.each(function(){
          faq_ids.push(jQuery(this).attr('id').replace("link-", ""));
          //console.log('id: ' + jQuery(this).attr('id'));
          faqs_elements.push(jQuery(this));
        });

        // leog: i need this to refresh stuff on IE6 IE7
        //var cat_links;
        //cat_links=jQuery('#cat-' + cat_id + " ol");

        var cat_details=jQuery('#cat-detail-' + cat_id + " ol"); // leog: antes usaba #id solo pero conflictúa con faq ids
        //            faq_ids.each(function(id){
        //              jQuery('#'+id).remove().appendTo(cat_details);
        //            });
        // leog: changed this when desperate
        if (faq_ids.length > 0) {
          for (ff in faq_ids) {
          //for (var i = 0; i < ) {
            id = faq_ids[ff];
            if (id && IsNumeric(id)) {
              var elm = jQuery('#li-faq-'+id);
              //try {
                elm.remove().appendTo(cat_details);
              //} catch(err) {
              //  alert('error en elm.remove().appendTo: id = ' + id + ' ff = ' + ff + ' cat_details = ' + cat_details + ' err: ' + err.toString());
              //}
              
            }
          }
        }

        //toggleAddNewFaqLink(cat_id);

        // Verify if cat_id should show "This Category has no FAQ yet" message
        var mi_cat = jQuery("#nofaqmsg-" + cat_id);
        if (faq_ids.length > 0) {
          mi_cat.css('display','none');
        } else {
          mi_cat.css('display','block');
        }

        // Internet explorer: refresh stuffs
        // Hide first
        //            var faqs_html_content = new Array();
        //            faqs.each(function(){
        //              cad = jQuery(this).html();
        //              faqs_html_content.push(cad);
        //            });
        //            // Show again
        //            for(var i=0; i < faqs.length; i++) {
        //              cad = faqs_html_content[i];
        //              //jQuery(this).html(cad);
        //              //console.log('faqs: ' + faqs[i]);
        //              jQuery(faqs[i]).html(cad);
        //            }
        //location.href='#';
        //if (document.all) { Droppables.drops = [] }

        // Finally update the database
        var params = {
          'cat_id':cat_id,
          'faqs[]':faq_ids
        };
        //jQuery.post("categories/reorder_faq/"+cat_id, params, function(){}, "json");
        jQuery.post(url_drag_drop+cat_id, params, function(data) {
          //jQuery('.result').html(data);
          // leog: i am trying to refresh internet explorer mother fucker 6.0
          }, "json");

        // leog: recalculate draggable boundaries area
        // be careful in not doing this after hidding elements!
        setTimeout('recalculate_boundaries();', 1000);

        //location.href='#cat-button-'+cat_id;
        if (jQuery.browser.msie) {
          // Ocultar y mostrar botones add faq
          var idd = 'cat-button-'+cat_id;
          jQuery('#'+idd).hide();
          //var llamada = "$('#cat-button-" + cat_id + "'" + ").show();";
          var llamada = "$('#" + idd + "'" + ").show();";
          setTimeout(llamada, 300);
          // Ocultar y mostrar cada faq link
          faqs.each(function(){
            var idd = jQuery(this).attr('id');
            jQuery('#'+idd).hide();
            var llamada = "$('#" + idd + "'" + ").show();";
            setTimeout(llamada, 500);
          });
        }
      //elemsortable.sortable('refresh');
      } // endif de inside_draggable_area

    }
  });

}

function makeCategoriesSortable() {
  jQuery('table.sortable tbody tr:odd').attr('class', 'odd');
  jQuery('table.sortable tbody tr:even').attr('class', 'even');

  jQuery('table tbody a.control').live('click', function (e) {
    e.preventDefault();

    // To allow the control links to be buried anywhere in the table (rather than at two deep)
    // The following uses the jQuery parent() function to cycle up through parents until the TR is found
    // To avoid an infinite loop (due to HTML error or other misnomer), there is a max iteration count set of 100
    var tr = jQuery(this); // Start with this link and work upwards from there, this allows the TR element itself to be the control if desired
    var iterations = 0;
    while(tr.attr('tagName') != 'TR') {
      tr = tr.parent();
      iterations += 1;
      if (iterations == 100) {
        return false; // Bail out, surely something is wrong or there is lots and lots of html in there
      }
    }

    // Now that the TR tag has been stored in the tr variable, check the rel attribute of the link that has been clicked  ( jQuery(this) ) to see what direction to move
    // To fine the previous sibling inside the <tbody> tag, the jQuery prev() function is used and to find the next element,
    // surprisingly enough, the jQuery next() element is used.
    // The TR element will only be moved if there IS a sibling , otherwise the function is exited
    if (jQuery(this).attr('rel') == 'up' && tr.prev().length)
      // This next part is here mainly for show. The fading in and out isn't required. To simply move up
      // or down, just use tr.insertBefore(tr.prev()) or tr.insertAfter(tr.next())
      // The code below uses the jQuery fadeTo function to fade to 0.1 opacity (not fadeOut as that causes jerkiness when
      // the element is hidden after fading out), then does the move inside a callback function before fading back in.

      tr.fadeTo('medium', 0.1, function () {
        tr.insertBefore(tr.prev()).fadeTo('fast', 1);
        // If you want to do any more to the table after the move put it here, I am running the reorder function (defined below)
        reorder();
      });
    else if (jQuery(this).attr('rel') == 'down' && tr.next().length)
      // Same as above only this is for moving elements down instead of up
      tr.fadeTo('fast', 0.1, function () {
        tr.insertAfter(tr.next()).fadeTo('fast', 1);
        // If you want to do any more to the table after the move put it here, I am running the reorder function (defined below)
        reorder();
      });
    else
      //Can't do anything with these
      return false;

    return false;
  });

}

// If you need nothing more than just to move rows up and down, you can leave it at that!
// This next part cycles through all of the TR elements putting the zebra-striping back in the correct places
// It also renumbers the positions so they are in the correct sequential order (this was a requirement for my task)
function reorder () {
  var position = 1;
  jQuery('table#main_table tbody tr').each(function () {
    // Change the text of the first input element inside this TR
    jQuery('input.ord_num', jQuery(this)).attr('value', position);
    //Now remove current row class and add the correct one
    jQuery(this).removeClass('odd even').addClass( position % 2 ? 'odd' : 'even');

    position += 1;

  });
}

/**
 * Concatenates the values of a variable into an easily readable string
 * by Matt Hackett [scriptnode.com]
 * @param {Object} x The variable to debug
 * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
 * @param {String} sep The separator to use between [default: a single space ' ']
 * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
 */
function print_r(x, max, sep, l) {

	l = l || 0;
	max = max || 10;
	sep = sep || ' ';

	if (l > max) {
		return "[WARNING: Too much recursion]\n";
	}

	var
		i,
		r = '',
		t = typeof x,
		tab = '';

	if (x === null) {
		r += "(null)\n";
	} else if (t == 'object') {

		l++;

		for (i = 0; i < l; i++) {
			tab += sep;
		}

		if (x && x.length) {
			t = 'array';
		}

		r += '(' + t + ") :\n";

		for (i in x) {
			try {
				r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
			} catch(e) {
				return "[ERROR: " + e + "]\n";
			}
		}

	} else {

		if (t == 'string') {
			if (x == '') {
				x = '(empty)';
			}
		}

		r += '(' + t + ') ' + x + "\n";

	}

	return r;

};
var_dump = print_r;
