//show/hide the filter boxes depending on dslr vs point-and-shoot

var filters;

function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}




function chooseFilterBoxes() {
        var pncs = $("td.cat-5");
	var dslrs = $("td.cat-52");
	if (pncs.length > 0 && dslrs.length > 0) {
		pncs.hide();
		dslrs.hide();
		$("table#filter tr:first").append("<td colspan='2' width='200' class='filter_header filler-cat'></td>");
		$("table#filter tr:last").append("<td colspan='2' class='filler-cat'></td>");
		
		$("table#filter tr:last td.filler-cat").prepend("<div class='select-cat'>" + 
		  "<span class='cat-5'>Filter Point &amp; Shoot Reviews <img src='/images/Cameras.gif'/></span> " + 
		  "<span class='cat-52'>Filter Digital SLR Reviews <img src='/images/SLR-Cameras.gif'/></span></div>");
		
		$("span.cat-5").click(function() {
		  $("div.select-cat span").removeClass('selected');
		  $(this).addClass('selected');
		  $("td.filler-cat").hide();
		 // $("div.select-cat").hide();
		  dslrs.hide();
		  pncs.show();
		  $("#cat_id").attr('value', '5');
		  $("table.cat-52, h2.cat-52").hide();
		  $(".quickJump-Ratings-Table").hide();
		  fixComparedTos();
		});
		
		$("span.cat-52").click(function() {
		  $("div.select-cat span").removeClass('selected');
		  $(this).addClass('selected');
		  $("td.filler-cat").hide();
		//  $("div.select-cat").hide();
		  pncs.hide();
		  dslrs.show();
		  $("#cat_id").attr('value', '52');
		  $("table.cat-5, h2.cat-5").hide();
		  $(".quickJump-Ratings-Table").hide();
		  fixComparedTos();
		});

	}
	activateFilters();
}

function activateFilters() {
	
	$("#filter input:checkbox").click(function() {
	  if (this.value == "All") {
  	  	$("#filter input[name="+ this.name + "]").attr("checked", false);
  	  	this.checked=true;
  	  } else {
  	  	$("#filter input[name="+ this.name + "]").get(0).checked=false;
	  }
	  var none_checked = true;
	  $("#filter input[name="+ this.name + "]").each(function() {
		if (this.checked) {
			none_checked = false;
		}
  	  });
	  if (none_checked) {
		  $("#filter input[name="+ this.name + "]").get(0).checked=true;
  	}
	  $(".quickJump-Ratings-Table").hide();
    doFiltering();
	  
	});
	
	
}

function doFiltering() {
	  
	  filters = {
	            "man552": [],
	            "type5": [],
	            "type52": [],
              "price5": [],
              "price52": [],
              "zoom_range5": [],
              "pixels5": [],
	            "pixels52": []
              };
	  
	  // look at each filter
	  for(var filter in filters) {
	    $("#filter input[name="+filter+"\\[\\]]").each(function() {
	      if (this.checked) {
	        filters[filter].push(this.value);
	      }
	    })
	  }
	
	  var filter_limit = $("#filter_limit").attr('value');	
	  if (typeof(filter_limit) != 'undefined' && filter_limit != '') {
		filter_limit = parseInt(filter_limit);
	  } else {
		filter_limit = 0;
	  }
	
	  //apply the filters
	  var line_count = 0;
	  $("table.cat-5 > tbody > tr, table.cat-52 > tbody > tr").each(function() {
		  var filterVals = $(this).find("div.filterableValues");
		  if (filter_limit > 0 && line_count >= filter_limit) {
			$(this).hide();
		  } else {
		
			  if (filterVals.length > 0) {
					var show = true;
					if (filters["man552"].length > 0 && filters["man552"][0] != "All") {
						var manVal = $(filterVals).find("span.man552").text();
						show = show && (manVal in oc(filters["man552"]));
					}
			
					var tcId = $("#cat_id").attr('value');
					if (tcId != '5,52') { 
						if (filters["type" + tcId].length > 0 && filters["type" + tcId][0] != "All") {
							var typeVal = $(filterVals).find("span.type" + tcId).text();
							show = show && (typeVal in oc(filters["type" + tcId]));
						}
						if (filters["price" + tcId].length > 0 && filters["price" + tcId][0] != "All") {
							var priceVal = $(filterVals).find("span.price" + tcId).text();
							priceVal = parseFloat(priceVal);
							priceMatch = false;
							for(var i=0; i < filters["price" + tcId].length; i++) {
								var limits = filters["price" + tcId][i].replace(/\$/g,'').split('-');
								if (limits.length == 1) {
									if (limits[0].indexOf('+') != -1) {
										priceMatch = priceMatch || priceVal >= parseFloat(limits[0].replace('+',''));
									}
								} else if (limits.length == 2) {
									var minPrice = parseFloat(limits[0]);
									var maxPrice = parseFloat(limits[1]);
									priceMatch = priceMatch || (priceVal >= minPrice && priceVal <= maxPrice);
								}
							}
							show = show && priceMatch;
						}
						if (typeof(filters["zoom_range" + tcId]) != 'undefined') {
							if (filters["zoom_range" + tcId].length > 0 && filters["zoom_range" + tcId][0] != "All") {
								var zoom_rangeVal = $(filterVals).find("span.zoom_range" + tcId).text();
								zoom_rangeVal = parseFloat(zoom_rangeVal);
								zoomMatch = false;
								for(var i=0; i< filters["zoom_range" + tcId].length; i++) {
									var limits = filters["zoom_range" + tcId][i].split('->');
									if (limits.length == 2) {
										var minZoom = 0;
										var maxZoom = 100000000;
										if (limits[0] != '*') {
											minZoom = parseFloat(limits[0]);
										}
										if (limits[1] != '*') {
											maxZoom = parseFloat(limits[1]);
										}
										zoomMatch = zoomMatch || (zoom_rangeVal >= minZoom && zoom_rangeVal <= maxZoom);
									}
								}
							
								show = show && zoomMatch;
							}
						}
						if (filters["pixels" + tcId].length > 0 && filters["pixels" + tcId][0] != "All") {
							var pixelsVal = $(filterVals).find("span.pixels" + tcId).text();
							pixelsVal = parseFloat(pixelsVal);
							pixMatch = false;
							for(var i=0; i< filters["pixels" + tcId].length; i++) {
								var limits = filters["pixels" + tcId][i].split('->');
								if (limits.length == 2) {
									var minPix = 0;
									var maxPix = 100000000;
									if (limits[0] != '*') {
										minPix = parseFloat(limits[0]);
									}
									if (limits[1] != '*') {
										maxPix = parseFloat(limits[1]);
									}
									pixMatch = pixMatch || (pixelsVal >= minPix && pixelsVal <= maxPix);
								}
							}
						
							show = show && pixMatch;
						}
					
					
					}		
					if (show) {
						line_count += 1;
						$(this).show();
					} else {
						$(this).hide();
					}
				}
			}
		});
	
	  $("table.cat-5, table.cat-52").each(function() {
	    //var shown_rows=$(this).find("tbody > tr:not(:hidden)").length;
	    var shown_rows = 0;
	    
	    $(this).find("tbody > tr").each (function() {
	      if ($(this).css("display") != 'none' && $(this).parents("table.subRatingsRow").length == 0) {
	        shown_rows += 1;
	      }
	    });
	    
	    if (shown_rows == 0) {
	      $(this).find("tfoot tr.noResults").show();
	    } else {
	      $(this).find("tfoot tr.noResults").hide();
	    }
	    
	  })
	  fixComparedTos();
}

function fixComparedTos() {
  $(".subRatings .quickJump-Ratings").css("float","none");
  $(".subRatings .quickJump-Ratings").css("float","right");
  $(".subRatings .quickJump-Ratings").css("top",0);
  /* $("table:not(:hidden)").each(function() {
    $(this).hide();
    $(this).show();
  }); 
  $(".subRatings .quickJump-Ratings").hide().show();
  */
}


// Exclusively for model table filters
// Objectified so that it's compatible with the rest of the filter changes.
// Haven't bothered to fix much of the code--it could probably be
//   refactored immensely to take advantage of JQuery and the object.
function catFilters() {
	this.catid	= 0;
	
	this.ClearFilters = function() {
		for(i=1;i<$('input[name="man'+this.catid+'[]"]').length;i++){
			$('#man'+this.catid+'_'+i).attr('checked', false);
		}
		$('#man'+this.catid+'_0').attr('checked', true);

		for(i=1;i<$('input[name="type'+this.catid+'[]"]').length;i++){
			$('#type'+this.catid+'_'+i).attr('checked', false);
		}
		$('#type'+this.catid+'_0').attr('checked', true);

		for(i=1;i<$('input[name="price'+this.catid+'[]"]').length;i++){
			$('#price'+this.catid+'_'+i).attr('checked', false);
		}
		$('#price'+this.catid+'_0').attr('checked', true);

		this.BuildData();
	}
	
	this.SelectAll_Man = function() {
		if($('#man'+this.catid+'_0').attr('checked')==true){
			pageTracker._trackEvent("Filters", "Reset Manufacturer Filters");
			for(i=1;i<$('input[name="man'+this.catid+'[]"]').length;i++){
				$('#man'+this.catid+'_'+i).attr('checked', false);
			}
		}
		
		$('#man'+this.catid+'_0').attr('checked', true);
		
		this.BuildData();
	}

	this.SelectAll_Type = function() {
		if($('#type'+this.catid+'_0').attr('checked')==true){
			pageTracker._trackEvent("Filters", "Reset Type Filters");
			for(i=1;i<$('input[name="type'+this.catid+'[]"]').length;i++){
				$('#type'+this.catid+'_'+i).attr('checked', false);
			}
		}
		
		$('#type'+this.catid+'_0').attr('checked', true);

		this.BuildData();
	}

	this.SelectAll_Price = function(){
		if($('#price'+this.catid+'_0').attr('checked')==true){
			pageTracker._trackEvent("Filters", "Reset Price Filters");
			for(i=1;i<$('input[name="price'+this.catid+'[]"]').length;i++){
				$('#price'+this.catid+'_'+i).attr('checked', false);
			}
		}

		$('#price'+this.catid+'_0').attr('checked', true);

		this.BuildData();
	}

	this.SelectAll_Filter = function() {
		if($('#filter'+this.catid+'_0').attr('checked')==true){
			pageTracker._trackEvent("Filters", "Reset Special Filters");
			for(i=1;i<$('input[name="filter'+this.catid+'[]"]').length;i++){
				$('#filter'+this.catid+'_'+i).attr('checked', false);
			}
		}

		$('#filter'+this.catid+'_0').attr('checked', true);

		this.BuildData();
	}
	
	this.SelectMan = function(id) {
		var is_all_blank=1;
		
		for(i=0;i<$('input[name="man'+this.catid+'[]"]').length;i++){
			if($('#man'+this.catid+'_'+i).attr('checked')==true)
				is_all_blank=0;
		}
		
		if(is_all_blank==0) {
			pageTracker._trackEvent("Filters", "Added Manufacturer Filter");
			$('#man'+this.catid+'_0').attr('checked', false);
		}
		else
			$('#man'+this.catid+'_0').attr('checked', true);
		
		this.BuildData();
	}
	
	this.SelectType = function(id) {
		var is_all_blank=1;
		
		for(i=0;i<$('input[name="type'+this.catid+'[]"]').length;i++){
			if($('#type'+this.catid+'_'+i).attr('checked')==true)
				is_all_blank=0;
		}
		
		if(is_all_blank==0) {
			pageTracker._trackEvent("Filters", "Added Type Filter");
			$('#type'+this.catid+'_0').attr('checked', false);
		}
		else
			$('#type'+this.catid+'_0').attr('checked', true);

		this.BuildData();	
	}

	this.SelectPrice = function(id){
		var is_all_blank =1;
		
		for(i=0;i<$('input[name="price'+this.catid+'[]"]').length;i++){
			if($('#price'+this.catid+'_'+i).attr('checked')==true)
				is_all_blank=0;
		}

		if(is_all_blank==0) {
			pageTracker._trackEvent("Filters", "Added Price Filter");
			$('#price'+this.catid+'_0').attr('checked', false);
		}
		else
			$('#price'+this.catid+'_0').attr('checked', true);
		
		this.BuildData();
	}

	this.SelectFilter = function(id) {
		var is_all_blank=1;
		
		for(i=0;i<$('input[name="filter'+this.catid+'[]"]').length;i++){
			if($('#filter'+this.catid+'_'+i).attr('checked')==true)
				is_all_blank=0;
		}
		
		if(is_all_blank==0) {
		//	pageTracker._trackEvent("Filters", "Added Special Filter");
			$('#filter'+this.catid+'_0').attr('checked', false);
		}
		else
			$('#filter'+this.catid+'_0').attr('checked', true);
		
		this.BuildData();
	}
	
	this.BuildData = function() {
		var query_string;
		
		var man_array = new Array();
		var man_flags = new Array();
		
		var type_array = new Array();
		var type_flags = new Array();

		var price_array = new Array();
		var price_flags = new Array();
		
		var filter_array = new Array();
		var filter_flags = new Array();
		
		var cat_id = $('#cat_id').attr("value");
		
		for(i=0;i<$('input[name="man'+cat_id+'[]"], input[name="man552[]"]').length;i++){
			man_array[i] = $('#man'+cat_id+'_'+i+', #man552_'+i).attr('value');
			man_flags[i] = $('#man'+cat_id+'_'+i+', #man552_'+i).attr('checked');
		}

		for(i=0;i<$('input[name="type'+cat_id+'[]"], input[name="type552[]"]').length;i++){	
			type_array[i] = $('#type'+cat_id+'_'+i+', #type552_'+i).attr('value');
			type_flags[i] = $('#type'+cat_id+'_'+i+', #type552_'+i).attr('checked');
		}
	
		try{
			for(i=0;i<$('input[name="price'+cat_id+'[]"], input[name="price552[]"]').length;i++){	
				price_array[i] = $('#price'+cat_id+'_'+i+', #price552_'+i).attr('value');
				price_flags[i] = $('#price'+cat_id+'_'+i+', #price552_'+i).attr('checked');
			}
		}
		catch(e){
		}
		
		try{
			for(i=0;i<$('input[name="filter'+cat_id+'[]"], input[name="filter552[]"]').length;i++){
				filter_array[i] = $('#filter'+cat_id+'_'+i+', #filter552_'+i).attr('value');
				filter_flags[i] = $('#filter'+cat_id+'_'+i+', #filter552_'+i).attr('checked');
			}
		}
		catch(e){
		}
		
		
		//These are not pretty, but they do work.
		if(man_array != '')
			query_string = "&man_array=" + man_array + "&man_flags=" + man_flags;
		
		if(type_array != '')
			query_string += "&type_array=" + type_array + "&type_flags=" + type_flags;
		
		if(price_array != '')
			query_string += "&price_array=" + price_array + "&price_flags=" + price_flags;
			
		if(filter_array != '')
			query_string += '&filter_array=' + filter_array + '&filter_flags=' + filter_flags;

	
		query_string += "&cat_id=" + $('#cat_id').attr('value');
		query_string += "&spec_table=" + $('#spec_table').attr('value');
		query_string += "&stype_id=" + $('#stype_id').attr('value');
		query_string += "&sortBy=" + $('#sortby').attr('value');
		query_string += "&rating_tables=" + $('#rating_tables').attr('value');
		
		$('#model_box').html('<div class="ajax_load">Loading</div>');
    // if (console.log) {
    //  console.log(query_string); 
    //    }

		$.get(
				'/assets/model-table.php?'+query_string,
				function(data) {
					$('#model_box').html(data);
					addTableSort();
				}
			);
	}
}

// the flexible checking thing
$(function() {
/*	This is screwed up since changing stuff to work with multiple instances.
	Latest revisions have different function calls [part of an object now]
	as well as checkbox names and IDs, which now include a category identifier.
	
	$('.subcat-noentries div').click(function(e) {
		var input = $(this).children('input');
		if(e.target.tagName == 'DIV')
			input.attr('checked', !input.attr('checked'));
		
		if(input.attr('name') == 'man[]') {
			if(input.attr('id') == 'man0')
				SelectAll_Man();
			else
				SelectMan(input.attr('id'));
		}
		else if(input.attr('name') == 'type[]') {
			if(input.attr('id') == 'type0')
				SelectAll_Type();
			else
				SelectType(input.attr('id'));
		}
		else if(input.attr('name') == 'price[]') {
			if(input.attr('id') == 'price0')
				SelectAll_Price();
			else
				SelectPrice(input.attr('id'));
		}
		else if(input.attr('name') == 'filter[]') {
			if(input.attr('id') == 'filter0')
				SelectAll_Filter();
			else
				SelectFilter(input.attr('id'));
		}
	});*/
});





function zoom(ipath){
	if(ipath=='close'){
		$('#zoomer').fadeOut('fast');
		$('#zoom_image').html('');
	}	
	else{
		$('#zoomer').hide();
		$('#zoom_image').html('<img src="http://www.reviewed.com/' + ipath + '" /> ');
		$('#zoomer').css('top', aY).css('left', aX).fadeIn('fast');
	}
}

function opacity(id,opacity) { 
	var object = document.getElementById(id).style; 
	object.opacity = (opacity / 100); 
	object.MozOpacity = (opacity / 100); 
	object.KhtmlOpacity = (opacity / 100); 
	object.filter = "alpha(opacity=" + opacity + ")"; 
} 


var answer_id = 0;
var aX = 0;
var aY = 0;

$(function() {
 if($('#cr_wrapper').length > 0) {

	$(document).click(function(e) {
		aX = e.pageX;
		aY = e.pageY;
	});
	
	if($('#cr_answer_id').length > 0) {
		var tmp = $('#cr_answer_id').text().split('~');
		var tmp2 = '';
		answer_id = tmp[0]-0;
		if(tmp[1].length > 0)
			tmp2 = " named '<b>"+tmp[1]+"</b>'";
		$('#cr_wrapper').html(
				 '<div id="cr_links"></div>'
				+'<h2 style="margin:0;text-align:center;font-weight:normal">Your previously customized {cat_name} ratings'+tmp2+' are below.</h2>'
				+'<div class="center">You can further refine the custom ratings with the filters above for manufacturer, type and price.</div>'
			);
		$('#cr_links').html('Loading...').load('/assets/ajax/custom-ratings-handler.php?grab=toplinks&iw=1&id='+answer_id);
		showCR();
		BuildData();
	}

	$('#cr_launch').click(function(e) {
		e.preventDefault();
		pageTracker._trackEvent("Custom Ratings", "Start", "{cat_name}");
		$('#cr_wrapper').load(
				'/assets/ajax/custom-ratings-inline-wizard.php?cat={cat_id}&stage=0',
				{},
				function() {
					showCR();
					$('#cr_cancel').click(function(f) {
						f.preventDefault();
						removeCR();
					});
					// start question loop
					getNextQuestion();
				}
			);
	});

	var queue = '';
	function getNextQuestion() {
		$('#cr_next').unbind().click(function(e) {
			e.preventDefault();
			pageTracker._trackEvent("Custom Ratings", "Question "+($('#cr_count').html()-0+1)+" Submit", "{cat_name}");
			
			if($('#cr_form').serialize().length > 2)
				queue += '&'+$('#cr_form').serialize();
			
			$('#cr_question').slideUp('fast').load(
				$('#cr_form').attr('action'),
				{},
				function() {
					$('#cr_count').html($('#cr_count').html()-0+1);
					$('#cr_question').slideDown('normal');
					
					// make sure we don't go too far
					if($('#cr_count').html() < $('#cr_last').html())
						getNextQuestion();
					else
						endWizard();
				}
			);
		});
	}
	
	function endWizard() {
		$('#cr_next').unbind().click(function(e) {
			e.preventDefault();
			pageTracker._trackEvent("Custom Ratings", "Final Question Submit", "{cat_name}");
			
			if($('#cr_form').serialize().length > 2)
				queue += '&'+$('#cr_form').serialize();
			
			if(queue.length < 2) {
				$('#cr_wrapper').html('<div class="center">You must answer at least one question for the custom ratings to haev any effect.</div>');
				$('#cr_launch').slideDown('slow');
				return;
			}
			
			$.get(
				'/assets/ajax/custom-ratings-inline-wizard.php?cat={cat_id}&stage=2'+decodeURI(queue),
				function(data) {
					answer_id = data;
					if(parseInt(answer_id) > 0) {
						$('#cr_wrapper').html(
								 '<div id="cr_links"></div>'
								+'<h2 style="margin:0;text-align:center;font-weight:normal">Your customized {cat_name} ratings are below.</h2>'
								+'<div class="center">You can further refine the custom ratings with the filters above for manufacturer, type and price.</div>'
							);
						$('#cr_links').html('Loading...').load('/assets/ajax/custom-ratings-handler.php?grab=toplinks&iw=1&id='+answer_id);
						BuildData();
					}
					else {
						$('#cr_wrapper').html('<div class="center">There was an error in the custom ratings engine--sorry for the inconvenience!</div>');
						$('#cr_launch').slideDown('slow');
					}
				}
			);
		});
	}

} });

/* post-wizard link bar junk, jQuerified. */
function openDiv(div) {
	$('#'+div).css('bottom', aY).css('left', aX + 10).fadeIn('normal');
	
	if(div == 'wtblk' && document.wt.type.value == 'login') {
		showLogin();
		$('#login').click(function() {
				openName();
				$('#login').unbind();
			});
		setTimeout("$('#wtblk').fadeOut('normal')",4237);
	}
}
function closeDiv(div) {
	$('#'+div).fadeOut('normal');
}
function openName() {
	var d = new Date();
	$('#wtform').load(
			'/assets/ajax/custom-ratings-handler.php?grab=nameform&id='+answer_id+'&'+d.getTime(),
			function() {
				openDiv('wtblk');
			}
		);
}
function submitForm() {
	if(document.wt.type.value == 'name') {
		$.get(
				'/assets/ajax/custom-ratings-handler.php?grab=subname&id='+answer_id+'&name='+document.wt.name.value,
				function() {
					pageTracker._trackEvent("Custom Ratings", "Saved ratings");
					$('#wtform').html('Your Custom Rating Was Successfully Saved!');
					setTimeout("closeDiv('wtblk')", 3000);
				}
			);
	}
}
function submitEmail() {
	var form = document.eml;
	$.post(
			'/assets/ajax/custom-ratings-handler.php?grab=email&id='+answer_id,
			{
				from_name: form.from_name.value,
				to_name: form.to_name.value,
				to_email: form.to_email.value
			},
			function() {
				pageTracker._trackEvent("Custom Ratings", "Emailed ratings");
				$('#emlform').html('Your Email Was Successfully Sent!');
				setTimeout("closeDiv('emlblk')", 3000);
			}
		);
}
function resetBox() {
	openDiv('rsblk');
}
function showCR() {
	$('#cr_launch').slideUp('slow');
	$('#cr_wrapper').css('borderBottom', '1px solid #ccc').slideDown('slow');
}
function removeCR() {
	pageTracker._trackEvent("Custom Ratings", "Reset ratings");
	$('#cr_launch').slideDown('slow');
	$('#cr_wrapper').slideUp('slow', function(){$(this).css('borderBottom', '0').html('');});
	// get rid of the answer log so it won't show up here again...
	$.get('/assets/ajax/custom-ratings-inline-wizard.php?cat={cat_id}&stage=3&q='+answer_id);
	answer_id = 0;
	BuildData();
}
