var sendPage = false;
$(document).ready(function()
{

	//add EasyAsk tracking call to product details links.
	$('.shoe_detail_link').live('click',function(event){
		//make an ajax tracking request for EasyAsk...
		event.preventDefault();
		$this = $(this);
		var querystring = buildQueryStr();
		querystring += "&" + $this.attr('rev') +'&track=itemview';

		/*
		var productcode_and_pageposition = $this.attr('rev');
		var request_url = '/tracking/easyask_track_event/clicked_product_detail_link/?'+productcode_and_pageposition;
		//var querystring = "&calling_uri=" + location.href + buildQueryStr();
		var querystring = buildQueryStr();

		//querystring += "&DBGSESSID=1@localhost:7869";

		request_url += "&" + querystring;
		//BRETT switched this to use the core ajax function so we can use the 'success'
		//event which is fired immediately after the request is sent and is guaranteed
		//to fire even on unsuccessful requests. We don't want to override our default link
		//behavior and then not be able to direct the user to the detail page after the
		//tracking request is sent...that would be bad.
		//Using a super-short timeout here so we just immediately call
		//the success function as soon as the tracking request goes out.
		$.ajax({
			url: request_url,
			data: null,
			type:'GET',
			dataType: "script",
			timeout:1,
			complete: function(){
				location.href = $this.attr('href')+"?"+querystring+'&track=itemview';
			}

		});
		*/
		//if(debug)querystring += "&DBGSESSID=1@localhost:7869";
		request_url = $this.attr('href')+"?"+querystring;
		location.href = request_url;

	});

	// set page
	//sendPage = false;

	var buildQueryStr = function()
		{
			var $options = $('.navOptions .selected');
			var query = $('#query').val();

			var optsArray = [];

			var styles       = [];
			var attributes   = [];
			var brands       = [];
			var heel_heights = [];
			var sizes        = [];
			var colors       = [];

			// extract values from all elements
			$options.each(function()
			{
				var $this = $(this);
				var key   = $this.data('key');
				var value = $this.data('value');

				switch (key) {

					case 'styles':

						styles.push(value);

						break;

					case 'attributes':

						attributes.push(value);

						break;

					case 'brands':

						brands.push(value);

						break;

					case 'heel_heights':

						heel_heights.push(value);

						break;

					case 'sizes':

						sizes.push(value);

						break

					case 'colors':

						colors.push(value);

						break;

				}
			});

			// add aggregated values in array to one big array
			//optsArray.push('DBGSESSID=0@clienthost:7869');
			(query.length > 0        ? optsArray.push('query=' + query)                        : '');
			(styles.length > 0       ? optsArray.push('styles=' + styles.join(','))             : '');
			(attributes.length > 0   ? optsArray.push('attributes=' + attributes.join(','))     : '');
			(brands.length > 0       ? optsArray.push('brands=' + brands.join(','))             : '');
			(heel_heights.length > 0 ? optsArray.push('heel_heights=' + heel_heights.join(',')) : '');
			(sizes.length > 0        ? optsArray.push('sizes=' + sizes.join(','))               : '');
			(colors.length > 0       ? optsArray.push('colors=' + colors.join(','))             : '');

			// get values from checkboxes
			($('input[name=sale]').attr('checked') == true ? optsArray.push('sale=' + $('input[name=sale]').val()) : '');
			($('input[name=new]').attr('checked')  == true ? optsArray.push('new=' + $('input[name=new]').val())   : '');

			// get values from select boxes
			($('select[name=price]').val() != '' ? optsArray.push('price='  + $('select[name=price]').val())  : '');
			($('select[name=order]').val() != '' ? optsArray.push('order='  + $('select[name=order]').val())  : '');
			($('select[name=limit]').val() != '' ? optsArray.push('limit='  + $('select[name=limit]').val())  : '');
			($('select[name=angle]').val() != '' ? optsArray.push('angle='  + $('select[name=angle]').val())  : '');

			// only pass page if page is selected or angle is selected
			if (sendPage == true) {

				// paging element may not exist, so check for that
				optsArray.push('page=' + currentPage);

			}

			// set category id
			(categoryId !== null ? optsArray.push('categories=' + categoryId) : '');


			//optsArray.push('DBGSESSID=0@localhost:7869');

			return optsArray.join('&'); // return complete query string
		};


	// gets all shoes
	var fetchShoes = function()
	{
		var $categoryShoes = $('#category-shoes');
		var $this          = $(this);

		//add a progress indicator popup....
		$categoryShoes
				  // .fadeTo("fast",.5)
				   .prepend('<img class="ajaxSpinnerBarTop" src="/img/ajax-loader-bar.gif" width="220" height="19" alt="loading..." />')
				   .append('<img class="ajaxSpinnerBar" src="/img/ajax-loader-bar.gif" width="220" height="19" alt="loading..." />');

		// set element styles
		if (!$this.hasClass('selected')) {

			$this.addClass('selected');

		} else {

			$this.removeClass('selected');

		}

		// add a deselection button
		if ($this.parent().hasClass('makeDeleteBox')) {

			var deselectId = 'deselect-' + this.id;

			if ($('#' + deselectId).length > 0) {

				$('#' + deselectId).remove();

			} else {

				// either get label from element's text or from display data property
				var displayText = typeof $this.data('display') != 'undefined' ? $this.data('display') : $this.html();

				$('<a href="#" id="' + deselectId + '" title="Uncheck Selection"><img class="vertMiddle" src="/img/category-nav-delete-select.png" alt="Uncheck Selection"/> ' + displayText + '</a>')
					.data('el', $this)
					.prependTo('#delete-select');
			}

		}

		// set page
		//var sendPage = false;
		if ($this.hasClass('previous')) {

			currentPage--;
			sendPage = true;


		} else if ($this.hasClass('next')) {

			currentPage++;
			sendPage = true;

		} else if ($this.hasClass('current')) {

			currentPage = $this.val();
			sendPage    = true;

		} else if ($this.attr('name') == 'angle'){
			sendPage    = true;
		}


		// ajax request
		$.post('/shoes/browse', buildQueryStr(), function(data)
		{
			if (data) {



				$categoryShoes.fadeOut(0, function()
				{



					 // replace contents
					$categoryShoes
						.empty()
						.append(data)
						.fadeIn(.5);

					// replace events that were lost during ajax call
					$('select.navOptions, .paging .current').change(fetchShoes);

					 //Scroll the window to the top nicely...Justin commented this out per Eric
					$('html,body')
					.animate({scrollTop: 150}, 0);

				});
				val = $('#query').val();
				if(val == ""){
					$('#category-header').fadeOut(250);
				}

			}

		}, 'html');

		return this.tagName != 'A' ? true :  false;
	};

	// set handlers to fetch shoes on click events
	$('.navOptions .active, input.navOptions, .paging .next, .paging .previous').live('click', fetchShoes);

	// set handlers to fetch shoes on change events
	$('select.navOptions, .paging .current').change(fetchShoes);

	$('#delete-select a').live('click', function()
	{
		var $target = $(this).data('el');

		$target.click();

		return false;
	});

	// make delete boxes for pre-populates items
	$('.makeDeleteBox div.selected, .makeDeleteBox li.selected').each(function()
	{
		var $this = $(this);

		var deselectId = 'deselect-' + this.id;

		// either get label from element's text or from display data property
		var displayText = typeof $this.data('display') != 'undefined' ? $this.data('display') : $this.html();

		$('<a href="#" id="' + deselectId + '" title="Uncheck ' + displayText + '"><img class="vertMiddle" src="/img/category-nav-delete-select.png" /> ' + displayText + '</a>')
			.data('el', $this)
			.prependTo('#delete-select');
	});
});

//set sizes data
$('#sizes-5').data('key', 'sizes');
$('#sizes-5').data('value', '5');
$('#sizes-5-5').data('key', 'sizes');
$('#sizes-5-5').data('value', '5.5');
$('#sizes-6').data('key', 'sizes');
$('#sizes-6').data('value', '6');
$('#sizes-6-5').data('key', 'sizes');
$('#sizes-6-5').data('value', '6.5');
$('#sizes-7').data('key', 'sizes');
$('#sizes-7').data('value', '7');
$('#sizes-7-5').data('key', 'sizes');
$('#sizes-7-5').data('value', '7.5');
$('#sizes-8').data('key', 'sizes');
$('#sizes-8').data('value', '8');
$('#sizes-8-5').data('key', 'sizes');
$('#sizes-8-5').data('value', '8.5');
$('#sizes-9').data('key', 'sizes');
$('#sizes-9').data('value', '9');
$('#sizes-9-5').data('key', 'sizes');
$('#sizes-9-5').data('value', '9.5');
$('#sizes-10').data('key', 'sizes');
$('#sizes-10').data('value', '10');
$('#sizes-10-5').data('key', 'sizes');
$('#sizes-10-5').data('value', '10.5');
$('#sizes-11').data('key', 'sizes');
$('#sizes-11').data('value', '11');
$('#sizes-11-5').data('key', 'sizes');
$('#sizes-11-5').data('value', '11.5');
$('#sizes-12').data('key', 'sizes');
$('#sizes-12').data('value', '12');
$('#sizes-12-5').data('key', 'sizes');
$('#sizes-12-5').data('value', '12.5');

//set colors data
$('#colors-beige').data('key', 'colors');
$('#colors-beige').data('value', 0);
$('#colors-beige').data('display', 'beige');
$('#colors-white').data('key', 'colors');
$('#colors-white').data('value', 1);
$('#colors-white').data('display', 'white');
$('#colors-black').data('key', 'colors');
$('#colors-black').data('value', 2);
$('#colors-black').data('display', 'black');
$('#colors-brown').data('key', 'colors');
$('#colors-brown').data('value', 3);
$('#colors-brown').data('display', 'brown');
$('#colors-grey').data('key', 'colors');
$('#colors-grey').data('value', 4);
$('#colors-grey').data('display', 'grey');
$('#colors-gold').data('key', 'colors');
$('#colors-gold').data('value', 5);
$('#colors-gold').data('display', 'gold');
$('#colors-silver').data('key', 'colors');
$('#colors-silver').data('value', 6);
$('#colors-silver').data('display', 'silver');
$('#colors-blue').data('key', 'colors');
$('#colors-blue').data('value', 7);
$('#colors-blue').data('display', 'blue');
$('#colors-pink').data('key', 'colors');
$('#colors-pink').data('value', 8);
$('#colors-pink').data('display', 'pink');
$('#colors-purple').data('key', 'colors');
$('#colors-purple').data('value', 9);
$('#colors-purple').data('display', 'purple');
$('#colors-red').data('key', 'colors');
$('#colors-red').data('value', 10);
$('#colors-red').data('display', 'red');
$('#colors-yellow').data('key', 'colors');
$('#colors-yellow').data('value', 11);
$('#colors-yellow').data('display', 'yellow');
$('#colors-green').data('key', 'colors');
$('#colors-green').data('value', 12);
$('#colors-green').data('display', 'green');
$('#colors-orange').data('key', 'colors');
$('#colors-orange').data('value', 13);
$('#colors-orange').data('display', 'orange');
$('#colors-clear').data('key', 'colors');
$('#colors-clear').data('value', 14);
$('#colors-clear').data('display', 'clear');
$('#colors-multi').data('key', 'colors');
$('#colors-multi').data('value', 15);
$('#colors-multi').data('display', 'multi');