﻿$.updateViews = function (options) {
	var autoUpdateEnabled = true;
	var displayShortlistOnly = true;

	var dateRange = 0;
	var servicePath;
	var pageName;

	// variable that holds the current sort
	var currentSortList = [];
	var sortBoxSortLists = {};

	var sorting;
	var serviceUrl;

	if (options) {

		if (typeof (options.displayShortlistOnly) != "undefined")
			displayShortlistOnly = options.displayShortlistOnly;

		if (typeof (options.dateRange) != "undefined")
			dateRange = options.dateRange;

		if (typeof (options.pageName) != "undefined")
			pageName = options.pageName;

		if (typeof (options.servicePath) != "undefined")
			servicePath = options.servicePath;

		if (typeof (options.currentSortList) != "undefined")
			currentSortList = options.currentSortList;

		if (typeof (options.sortLists) != "undefined")
			sortBoxSortLists = options.sortLists;
	}

	function initializeDateBox() {
		$('.date_box a').click(function () {
			// set sorting column and direction, this will sort on the first and third column the column index starts at zero 
			dateRange = $(this).attr('href').substr(11, 1);
			// deselect all items
			$('.date_box a').removeClass('active');
			// add the active calss to the current item
			$(this).addClass('active');

			// track event
			_gaq.push(['_trackEvent', pageName, 'update', 'daterangebox', parseInt(dateRange)]);

			// start update
			updateData();
			// return false to stop default link action
			return false;
		});
	}

	function startCountDown() {
		$('#countdown').countdown({
			until: +30,
			format: 'S',
			layout: 'Refreshing in {sn} sec',
			onExpiry: function () {

				// track event
				_gaq.push(['_trackEvent', pageName, 'update', 'auto', parseInt(dateRange)]);

				updateData();
			}
		});
	}

	function stopCountDown() {
		try {
			$('#countdown').countdown('destroy');
		}
		catch (e) {
		}
	}

	function updateData() {
		// stop the countdown in any case
		stopCountDown();
		// display the loading bar
		updateAnimation(true);
		updateText(true);

		setTimeout(function () {
			try {
				$.ajax({
					type: "GET",
					//cache: false,
					url: serviceUrl,
					scriptCharset: "utf-8",
					dataType: "jsonp",
					data: "dateRange=" + dateRange,
					success: function (response) {
						dataUpdated($.parseJSON(response));
					},
					complete: function (XMLHttpRequest, textStatus) {
						CompleteLoading();
					}
				});
			} catch (e) {
				CompleteLoading();
			}

		}, 20);
	}

	function dataUpdated(response) {
		try {

			if (displayShortlistOnly) {
				response = $.grep(response, function (item, i) {
					return item.IsInShortlist == true;
				});
			}

			processTemplate(response);

			// trigger sortend
			$("#TableContainer").trigger("templateProcessed");

			initializeTableSorter();

			//initializeColorbox(pageName);
			// initialize the links .. can be done after everything is successfully loaded
			setTimeout(function () {
				try {
					initializeColorbox(pageName);
				} catch (e) {
				}
			}, 100);
		} catch (e) {
		}
	}

	function CompleteLoading() {
		// hide the loading bar
		updateAnimation(false);
		updateText(false);

		startCountDown();
	}

	function setTemplate() {
		// attach the template
		$("#TableContainer").setTemplateElement("Template");
	}

	function processTemplate(response) {
		// set the locale parameter based on the current selected culture (cookie)
		$("#TableContainer").setParam('Locale', getLocale($.cookie('enyo.user.culture')));
		// set odds format parameter
		$("#TableContainer").setParam('OddsFormat', 3);
		//$("#TableContainer").setParam('OddsFormat', $.cookie('OddsFormat'));
		// set parameter that determines if the short list filter should be applied (currently this is ont used)
		$("#TableContainer").setParam('DisplayShortlistOnly', displayShortlistOnly);
		// execute the template
		$('#TableContainer').processTemplate(response);
	}

	function updateAnimation(show) {
		show ? $('#UpdateProgressBar').show() : setTimeout(function () { $('#UpdateProgressBar').hide(); }, 20);
	}

	function updateText(show) {
		show ? $('#countdown').text('Updating...') : $('#countdown').text('');
	}

	function updateTextTo(text) {
		$('#countdown').text(text);
	}

	function initializeSortBox() {
		$(".sort_by_box a").each(function (index, element) {
			$(this).click(function () {
				sorting = true;
				// set sorting column and direction, this will sort on the first and third column the column index starts at zero 
				currentSortList = sortBoxSortLists[index];
				// sort on the first column => deselects all items
				$(".gridtable").trigger("sorton", [currentSortList]);
				// add the active calss to the current item
				$(this).addClass('active');

				// track event
				_gaq.push(['_trackEvent', pageName, 'sort', 'box', index]);

				// return false to stop default link action
				return false;
			});
		});
	}

	function initializeTableSorter() {
		setTimeout(function () {
			var $initial = true;

			$(".gridtable thead tr th.hidden").addClass("{sorter: 'metadata'}");
			$(".gridtable thead tr th.flag").addClass("{sorter: 'textmetadata'}");
			$(".gridtable thead tr th.opap").addClass("{sorter: 'metadata'}");
			$(".gridtable thead tr th.arrow").addClass("{sorter: false}");
			$(".gridtable thead tr th.league").addClass("{sorter: 'textmetadata'}");
			$(".gridtable thead tr th.eventdate").addClass("{sorter: 'metadata'}");
			$(".gridtable thead tr th.team").addClass("{sorter: 'textmetadata'}");
			$(".gridtable thead tr th.price").addClass("{sorter: 'metadata'}");
			$(".gridtable thead tr th.prices").addClass("{sorter: 'metadata'}");
			$(".gridtable thead tr th.percentage").addClass("{sorter: 'metadata'}");
			$(".gridtable thead tr th.volume").addClass("{sorter: 'metadata', sortInitialOrder: 'desc'}");
			$(".gridtable thead tr th.volumePercentage").addClass("{sorter: 'metadata', sortInitialOrder: 'desc'}");
			$(".gridtable thead tr th.volumeIndex").addClass("{sorter: 'metadata', sortInitialOrder: 'desc'}");
			$(".gridtable thead tr th.tip").addClass("{sorter: 'text', sortInitialOrder: 'desc'}");
			$(".gridtable thead tr th.links").addClass("{sorter: false}");

			$(".gridtable").tablesorter({
				// debug: true,
				// set sortList (empty on pageload)
				sortList: currentSortList,
				// deactivate headers for now
				cssHeader: "tableheader",
				textExtraction: "simple",
				parserMetadataName: "sortValue",
				widgets: ["zebra"],
				widgetZebra: { css: ["", "evenrowcolor"] }
			});

			$(".gridtable").bind("sortStart", function () {
				// deselect the items in the sort box
				$(".sort_by_box a").removeClass('active');
				updateAnimation(true);
			}).bind("sortEnd", function () {
				currentSortList = $(".gridtable")[0].config.sortList;
				updateAnimation(false);

				if ($initial) {
					$initial = false;
				} else {
					if (sorting) {
						sorting = false;
					} else {
						// track event
						_gaq.push(['_trackEvent', pageName, 'sort', 'header']);
					}
				}

			});
		}, 50);
	}

	function initializeSliders() {
		// hide (Collapse) the toggle containers on load
		$(".toggle_container").each(function (index, element) {
			if (!visibilityBoxes[this.id]) { $(this).hide() };
		});

		//Slide up and down on click
		$(".trigger").click(function () {
			//$(".toggle_container").slideUp();
			var elementToToggle = $(this).next(".toggle_container")
			visibilityBoxes[elementToToggle[0].id] = !visibilityBoxes[elementToToggle[0].id];
			elementToToggle.slideToggle("slow");
		});
	}

	function initializeSorts() {
		$(".sort_by_box a:first").addClass('active');
		currentSortList = sortBoxSortLists["0"];
	}

	function subscribeToEvents() {
		$("table.gridtable").live("autoUpdateEnabled", function () {
			updateData();
		});

		$("table.gridtable").live("autoUpdateDisabled", function () {
			stopCountDown();
			updateTextTo("Updating suspended");
		});
	}

	function start() {

		subscribeToEvents();

		serviceUrl = "/BetmateAjax.svc/" + servicePath;

		// HACK set data source to remote server
		serviceUrl = "http://manage.bet-mate.com" + serviceUrl;


		//		if ($.getServiceUrl) {
		//			serviceUrl = "/BetmateAjax.svc/" + $.getServiceUrl();
		//		} else {
		//			pageName = jQuery.url.attr("file").replace(/\.(aspx)$/, "");
		//			serviceUrl = "/BetmateAjax.svc/" + pageName;
		//		}

		// set the used template just on the first page load
		setTemplate();

		// intialize sort box
		initializeSortBox();

		// initializeDateBox
		initializeDateBox();

		initializeSliders();

		initializeSorts();

		// start continous update process
		updateData();
	}

	start();
}
