jQuery(function($) {
	$("img").lazyload({
		container: $("#container"),
		threshold: 500
	});
	if(typeof portfolioLoggedIn !== "undefined" ) { return; } // disable javascript if logged in
	$.history.init(pageload); 
	$("#container a").one('click', function() { $("#showAllLink").removeClass('noLink'); });
	$("#container a").click(function(e) {
		e.preventDefault();
		this.blur();
		$.history.load(getPortfolioStory(this));

	});
	$("select#country").change(function(e) {
		if(this.value === "United States") {
			$("select#state").show().attr('selectedIndex', 0);
			$("select#state")[0].selectedIndex = 0;
			$("select#province").hide();
		} else if(this.value === "Canada") {
			$("select#province").show();
			$("select#province")[0].selectedIndex = 0;
			$("select#state").hide();
		} else {
			$("select#state").hide();
			$("select#province").hide();
		}
	});
	$("#linkList .linksTable a").live('click', function(e) {
		$(".main-content .hovering").removeClass("hovering");
		var thishref = this.href;
		var foundit = false;
		$("#container a").each(function(e) {
			if(this.href === thishref) {
				foundit = true;
				$.history.load(getPortfolioStory(this));
				return false;
			}
		})
		if(foundit) { e.preventDefault(); }
	});
	$.event.special.hover.delay = 250; 
	$.event.special.hover.speed = 2;
	$("#linkList td a.alink, .partnerInstallations a.alink").hover(function() {
		var thisText = $(this).text();
		var matchingThumb = $(".main-content a span:contains("+thisText+")").parents(".section");
		matchingThumb.addClass('hovering');
		if(matchingThumb.prev().size()) {
			var scrollToMe = matchingThumb.prev();
		} else {
			var scrollToMe = matchingThumb;
		}
		$("#container").scrollTo(scrollToMe, 250);
	}, function() {
		//var thisText = $(this).text();
		$(".main-content .hovering").removeClass("hovering");
		/*var scrollTo = $("#selected").size() ? $("#selected") : 0;
		console.log(scrollTo);
		$("#container").scrollTo(scrollTo);*/
	});
	
	$("#province, #state").change(function(e) {
		filters.remove('location_stateprovince');
		if(this.value.toLowerCase() == "all") {
			$("#province, #state").removeData('location_stateprovince');
			filters.countResults();
			filters.hackLazyLoad();
			return;
		}
		var oldVal = $(this).data('curVal');
		if(!!oldVal) {
			filters.remove(oldVal);
		}
		
		filters.apply('location_stateprovince', this.value.toLowerCase(), false, false);
		
		$(this).data('curVal', this.value.toLowerCase());
	});
	$("#country").change(function(e) {
		if($("#province").data('curVal')) {
			filters.remove('location_stateprovince');
			$("#province").removeData('curVal');
		}
		if($("#state").data('curVal')) {
			filters.remove('location_stateprovince');
			$("#state").removeData('curVal');
		}
		filters.remove('location_country');
		
		if(this.value.toLowerCase() == "all") {
			$("#country").removeData('location_country');
			filters.hackLazyLoad();
			return;
		}
		
		filters.apply('location_country', this.value.toLowerCase(), false, false);
		
		var oldVal = $(this).data('curVal');
		if(!!oldVal) {
			filters.remove(oldVal);
		}
		$(this).data('curVal', this.value.toLowerCase());
	});
	$("#producttype").change(function(e) {
		if(this.value.toLowerCase() == "all") {
			filters.remove($(this).data('curVal'));
			if($(this).data('curVal')) {
				$(this).removeData('curVal');
			}
			filters.hackLazyLoad();
			return;
		}
		filters.apply(this.value.toLowerCase(), "1", false, false);
		
		var oldVal = $(this).data('curVal');
		if(!!oldVal) {
			filters.remove(oldVal);
		}
		filters.hackLazyLoad();
		$(this).data('curVal', this.value.toLowerCase());
	});
	
	$("#cat").change(function(e) {
		if($("#l3drop select").data('curVal')) {
			filters.remove($("#l3drop select").data('curVal'));
			$("#l3drop select").removeData('curVal');
		}
		if($("#subdrop select").data('curVal')) {
			// I think we don't need this
			filters.remove($("#subdrop select").data('curVal'));
			$("#subdrop select").removeData('curVal');
		}
		if(this.value.toLowerCase() == "all") {
			filters.remove('market');
			filters.hackLazyLoad();
			$(this).removeData('curVal');
			return;
		}
		var oldVal = $(this).data('curVal');
		if(!!oldVal) {
			filters.remove('market');
		}
		filters.apply('market', this.value.toLowerCase(), false, true);
		$(this).data('curVal', this.value.toLowerCase());
	});
	$("#subdrop select").live('change', function(e) {
		if(this.value.toLowerCase() == "all") {
			filters.remove('market');
			$(this).removeData('curVal');
			var curCat = $("#cat").attr('value').toLowerCase();
			filters.apply('market', curCat, false, true);
			return;
		}
		var oldVal = $(this).data('curVal');
		if(!!oldVal) {
			filters.remove('market');
		}
		var curCategory = $("#cat").attr('value').toLowerCase();
		// healthcare, diagnostic radiology.*
		filters.apply('market', curCategory + ", " + this.value.toLowerCase(), false, true);
		
		$(this).data('curVal', this.value.toLowerCase());
	});
	$("#l3drop select").live('change', function(e) {
		if(this.value.toLowerCase() == "all") {
			filters.remove('market');
			$(this).removeData('curVal');
			var curCat = $("#cat").attr('value').toLowerCase();
			var curSubcat = $("#subdrop select").attr('value').toLowerCase();
			filters.apply('market', curCat + ", " + curSubcat, false, true);
			return;
		}
		var oldVal = $(this).data('curVal');
		if(!!oldVal) {
			filters.remove('market');
		}
		var curCategory = $("#cat").attr('value').toLowerCase();
		var curSubCategory = $("#subdrop select").attr('value').toLowerCase();
		// healthcare, diagnostic radiology.*
		filters.apply('market', curCategory + ", " + curSubCategory + ", " + this.value.toLowerCase(), false, true);
		
		$(this).data('curVal', this.value.toLowerCase());
	});
	
	//you should refuse to touch this until you get a raise and clear your schedule.
	filters = {
		filterUs: $("#container .section a"),
		filterFieldsInUse: [],
		apply: function(filterField, filterValue, reverse, leftMatch) {
			// need to call this when changing categories?
			matchRE = (leftMatch) ? new RegExp(filterValue.toLowerCase() + ".*", "g") : new RegExp(filterValue.toLowerCase(), "g");
			this.filterUs.each(function(i, obj) {
				if(filterField === "market") {
					// market has three fields now
					var ff = $(this).data(filterField) + "";
					var ff2 = $(this).data(filterField + "2") + "";
					var ff3 = $(this).data(filterField + "3") + "";
				} else {
					var ff = $(this).data(filterField) + "";
					var ff2 = "";
					var ff3 = "";
				}
				if(!reverse) {
					if(!ff.toLowerCase().match(matchRE) && !ff2.toLowerCase().match(matchRE) && !ff3.toLowerCase().match(matchRE)) {
						//this.filterFieldsInUse.push(filterField);
						$(this).parent(".section").addClass("filtered "+filterField);
						myThat = this;
					} else {
						myThis = this;
					}
				} else {
					if(ff == filterValue || ff2 == filterValue || ff3 == filterValue) {
						//this.filterFieldsInUse.push(filterField);
						$(this).parent(".section").addClass("filtered "+filterField);
					}
				}
			});
			this.countResults();
			this.hackLazyLoad();
		},
		remove: function(filterField) {
			// how to call this when changing categories?
			this.filterUs.each(function(i, obj) {
					$(this).parent(".section").removeClass(filterField);
			});
			this.filterCleanup();
			this.hackLazyLoad();
			this.countResults();
		},
		filterCleanup: function() {
			this.filterUs.each(function(i, obj) {
				var thissection = $(this).parent(".section");
				var arrclasses = thissection[0].className.split(' ');
				window.lastlength = arrclasses.length;
				if(arrclasses.length === 2 && thissection.hasClass('filtered')) {
					thissection.removeClass('filtered');
				}
				return;
				$(this).parent(".section").filter('.filtered').each(function(i, obj) {
					// if this has the filtered class, verify that there is at least one valid filter
					var activeClasses = this.className.split(" ");
					if(!activeClasses.intersect(this.filterFieldsInUse)) {
						$(this).removeClass('filtered');
					}
				});
			});
		},
		hackLazyLoad: function() {
			//two hacks to make lazyload show the currently visible images:
			if($("#container img:visible").size() < 5) {
				$("#container img:visible").trigger('appear');
			} else {
				$("#container").scrollLeft(1).scrollLeft(0);
			}
		},
		countResults: function() {
			var numResults = $(".section:not(.filtered)").size();
			$("#num_results span.num").text(numResults);
			$("#container .main-content").width(170 * numResults);
		}
	}
});

function pageload(hash) {
	//console.log('in pageload, hash: '+hash);
	if(!hash && !getURLParamValue('p')) { 
		// no history state and not loaded normally using ? query string, retrieve the table of links
		$("#selected").removeAttr('id');
		$("#container").scrollTo(0);
		if($("#linkList a").size() < 6) {
			$("#linkList").attr("id", "linkList_outer").load(window.location.href +" #linkList");
			$("#linkList").attr("id", "linkList_inner");
			$("#linkList_outer").attr('id', 'linkList');
		}
	}
	else if(!hash && !!getURLParamValue('p')) { 
		// no history state, loaded normally using ? query string
		var searchText = $("#A1").text();
		$("#selected").attr('id', '');
		$("#container").scrollTo($(".main-content a span:contains("+searchText+")").parents(".section").attr('id', 'selected').prev());
		return 
	}
	else { 
		$("#showAllLink").removeClass('noLink');
		var foundHash = false;
		$(".main-content a").each(function() {
			if('p=' + getURLParamValue('p', this.href) == hash) {
				foundHash = true;
				getPortfolioStory(this);
				//$("#linkList").load(this.href+" #fooTable");
				var $pI = $(".partnerInstallations");
				if($pI.size()) { $pI.hide(); }
				$.get(this.href, function(data, textStatus) {
					//Giant hack for IE
					inject = data.slice(data.indexOf("fooBegin")+ 16,data.indexOf("fooEnd") - 9);
					$("#linkList").html(inject);
				});
				return false;
			}
		});
		if(!foundHash) {
			minDist = 100;
			$(".main-content a").each(function() {
				distance = levenshtein('p=' + getURLParamValue('p', this.href), hash);
				if(distance < minDist) {
					minDist = distance;
					closest = this;
				}
			});
			if(minDist <= 6) {
				//console.log('closest was '+closest+' with a distance of '+minDist);
				getPortfolioStory(closest);
				//$("#linkList").load(this.href+" #fooTable");
				$.get(closest.href, function(data, textStatus) {
					//Giant hack for IE
					inject = data.slice(data.indexOf("fooBegin")+ 16,data.indexOf("fooEnd") - 9);
					$("#linkList").html(inject);
				});
			}
		}
	}
}

function getPortfolioStory(obj) {
	//console.log('in getPortfolioStory, href: ' + obj.href);
	var s = $("#selected");
	var jObj = $(obj);
	if(jObj !== s) {
		s.removeAttr('id');
		jObj.parents('div.section').attr('id', 'selected');
	}
	// prevAll gets all previous siblings in reverse order (in order from closest to the element to furthest)
	// filter just visible ones
	// the first index is the closest object
	var oPrev = jObj.parent().prevAll().filter(":visible").eq(0);
	if(oPrev.size()) {
		$("#container").scrollTo(oPrev, "800");
	}
	//$("#linkList").load(obj.href +" #fooTable")
	return "p=" + getURLParamValue('p', obj.href);
}

function getX(oElement) {
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetLeft;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function goleft(yesno) {
	moveto = (document.getElementById('container').scrollLeft) - 170;
	document.getElementById('container').scrollLeft = moveto;
}

function goright(yesno) { 
	moveto = (document.getElementById('container').scrollLeft) + 170;
	document.getElementById('container').scrollLeft = moveto;		
}

function changeCats() {
	document.getElementById('cat').selectedIndex = 0;  
	document.getElementById('subs').innerHTML = "<select name =\"subcategory\" class=\"textbox\"  style=\"width:150px; margin:5px 8px;\" disabled><option>All</option></select>" 
}

function levenshtein (s1, s2) {
/* http://kevin.vanzonneveld.net | original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com) | bugfixed by: Onno Marsman | revised by: Andrea Giammarchi | (http://webreflection.blogspot.com) | reimplemented by: Brett Zamir (http://brett-zamir.me) | reimplemented by: Alexander M Beedie | 
* example 1: levenshtein('Kevin van Zonneveld', 'Kevin van Sommeveld');
* returns 1: 3
*/
    if (s1 == s2) {
        return 0;
    }
    var s1_len = s1.length;
    var s2_len = s2.length;
    if (s1_len === 0) {
        return s2_len;
    }
    if (s2_len === 0) {
        return s1_len;
    }
    // BEGIN STATIC
    var split = false;
    try{
        split=!('0')[0];
    } catch (e){
        split=true; // Earlier IE may not support access by string index
    }
    // END STATIC
    if (split){
        s1 = s1.split('');
        s2 = s2.split('');
    }

    var v0 = new Array(s1_len+1);
    var v1 = new Array(s1_len+1);

    var s1_idx=0, s2_idx=0, cost=0;
    for (s1_idx=0; s1_idx<s1_len+1; s1_idx++) {
        v0[s1_idx] = s1_idx;
    }
    var char_s1='', char_s2='';
    for (s2_idx=1; s2_idx<=s2_len; s2_idx++) {
        v1[0] = s2_idx;
        char_s2 = s2[s2_idx - 1];

        for (s1_idx=0; s1_idx<s1_len;s1_idx++) {
            char_s1 = s1[s1_idx];
            cost = (char_s1 == char_s2) ? 0 : 1;
            var m_min = v0[s1_idx+1] + 1;
            var b = v1[s1_idx] + 1;
            var c = v0[s1_idx] + cost;
            if (b < m_min) {
                m_min = b; }
            if (c < m_min) {
                m_min = c; }
            v1[s1_idx+1] = m_min;
        }
        var v_tmp = v0;
        v0 = v1;
        v1 = v_tmp;
    }
    return v0[s1_len];
}

/*
 *removed from filters: 

,
		filtersFilter: function(curData) { return
			/* 
			 * this runs on pageload and every time filters are changed
			 * it examines currently visible thumbnails and applies the current filter option and returns the number of results
			 * then the text of the filter is modified with this result
			 * data-originaltext is used to store unmodified text.
			 */
			 /*
			$("tr.filters select").each(function(i, obj) {
				//if(curData) { alert(curData); }
				if(this.id == "cat") {
					filterField = "market";
				} else if(!!$(this).parents("#subselect").size()) {
					filterField = "market";
				} else if(this.id == "producttype") {
					// here we need to call applyFilter differently -- like:
					// this.applyFilter(this.value, 1, curData)
					filterField = "producttype";
				} else if(this.id == "country") {
					filterField = "location_country";
				} else if(this.id == "state" || this.id == "province") {
					filterField = "location_stateprovince";
				}
				
				$('option', this).each(function(i, obj) {
					
					if(this.value.toLowerCase() !== curData && this.value.toLowerCase() !== "all") {
						if(filterField !== "producttype") {
							var result = filters.applyFilter(filterField, this.value.toLowerCase(), curData);
						} else {
							var result = filters.applyFilter(this.value.toLowerCase(), 1, curData);
						}
						if(!$(this).data('originaltext')) { $(this).data('originaltext', $(this).text()); }
						$(this).text($(this).data('originaltext') + " (" + result + ")");
					}
					else { var result = $(".section:not(.filtered)").size(); }
					if(!$(this).data('originaltext')) { $(this).data('originaltext', $(this).text()); }
					$(this).text($(this).data('originaltext') + " (" + result + ")");
				});
			});
		},
		applyFilter: function(filterField, filterValue, curData) {
			filterValueString = filterValue + "";
			var matchFilter = (filterField == "market") ? new RegExp(filterValueString.toLowerCase() + ".*", "g") : new RegExp(filterValueString.toLowerCase(), "g");
			var returned = 0;
			if(filterField !== "fixme" && filterValue !== curData) {
				window.filteredEntriesThatAreApplicable = [];
				$(".filtered a").each(function(i, obj) {
					// todo: check to see why this is filtered and if removing the current filter field will unfilter
					if($(this).parents('.section')[0].className.split(' ').length == 3) {
						// this entry is being filtered by only one filter.  check to see if it is the current filterField
						if($(this).parents('.section').hasClass(filterField)) {
							// this one should be checked 
							filteredEntriesThatAreApplicable[filteredEntriesThatAreApplicable.length] = this;
						}
					}
				});
				$(".section:not(.filtered) a").add(filteredEntriesThatAreApplicable).each(function(i, obj) {
					var thisfilterValue = $(this).data(filterField) + "";
					thisfilterValue = thisfilterValue.toLowerCase();
					/*if(filterField == "location_country") {
						alert($(this).data(filterField));
					}*/
					/*
					if(thisfilterValue.match(matchFilter)) {
						returned++;
					}
				});
			}
			return returned;
		},
		findNewByPortfolioId: function(howMany) {
			var arrIDs = [];
			$(this.filterUs).each(function(i, obj) {
				var thisID = $(this).data('portfolioid');
				arrIDs.push(thisID);
			});
			return arrIDs.sort().slice(-howMany);
		}
		
*/

