var cookieName = 'pr_sort_refine';
var lastColumn = 0;
var sortColumn = 0;
var sortDirection = 'asc';

var rBrand;
if ("undefined" == typeof rBrand) {
	rBrand = "";
}
var rColumn;
if ("undefined" == typeof rColumn) {
	rColumn = -1;
}
var rCondition;
if ("undefined" == typeof rCondition) {
	rCondition = null;
}
var rValue;
if ("undefined" == typeof rValue) {
	rValue = -1;
}

var nrSet = 0;

var productRadarURL = '';

var productCasesSets = new Array();
var originalProductCasesSets = new Array();

// these values will be set when the assessment page is loaded
var minProducts = 0;
var maxProducts = 0;

var selectedItems = new Array();

function sortColumnsTitle(nrColumn, nrSet) {
	var setSuffix = '_set' + nrSet;
	var upClass = $('div[id=pr_up' + nrColumn + setSuffix + ']').attr("class");
	var downClass = $('div[id=pr_down' + nrColumn + setSuffix + ']').attr(
			"class");

	var order = 'asc';
	if (-1 != upClass.indexOf('_selected')) {
		order = 'desc';
	} else if (-1 != downClass.indexOf('_selected')) {
		order = 'asc';
	}
	sortColumns(nrColumn, order, nrSet);
}

function sortColumns(nrColumn, order, nrSet) {
	if (undefined == nrSet || undefined == arguments[2]) {
		nrSet = 0;
	}
	sortColumn = nrColumn;
	sortDirection = order;
	// saveSortRefineStatus();
	productCases = productCasesSets[nrSet];
	// alert('nrSet = ' + nrSet + ' ' + print_r(productCasesSets, true));
	var n = productCases.length, sortedProductCases;
	var i, j, temp, swaped;
	productCases = qsort(productCases, nrColumn, order);
	temp = 1;
	var setSuffix = '_set' + nrSet;
	$('#pc0' + setSuffix).after($('#pc' + productCases[0].index + setSuffix));
	if (false == productCases[0].show) {
		$('#pc' + productCases[0].index + setSuffix).css("display", "none");
	} else {
		$('#pc' + productCases[0].index + setSuffix)
				.css("display", "table-row");
	}
	for (i = 1; i < (n - 1); i++) {
		$('#pc' + productCases[i].index + setSuffix).after(
				$('#pc' + productCases[i + 1].index + setSuffix));
		if (false == productCases[i].show) {
			$('#pc' + productCases[i].index + setSuffix).css("display", "none");
		} else {
			$('#pc' + productCases[i].index + setSuffix).css("display",
					"table-row");
		}
	}
	$('#pc' + productCases[n - 1].index + setSuffix).after(
			$('#pr_footer' + setSuffix));
	if (false == productCases[n - 1].show) {
		$('#pc' + productCases[n - 1].index + setSuffix).css("display", "none");
	} else {
		$('#pc' + productCases[n - 1].index + setSuffix).css("display",
				"table-row");
	}
	temp = 1;
	$('#products' + setSuffix).find("tr[id^=pc][id!=pc0]").each(
			function(i) {
				if ("none" != $(this).css("display")) {
					$(this).find("td").each(
							function(j) {
								if (0 != i) {
									var oldClass = $(this).attr("class");
									if (-1 != oldClass.indexOf('pr_checked')) {
										var newClass = oldClass.replace(
												/(pr_odd)|(pr_even)/,
												(temp % 2 ? 'pr_even'
														: 'pr_odd'));
									} else {
										var newClass = oldClass.replace(
												/(pr_odd)|(pr_even)/,
												(temp % 2 ? 'pr_even'
														: 'pr_odd'));
									}
									$(this).attr("class", newClass);
								}
							});
					temp++;
				}
			});
	$('div[id^=pr_up][id*=' + setSuffix + ']').each(function(i) {
		var cClass = $(this).attr("class");
		$(this).attr("class", cClass.replace(/_selected/, ''));
	});
	$('div[id^=pr_down][id*=' + setSuffix + ']').each(function(i) {
		var cClass = $(this).attr("class");
		$(this).attr("class", cClass.replace(/_selected/, ''));
	});
	var sClass = $('#pr_' + ('asc' == order ? 'up' : 'down') + nrColumn
			+ setSuffix);
	sClass.attr("class", sClass.attr("class") + "_selected");
	$('a[id^=clink]').each(function() {
		$(this).removeClass('pr_highlight_sorting');
		var img = $(this).find('img');
		if (0 < img.length) {
			var src = img.attr('src');
			img.attr('src', src.replace('FFA115', '062D94'));
		}
	});
	$('#clink' + nrColumn).addClass('pr_highlight_sorting');
	var img = $('#clink' + nrColumn).find('img');
	if (0 < img.length) {
		var src = img.attr('src');
		img.attr('src', src.replace('062D94', 'FFA115'));
	}
}
function refine(nrSet) {
	var comparison, val, newRValue;
	var comparisonExp = "", operator = "";

	rBrand = document.getElementById('pr_refine_brand').value;
	rColumn = document.getElementById('pr_refine_column').value;
	// rCondition = document.getElementById('pr_condition').value;
	rValue = document.getElementById('pr_refine_value').value;

	if ("" != rBrand) {
		comparisonExp = "productCases[i].c1 == '" + rBrand + "' ";
	}
	if ("" != comparisonExp) {
		operator = " && ";
	}
	if (0 != rValue) {
		if (-1 != rColumn.indexOf('%')) {
			rColumn = rColumn.replace(/%/, '');
			rValue = rValue + "0";
		}
		comparisonExp = comparisonExp + operator
				+ " parseFloat(productCases[i].c" + rColumn + ") >= "
				+ parseFloat(rValue.replace(/,/, '.'));
	}
	if ("" == comparisonExp) {
		comparisonExp = "1";
	}
	// if ('greater_than' == rCondition) {
	// comparison = '>';
	// } else if ('less_than' == rCondition) {
	// comparison = '<';
	// } else if ('equal_to' == rCondition) {
	// comparison = '==';
	// }
	productCases = originalProductCasesSets[nrSet];
	n = productCases.length;
	for (i = 0; i < n; i++) {
		// if (eval('parseFloat(productCases[i].c' + rColumn + ') ' + comparison
		// + parseFloat(rValue.replace(/,/, '.')) + ';')) {
		if (eval(comparisonExp + ";")) {
			productCases[i].show = true;
		} else {
			productCases[i].show = false;
		}
	}
	sortColumns(sortColumn, sortDirection, 0);
}
function qsort(a, nrColumn, order) {
	if (0 == a.length) {
		return new Array();
	}

	var left = new Array();
	var right = new Array();
	var pivot = a[0];
	for ( var i = 1; i < a.length; i++) {
		// if the selected column values are equal then sort by brand name
		if (eval('a[i].c' + nrColumn + '==' + 'pivot.c' + nrColumn)) {
			// also if the selected column values are equal AND the brand labels
			// are equal
			// then sort by type name, if exists
			if (eval('a[i].c1 == pivot.c1') && undefined != eval('a[i].c2')) {
				if (eval('a[i].c2' + ('asc' == order ? '<' : '>') + 'pivot.c2')) {
					left.push(a[i]);
				} else {
					right.push(a[i]);
				}
			} else if (eval('a[i].c1' + ('asc' == order ? '<' : '>') + 'pivot.c1')) {
				left.push(a[i]);
			} else {
				right.push(a[i]);
			}
		} else if (eval('a[i].c' + nrColumn + ('asc' == order ? '<' : '>')
				+ 'pivot.c' + nrColumn)) {
			left.push(a[i]);
		} else {
			right.push(a[i]);
		}
	}
	return qsort(left, nrColumn, order).concat(pivot,
			qsort(right, nrColumn, order));
}
function prepareCompareForm() {
	var f = document.getElementById('pr_compare_form');
	var fUrl = f.action;
	var checkbox;
	var nrChecked = 0;
	n = productCases.length;
	for (i = 0; i < n; i++) {
		checkbox = document.getElementById('bt' + productCases[i].index);
		if (true == checkbox.checked) {
			fUrl += '/' + checkbox.value;
			nrChecked++;
		}
	}
	if (2 <= nrChecked) {
		window.location.href = fUrl;
		// f.action = fUrl;
		// f.submit();
	} else {
		alert('Selecteer minimaal 2 producten om te kunnen vergelijken');
	}
}
function showRefinePopup(doToggle) {
	$(document).ready(function() {
		if (true == doToggle) {
			$('#pr_refine_popup').toggle();
		}
		n = productCases.length;
		for (i = 0; i < n; i++) {
			productCases[i].show = true;
		}
		sortColumns(sortColumn, sortDirection, 0);
	});
}
function showReviews(pageNr, brandId, typeId, perPage) {
	$(document).ready(
			function() {
				$('#pr_loading').toggle();
				$('#productReviews').load(
						productRadarURL + 'reviews/' + brandId + '/' + typeId
								+ '/' + pageNr + '/' + perPage);
			});
}
function selectCompared() {
	$(document)
			.ready(
					function() {
						var i = 0;
						$('input[id^=bt]').each(function() {
							if (true == $(this).attr("checked")) {
								i++;
							}
						});
						if (minProducts <= i) {
							$('#pr_compare_link').removeClass('disabled');
							$('#pr_compare_link').addClass('enabled');
							$('#pr_compare_link').attr('title', '');
						} else {
							$('#pr_compare_link').removeClass('enabled');
							$('#pr_compare_link').addClass('disabled');
							$('#pr_compare_link')
									.attr('title',
											'Selecteer minimaal 2 producten om te kunnen vergelijken');
						}
						if (maxProducts <= i) {
							$('input[id^=bt]').each(function() {
								if (false == $(this).attr("checked")) {
									$(this).attr("disabled", true);
								}
							});
						} else {
							$('input[id^=bt]').each(function() {
								if (false == $(this).attr("checked")) {
									$(this).attr("disabled", false);
								}
							});
						}
					});
}
function returnSelection() {
	$(document).ready(function() {
		$('#returnForm').submit();
	});
}

function saveSortRefineStatus() {
	var date = new Date();
	date.setTime(date.getTime() + (30 * 60 * 1000)); // 30 minutes
	var options = {
		path : '/',
		expires : 10
	};

	// delete the cookie
	$.cookie(cookieName, null, options);

	// set the cookie
	var cookieContent = '';
	cookieContent = cookieContent + 'rColumn=' + rColumn + '&';
	cookieContent = cookieContent + 'rCondition="' + rCondition + '"&';
	cookieContent = cookieContent + 'rValue="' + rValue + '"&';
	cookieContent = cookieContent + 'nrSet=' + '0' + '&';
	cookieContent = cookieContent + 'sortColumn=' + sortColumn + '&';
	cookieContent = cookieContent + 'sortDirection="' + sortDirection + '"';
	options.expires = date;
	$.cookie(cookieName, cookieContent, options);
}

if ("undefined" !== typeof $) {
	$(window).load(function() {
		$('input:checkbox').checkbox();
		$('input:checkbox').each(function() {
			$(this).css("display", "block")
		});
		if (0 != selectedItems.length) {
			$('input[id^=bt]').attr('checked', '');
			for ( var i = 0; i < selectedItems.length; i++) {
				$('input[id^=bt][value=' + selectedItems[i] + ']').trigger(
						"click");
			}
		}
		BrowserDetect.init();
		// use css transform: rotate for browsers that support it, for others use image
		if (('Firefox' == BrowserDetect.browser && 3.5 <= BrowserDetect.version) 
				|| ('Chrome' == BrowserDetect.browser) 
				|| ('Safari' == BrowserDetect.browser && 3.1 <= BrowserDetect.version)
				|| ('Opera' == BrowserDetect.browser && 9 <= BrowserDetect.version)
				)
		{
			fixColumnHeaders("assessmentLabels");
		}
		else
		{
			var heighestElement = 0;
			$('.angleLabel').each(function(){
				var img = $(this).parent().find('.labelImageSrc').html();
				$(this).html(img);
				$(this).removeAttr('style');
				$(this).css('display', 'block');
				if ($(this).height() > heighestElement) {
					heighestElement = $(this).height();
				}
			});
			$('.angleLabel').each(function(){
				$(this).css('margin-top', heighestElement - $(this).height());
			});
		}
	});
}

// CREATE TOOLTIPS
var qtipDefinition = {
	position : {
		corner : {
			target : 'topLeft',
			tooltip : 'bottomLeft',
			size : {
				y : 12
			}
		},
		adjust : {
			x : 2,
			y : -6
		}
	},
	style : {
		name : 'cream',
		tip : true,
		color : '#727272',
		backgroundColor : '#ececec',
		border : {
			width : 2,
			radius : 10,
			color : '#ececec'
		}
	}
};
var BrowserDetect = {
	init : function() {
		this.browser = this.searchString(this.dataBrowser)
				|| "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString : function(data) {
		for ( var i = 0; i < data.length; i++) {
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch
					|| data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			} else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion : function(dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1)
			return;
		return parseFloat(dataString.substring(index
				+ this.versionSearchString.length + 1));
	},
	dataBrowser : [ {
		string : navigator.userAgent,
		subString : "Chrome",
		identity : "Chrome"
	}, {
		string : navigator.userAgent,
		subString : "OmniWeb",
		versionSearch : "OmniWeb/",
		identity : "OmniWeb"
	}, {
		string : navigator.vendor,
		subString : "Apple",
		identity : "Safari",
		versionSearch : "Version"
	}, {
		prop : window.opera,
		identity : "Opera"
	}, {
		string : navigator.vendor,
		subString : "iCab",
		identity : "iCab"
	}, {
		string : navigator.vendor,
		subString : "KDE",
		identity : "Konqueror"
	}, {
		string : navigator.userAgent,
		subString : "Firefox",
		identity : "Firefox"
	}, {
		string : navigator.vendor,
		subString : "Camino",
		identity : "Camino"
	}, { // for newer Netscapes (6+)
				string : navigator.userAgent,
				subString : "Netscape",
				identity : "Netscape"
			}, {
				string : navigator.userAgent,
				subString : "MSIE",
				identity : "Explorer",
				versionSearch : "MSIE"
			}, {
				string : navigator.userAgent,
				subString : "Gecko",
				identity : "Mozilla",
				versionSearch : "rv"
			}, { // for older Netscapes (4-)
				string : navigator.userAgent,
				subString : "Mozilla",
				identity : "Netscape",
				versionSearch : "Mozilla"
			} ],
	dataOS : [ {
		string : navigator.platform,
		subString : "Win",
		identity : "Windows"
	}, {
		string : navigator.platform,
		subString : "Mac",
		identity : "Mac"
	}, {
		string : navigator.userAgent,
		subString : "iPhone",
		identity : "iPhone/iPod"
	}, {
		string : navigator.platform,
		subString : "Linux",
		identity : "Linux"
	} ]

};

function fixColumnHeadersOld(tableClass) {
	var maxHeight = 0;
	var angle;
	var longestOpposite = 0;
	var heighestElement = 0;
	// because rotate will not extend the height of the container we have to calculate it
	$('.angleLabel').each(function(){
		var angleI = parseInt($(this).parent().find('.labelAngle').html(), 10);
		angle = Math.abs(angleI);
		var width = $(this).width();
		var height = $(this).height();
		// projection of the segments
		var newWidth =  width * Math.cos(angle * (Math.PI/180) ) + height * Math.cos((90 - angle) * (Math.PI/180));
		var newHeight = width * Math.cos((90 - angle) * (Math.PI/180) ) + height * Math.cos(angle * (Math.PI/180) );
		if (newHeight > maxHeight)
		{
			maxHeight = newHeight;
		}
		$(this).width(Math.round(newWidth));
		opposite = Math.sin(angle * (Math.PI/180)) * width; 
		if (opposite > longestOpposite) {
			longestOpposite = opposite;
		}	
		if (height > heighestElement) {
			heighestElement = height;
		}
//		$(this).width(0);
		// set a margin top to center the label in the container
		var bottom = Math.round(opposite/2); // works, don't change, don't ask why
		var verticalAlignment = $(this).parent().css("vertical-align");	 				
		
		// Set the position of the div inside the th
		$(this).css("position", "relative");
		$(this).css(verticalAlignment, bottom);		
	});
	longestOpposite += heighestElement;
	$("."+ tableClass + " th").css("height",longestOpposite);
}
/*!
 * Rotating table headers library
 * https://public.me.com/renedekat/rotate_v1.0.zip
 *
 * Copyright 2011, Rene de Kat
 * Licensed under the GPL Version 3 licenses.
 * http://www.gnu.org/licenses/gpl.txt
 *
 * Includes jquery-1.4.2.js
 * http://jquery.com/
 * Copyright 2010, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Date: Tue Feb 9 2011 
 */
 
function fixColumnHeaders(tableClass) {
	// Keep track of the heighest element (width)
	var longestAdjacent = 0;

	// Keep track of the heighest element
	var longestOpposite = 0;
	// Keep track of the heighest text element. We need it later to determine the TH height
	var heighestElement = 0;
	// Table width
	var tableWidth = 0;
			
	// Get all divs in all tg
	$.each($("."+ tableClass + " th .angleLabel"), function() {		 
		var degrees = parseInt($(this).parent().find('.labelAngle').html(), 10);
		angleInRadians = Math.abs(degrees * Math.PI / 180);	
		var width = $(this).find('span').width();
		var height = $(this).find('span').height();
		// projection of the segments
		var newWidth =  width * Math.cos(angleInRadians ) + height * Math.cos((90 - degrees) * (Math.PI/180));
		
		opposite = Math.sin(angleInRadians) * width; 
		adjacent = Math.cos(angleInRadians) * width; 
		
		// Get the vertical alignment of the th
		var verticalAlignment = $(this).parent().css("vertical-align");	 				
		
		// Set the position of the div inside the th
		$(this).width(Math.round(newWidth));
		$(this).css("position", "relative");
		$(this).css(verticalAlignment, opposite/2);		
		// Reposition on the x axis
		var widthDifference = width - adjacent;
		$(this).css("left", -((widthDifference-this.offsetHeight)/2) );		
		// Set the cell width
		var cellWidth = adjacent+height;
		$(this).parent().css("width", cellWidth);	// Set the TH width. This is optional
		$(this).css("width", cellWidth);	// Set the DIV width
		// add cell width to tableWidth
		tableWidth += cellWidth;
		// Check if the adjacent is greater than the current value of longestAdjacent
		if (adjacent > longestAdjacent) {
			longestAdjacent = adjacent;
		}
		// Check if the adjacent is greater than the current value of longestAdjacent
		if (opposite > longestOpposite) {
			longestOpposite = opposite;
		}		
		
		// Check if the height of this element is greater than the current value of heighestElement;
		if ($(this).height() > heighestElement) {
			heighestElement = $(this).height();
		}
	});
	// Set height of all th to longestAdjacent and add the height of the heighest element (remember we rotated).
	longestOpposite += (heighestElement);
	$("."+ tableClass + " th").css("height",longestOpposite);	
}
