var empty_inputs = [];

/*
 *  Fancybox settings & functions
 */
var popup_settings = {
	'hideOnContentClick'  : false,
	'hideOnOverlayClick'  : false,
	'showCloseButton'     : false,
	'centerOnScroll'      : true,
	'titleShow'      	  : false,
 	'padding'             :	6,
	'overlayOpacity'  	  :	0.7,
	'overlayColor'        : '#fff'
}

try {
	if ($.fn.fancybox != undefined) {
		$(".popup_close").live('click', $.fn.fancybox.close);
	}

	$('input[type=submit]', '#fancy_content').live('click', function() {
		var form = $(this).parents('form');

		if (form != undefined && !$(form).hasClass('no-popup')) {
			$.ajax({
					type: 'POST',
					url: $(form).attr('action'),
					data: $(form).serialize(),
					dataType: 'html',
					complete: function (XHR, status, e) {
						if (XHR.responseText.length > 0) {
							$("#fancy_content").html(XHR.responseText);
						}
						else {
							// TODO: JS Function callback support
							//$.fn.fancybox.close();
							location.reload(false);
						}
					}
				});

			return false;
		}
		else {
			return true;
		}
	});
}
catch (e) {
	// Log the error on Firebug, if it exists
	if (window.console && window.console.firebug) {
		console.error(e);
	}
}


/*
 * Utility functions
 */

function trim(s)
{
	return rtrim(ltrim(s));
}

function ltrim(s)
{
	var l=0;
	while(l < s.length && s[l] == ' ')
	{	l++; }
	return s.substring(l, s.length);
}

function rtrim(s)
{
	var r=s.length -1;
	while(r > 0 && s[r] == ' ')
	{	r-=1;	}
	return s.substring(0, r+1);
}

/*
 * Tab system
 */

function switchTab(element)
{
	// Retrieve the name of the tab group
	var elementName = $(element).attr('href').match(/#(.*)\./);

	if (elementName != null && elementName.length > 1) {
		var contentList = $("div[id^='" + elementName[1] + "']");
		var selectedContentId = $(element).attr('href').replace(/\./g, '\\.');
		var tabId;

		// Only proceed if the selected tab is not visible
		if ($(selectedContentId).css('display') == 'none') {
			for (n = 0; n < contentList.length; n++)
			{
				// Search for the currently visible tab
				if ($(contentList[n]).css('display') != 'none') {
					// Toggle the currently visible tab
					tabId = '#' + $(contentList[n]).attr('id').replace(/\./g, '\\.') + '\\.tab';
					$(tabId).removeClass('active');
					$(contentList[n]).toggle();

					// Toggle the selected tab
					tabId = selectedContentId + '\\.tab';
					$(tabId).addClass('active');
					$(selectedContentId).toggle();
					break;
				}
			}
		}
	}
}

/*
 * Category selection system
 */

function show_category(tag_id, header_id) {
  $(".header_div_"+tag_id).removeClass('bold');
  $(".header_"+tag_id+"_"+header_id).addClass('bold');
  $(".cat_div_"+tag_id).hide();
  $(".category_"+tag_id+"_"+header_id).show();
}

function select_category(element, tag_id, header_id, category_id) {
  /* ==[ WARNING ]===========================================================
   * This function is wrapped by the function limit_select_category.
   * Changes made to the parameter list must be implemented in that function.
   * ======================================================================== */

  // The user selects all categories of the header
  if (category_id == null) {
    var num_available = $(".category_"+tag_id+"_"+header_id+" .checkbox input").length;
    var num_checked = $(".category_"+tag_id+"_"+header_id+" .checkbox input:checked").length;
    var checked = false;
    
    if (num_available > num_checked) checked = true;

    $(".category_"+tag_id+"_"+header_id+" .checkbox input").each(function() {
      var id = parseInt($(this).attr('id').replace('CategoryCategory', ''));

      $(this).attr('checked', checked);

      select_category(this, tag_id, header_id, id);
    });
  }
  else {
	  if( $("#CategoryCategory"+category_id).attr('checked')) {
	    if ($('.cat_selected_'+category_id).length == 0) {
			// Insert the category name into the selected categories area
			$("#CategoryCategory"+category_id).siblings().each( function() {
			  $(".selected_categories").append( '<span class="cat_selected_'+category_id+'">'+$(this).html()+'</span>' );
			})
		}
	  } else {
		// Remove the name of the categories on the selected categories area
		$(".selected_categories .cat_selected_"+category_id).remove();
	  }

	  var size_selected_categories = $('.selected_categories').html().length;

    // Show the selected categories area if hidden
	  if ($(".selected_categories:hidden") && size_selected_categories > 0) {
		  $(".selected_categories").show();
	  }
	  else if (size_selected_categories == 0) {
		  $('.selected_categories').hide();
	  }
  }
}

function limit_select_category(element, tag_id, header_id, category_id)
{
  if ($('.search-categories .container input:checked').length > 6) {
    if (element && $(element).attr('checked')) {
      $(element).attr('checked', false);
      alert('You cannot select more than 6 categories.');
    }
  }
  else {
    select_category(element, tag_id, header_id, category_id)
  }
}

/*
 * Empty on click the default values of inputs.
 */

function empty_first(input_element)
{
	if ($.inArray(input_element, empty_inputs) == -1) {
		$(input_element).val('');
		empty_inputs.push(input_element);
	}
}

/*
 * Star rating functions
 */

function write_rate()
{
	var value = $('.star', this).length - 1;
	$('input[type=hidden]', this).val(value);
}

function rating_paint(element)
{
	if (element instanceof jQuery == false) element = this;
	
	$(element).prevAll().addClass('star');
	$(element).addClass('star');
	$(element).nextAll().removeClass('star');
}

function rating_restore()
{
	var value = parseInt($('input[type=hidden]', this).val()) + 1;
	rating_paint($('li:nth-child(' + value + ')', this));
}

/*
 * Review comments behaviors
 */

function view_comments()
{
	var commentlist = $(this).attr('href');
	
	if ($(commentlist) != undefined) {
		if ($(commentlist).is(":visible")) {
			$(commentlist).fadeOut();
		}
		else {
			$(commentlist).fadeIn();
		}
	}
	
	return false;
}

function preview_listing()
{
  var form = $(this).parents('form');

  $.ajax({
    type: 'POST',
		url: '/listings/preview',
		data: $(form).serialize(),
		dataType: 'html',
		complete: function (XHR, status, e) {
      if (XHR.responseText.length > 0) {
        $("#listing-preview-content").html(XHR.responseText);
        $("#listing-preview-link").click();
      }
    }
	});

  return false;
}

/*
 * jQuery's onDocumentReady event
 */
$(document).ready(function() {
	$('.dynamic-star-rating').each(function() {
		$(this).bind('mouseout', rating_restore);
		$(this).bind('click', write_rate);
		$(this).children().each(function() {
			$(this).bind('mouseover', rating_paint);
		});
	});

  $('#listing-preview-button').bind('click', preview_listing);
  $('#listing-preview-link').fancybox($.extend(popup_settings, {'frameHeight': 500, 'frameWidth': 700}));
  $('#register_cloudshare').fancybox($.extend(popup_settings, {'frameHeight': 500, 'frameWidth': 700}));
  $('#request_livedemo').fancybox($.extend(popup_settings, {'frameHeight': 600, 'frameWidth': 700}));
  
	// View comments code
	$('a.view-comments-link').bind('click', view_comments);
	$('a.add-comment-link').each(function() {
		$(this).fancybox($.extend(popup_settings, {'frameHeight': 390}));
	});

	// Behaviour for Other checkboxes and their respective Other (text fields) 
  $(".listing_form .other[type=checkbox]").each( function() {
    $(this).bind("click", function() {
      var target_selector = ".listing_form ."+$(this).attr("rel")+"_specific";
      if( !$(target_selector).attr('disabled') ) {
				$(target_selector).attr('disabled', 'disabled');
				$(target_selector).val('');
			} else {
        $(target_selector).removeAttr('disabled');
      }
    })
  });

  // Check for tab links
  var tab_id = window.location.toString().match(/#.+/);

  if (tab_id != null) {
    var new_tab = $('a[href=' + tab_id + ']');

    if (new_tab != null) {
      $(new_tab).click();
    }
  }

  if ($.fn.fancybox != undefined) {
	  $('#editorial_guidelines_link').fancybox( $.extend(popup_settings, {'frameHeight': 600, 'frameWidth': 700}) );
	  $('#review_guidelines_link').fancybox( $.extend(popup_settings, {'frameHeight': 300, 'frameWidth': 700}) );
  }
});


/** Limit characters **/
/** textaera limit **/
function limitChars(textid, limit, infodiv) {
    var text = $(textid).val();
    var textlength = text.length;
    if(textlength > limit){
        $('#' + infodiv).html('0').attr('style','color:red; font-weight: bold');
        $(textid).val(text.substr(0,limit));
        return false;
    } else {
        $('#' + infodiv).html(limit - textlength).attr('style',false);
        return true;
    }
}
