function strtrim() {
	return this.replace(/^\s+/,'').replace(/\s+$/,'');
}

String.prototype.trim = strtrim;


function formatNumber(value) {
	value += '';
	var integerDecimals = value.split(".");
	var integer = integerDecimals[0];
	var decimals = integerDecimals.length > 1 ? '.' + integerDecimals[1] : '';
	var rgx =  /(\d+)(\d{3})/;
	while (rgx.test(integer)) {
	  integer = integer.replace(rgx, '$1' + ',' + '$2');
	}
	return integer + decimals;
}


function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function createCookie(name,value,minutes) {
	if (minutes) {
		var date = new Date();
		date.setTime(date.getTime()+(minutes*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}




$(document).ready(function() {
	//Nav drop-downs
	$("#nav ul li").hover(function() {
		$(this).addClass("mouseOver");
	}, function() {
		$(this).removeClass("mouseOver");
	});
	
	
	//table filters
	$('.filterable').each(function (){
		buildFilters(this);
	})
	
	//photo galleries
	$(".photoGallery").each(function() {
	  buildPhotoGallery(this);
	});
	
	
	//review title 'quick jumps'
	$(".quickJump span.quickJumpLabel").click(function() {
   	$(this).parent().children("table").toggle();
  });
  $(".quickJump table td.close div span").click(function() {
    $(".quickJump table").hide();
  });
	
});


var ignoreFilterValue = "*.*.*"
function sortFiltersByName(fv1,fv2) {
	if (fv1.name > fv2.name) {
		return 1;
	} else if (fv1.name == fv2.name) {
		return 0;
	} else {
		return -1;
	}
}

function buildFilters(wd) {
	var filters = {};
	var filterLabels = {};
	//looks through filter data in the table and builds filters
	$(wd).find("table td.filterAttributes").each(function() {
		$(this).children("div").each(function() {
			if (typeof(filters[this.className]) === 'undefined') {
				filters[this.className] = [];
				filterLabels[this.className] = $(this).children(".filterLabel").text();
			}
			//for range filters
			if ($(this).children(".range").length > 0) {
				if (filters[this.className].length === 0) {
					var fName = this.className
					$(this).children(".range").each(function() {
						filters[fName].push({name: $(this).children(".rangeName").text(), value: $(this).children(".rangeValue").text()});
					});
				}
			} else if ($(this).children(".option").length > 0) {
				//for data that has 1-n values
				var fName = this.className
				$(this).children(".option").each(function() {
					var fVal = {name: $(this).text(), value: $(this).text()};
					var inList = false;
					var listSize = filters[fName].length;
					for(var i=0;i<listSize;i++) {
						if (fVal.name === filters[fName][i].name) {
							inList = true;
							break;
						}
					}
					if (!inList) {
						filters[fName].push(fVal);
					}
				});			  
			}	else {
				//for regular single-value select filters
				var fVal = $(this).children(".value").text();
				if ($.inArray(fVal, filters[this.className])===-1) {
					filters[this.className].push(fVal);
				}
			}
		})
	});
	
	
	var fHead = "<tr>";
	var fBod = "<tr>";
	for (var filterName in filters) {
	  var fLabel='';
	  if (typeof(filterLabels[filterName]) == 'undefined' || filterLabels[filterName].trim() == '') {
	    fLabel = filterName.replace('_', ' ');
	  } else {
	    fLabel = filterLabels[filterName];
	  }
		var fvs = filters[filterName];
		var fvLen = fvs.length;
		if (fvLen > 1) {
			fHead += "<th>" + fLabel + "</th>";
			fBod += "<td><div class='filterList "+filterName+" '>";
			fBod += "<div><input type='checkbox' checked='checked' value='"+ignoreFilterValue+"'/> <strong>"+allLabel+"</strong></div>";
			if (typeof(fvs[0]) !== "object") {
				fvs.sort();
			}
			for (var i=0;  i<fvLen; i++) {
				var fv = fvs[i];
				var fVal = fv;
				var fName = fv;
				if (typeof(fVal)==="object") {
					fVal = fv.value
					fName = fv.name
				}
				if (fVal.trim() != '') {
	  			fBod += "<div>";
	  			fBod += "<input type='checkbox' value='"+fVal+"' /> "
	  			fBod += fName;
	  			fBod += "</div>"
	  		}
			}
			fBod += "</div></td>";
		}
	}
	fBod += "</tr>";
	fHead += "</tr>";

	var fTable = "<table class='rankingsFilter' id='" + wd.id + "_filters'>" + fHead + fBod + "</table>";
	
	$(wd).children("h3").after(fTable);
	
	$(wd).find("input").click(function() {
		if (this.value === ignoreFilterValue) {
			//Uncheck all others
			$(this).parents(".filterList").find("input").attr('checked', false);
			this.checked = true;
		} else {
			$(this).parents(".filterList").find("input[value='"+ignoreFilterValue+"']").attr('checked', false);
		}
		executeFilters($(wd).find("table:not(.rankingsFilter)"), $(wd).find("table.rankingsFilter"));
	});
	
}


function executeFilters(table, filterTable) {
	var filters = {};
	filterTable.find(".filterList").each(function() {
		var filterName = this.className.replace('filterList ', '');
	  var values = [];
		$(this).find("input:checked").each(function() {
			values.push(this.value);
		})
		filters[filterName] = values;
	});
	
	
	table.find("tbody > tr").each(function() {
		keep = true;
		
		for (var filterName in filters) {
			var values = filters[filterName]
			if ($.inArray(ignoreFilterValue, values)===-1) {
				//console.log('checking', filterName, values)
				var rowValue = $(this).find(".filterAttributes ."+filterName+ " .value").text();
				if ($(this).find(".filterAttributes ."+filterName+ " .range").length > 0) {
					//Range comparison
					rowValue = parseFloat(rowValue);
					var valLen = values.length;
					for (var i=0; i<valLen; i++) {
						var rangeMatch = true
						var ranges = values[i].split(',');
						if (ranges.length === 2) {
							//check min
							if (ranges[0].length > 0 && parseFloat(ranges[0]) > rowValue) {
								rangeMatch=false;
							}
							if (ranges[1].length > 0 && parseFloat(ranges[1]) <= rowValue) {
								rangeMatch=false;
							}
						}
						if (rangeMatch) {
							break;
						}
					}
					keep = rangeMatch
					if (!keep) {
						break;
					}
				} else if ($(this).find(".filterAttributes ."+filterName+ " .option").length > 0) {
				  var rowValues = rowValue.split(',');
				  var valLen = rowValues.length;
				  //var
				  keep = false;  
				  for (var i=0; i < valLen; i++) {
				    if ($.inArray(rowValues[i].trim(), values) != -1) {
				      keep=true;
				      break;
				    }
				  }
				  if (!keep) {
				    break;
				  }
				} else {
					//Normal comparison
					if ($.inArray(rowValue, values)===-1) {
						keep = false;
						break;
					}
				}
			}
		}
		
		if (!keep) {
			$(this).hide();
		} else {
			$(this).show();
		}
		
	});
}




function buildPhotoGallery(wd) {
  var items = $(wd).children(".galleryItem");
  items.hide();
  $(items[0]).addClass("first").show();
  $(items[items.length-1]).addClass("last");
  $(wd).prepend("<div class='controls controlsPrev'></div>");
  $(wd).append("<div class='controls controlsNext'></div>");
  $(wd).children(".controlsPrev").hide();
  
  $(wd).children(".controls").click(function() {
    var curImage = $(this).parent().children(".galleryItem:visible");
    if ($(this).hasClass("controlsPrev")) {
      var nextImage = curImage.prev(".galleryItem");
    } else {
      var nextImage = curImage.next(".galleryItem");
    }
    
    curImage.fadeOut(function() {
      nextImage.fadeIn();
    });
    if (nextImage.hasClass("last")) {
      nextImage.parent().children(".controlsNext").hide();
    } else {
      nextImage.parent().children(".controlsNext").show();  
    }
    if (nextImage.hasClass("first")) {
      nextImage.parent().children(".controlsPrev").hide();
    } else {
      nextImage.parent().children(".controlsPrev").show();  
    }
  });
}




function fixComparedTos() {
   $(".subRatings .quickJump-Ratings").css("float","none");
   $(".subRatings .quickJump-Ratings").css("float","right");
   $(".subRatings .quickJump-Ratings").css("top",0);
}






