// Constructs SEO URL
function constructURL(page) {
  // Setup default variables
  var category = ($('#Category').val() == "") ? "" : "/" + $('#Category').val().toLowerCase().replace("&amp;", "").replace(/\s/gi, "_").replace("__", "_");
  var order = ($('#Order').val() == "") ? "" : "/" + $('#Order').val();
  var type = ($('#Type').val() == "") ? "" : "/" + $('#Type').val().toLowerCase();
  var srch = ($('#txtSearch').val() == "") ? "" : "/" + $('#txtSearch').val();
  var url = "/research";
  var perpage = ($('#per-page').val() == 25 || $('#per-page').val() == undefined) ? "" : "/" + $('#per-page').val();

  if (page == undefined) {
    page = "";
  } else if (page == "next") {
    page = "/page" + (parseInt($('.current').attr('rel')) + 1);
  } else if (page == "prev") {
    page = "/page" + (parseInt($('.current').attr('rel')) - 1);
  } else {
    page = "/page" + page;
  }


  if (perpage != "") {
    if(page == "") {
      page = "/page1";
    } 
    if(srch == "") {
      srch = "/all";
    } 
    if(type == "") {
      type = "/any";
    }    
    if(order == "") {
      order = "/recent";
    }
    if (category == "" || category == "/all_categories") {
      category = "/all_categories";
    }
  } else if (page != "") {
    if(srch == "") {
      srch = "/all";
    } 
    if(type == "") {
      type = "/any";
    }    
    if(order == "") {
      order = "/recent";
    }
    if (category == "" || category == "/all_categories") {
      category = "/all_categories";
    }
  } else if (srch != "") {
    if(type == "") {
      type = "/any";
    }    
    if(order == "") {
      order = "/recent";
    }
    if (category == "" || category == "/all_categories") {
      category = "/all_categories";
    }
  } else if(type != "" && type != "/any") {
    if(order == "") {
      order = "/recent";
    }
    if (category == "" || category == "/all_categories") {
      category = "/all_categories";
    }
  } else if (order != "" && order != "/recent") {
    type = "";
    if (category == "" || category == "/all_categories") {
      category = "/all_categories";
    }
  } else if (category == "" || category == "/all_categories") {
    srch = "";
    type = ""
    order = "";
    category = "";
  }
  url += category + order + type + srch + page + perpage;

  window.location = url;
}

$(document).ready(function(){

  $('.content-item:last').addClass('no-border');

  // Bind Category clicks
  $('#cat-list li a').click(function(){
    $('#Category').val($(this).html());
    constructURL();
  });

  // Bind order clicks
  $('.search-order').click(function(){
    $('#Order').val($(this).attr("rel"));
    constructURL();
  });

  // Bind type change
  $('#TypeDropDown').change(function(){
    $('#Type').val($(this).children("option:selected").html());
    constructURL();
  });

  // Bind type change
  $('#per-page').change(function(){
    constructURL();
  });


  // Track Views
  $('a.track').click(function(){
    var tracked;
    $.ajax({  type:     "POST",
              url:      "/ajax/metrics.php",
              data:     { type: "research",
                          key: $(this).attr('href')},
              async:    false,
              dataType: "json",
              success:  function(json){
                          tracked = json;
                        },
              error:    function() {
                          tracked = false;
                        } });
    return tracked;
  });

  // Toggle Categories
  $('.view').toggle(function(){
    $(this).html("(-) Hide all Categories");
    $('#cat-list').children().show();
  }, function(){
    $(this).html("(+) View all Categories");
    $('#cat-list').children('.hide').hide();  
  });

  $('div.pages span.clickable').click(function(){
    constructURL($(this).attr('rel'));
  });

  // Research Comments
  $('#comment-form').submit(function(){
    var comment = $.trim($('#comment').val());
    var errors = new Array();
    // Begin comment validation
    if(comment == "") {
      errors.push('Please enter a comment');
    }
    errors = contentCheck(comment, errors);
    
    if(errors.length > 0) {
      $().fyiMessage('init', {
        type: 'error',
        errors: errors,
        attach: $('#comment-box')
      });
    } else {
      $.ajax({
        url: '/professional/Research.php',
        type: 'post',
        dataType: 'json',
        data: {
          rid: $('#rid').val(),
          comment: comment
        },
        success: function(json) {
          function displayComment(markup) {
            $('.comment-count-span').animate({
              opacity: 0
            }, function(){
              var count = parseInt($(this).text());
              count++;
              $(this).text(count).animate({
                opacity: 1
              });
            });
            $('#comment').val("");
            $('#comment-list').append(markup).children('li:last').andSelf().slideDown();
          }

          if(json.loggedIn) {
            if ($('#no-comments').length > 0) {
              $('#no-comments').slideUp('normal', function() {
                $(this).replaceWith('<ul class="hidden" id="comment-list"><\/ul>');
                displayComment(json.markup);
              });
            } else {
              displayComment(json.markup);
            }
          } else {
            loginUser();
          }
        }
      });
    }    
    
    return false;
  });

  // Submit search helper
  $('#sfrm').submit(function(){
    constructURL()
    return false;
  });

  // Toggle input label
  $('#txtSearch').focus(function(){
    $(this).prev().hide();
  }).blur(function(){
    if($(this).val().length ==0){
      $(this).prev().show();
    }
  });

  // Toggle show details
  $('.detail-toggle').toggle(function(){
    $(this).html("Hide Details");
    $('.research-details').toggle();
  }, function(){
    $(this).html("Show Details");
    $('.research-details').toggle();  
  });
  
  // Handle Helpful Votes
	$('.vote').click(function(){
		var vote  = $(this);
		var ans = $.trim(vote.html());
		$.post("/professional/ajax/collateral-vote.php", {Answer: ans, Id: vote.attr("rel"), Type: "research"}, function(response){
      if (response == "false") {
        window.location = '/professional/NotLogin.php';
      } else if (ans == "Yes") {
				var helpful = vote.parent().prev().children(".spacer1").children(".helpful");
				var total = parseInt(helpful.html()) + 1;
				if (total >= 1000) {
					helpful.hide().html(total).removeClass('spacer2').addClass('spacer2-fourdigits').fadeIn("normal", function(){if(jQuery.browser.msie)$(this).get(0).style.removeAttribute('filter');});
				} else {
					helpful.hide().html(total).fadeIn("normal", function(){if(jQuery.browser.msie)$(this).get(0).style.removeAttribute('filter');});
				}
  			vote.parent().html('<span class="voted">' + ans + '</span>');
			}
		});
	});

});
