var xl = xl || {};

xl = {
	vars: { },
	init: function() {
		xl.print.init();
		xl.eraseInput.init();
		xl.setupFavouriteSelector.init();
		xl.setupFavouriteTooltip.init();
		xl.megaDropDown.init();
		xl.navTabs.init();
		xl.slidingTabs.init();

		if ($().tabs) {
			$('.tabs').tabs();
			// Bugfix for IE7/8, there is something fishy with the tabs in IE causing the footer to not get updated when we add elements to the list, this will make it move to the bottom in most cases
			if ($.browser.msie) {
				$('.tabs').bind('tabsshow', function(event, ui) {
					$('#footer').addClass('x');
					$('#footer').removeClass('x');
				});

				$('.row .category-item:first-child').css({ 'margin-left': '0' });
			}
		}
		$('.Slideshow').parent('.teaserContainer').addClass('first');
	},
	slidingTabs: {
		init: function() {
			if (!$('#nav-tabs').length) return;
			$('#nav-tabs').data('origTop', $('#nav-tabs').offset().top); //save original top position as data on object.
			$(window).bind('scroll', function(obj) {
				var offsetTop = $(window).scrollTop();
				var origTop = $('#nav-tabs').data('origTop') - 30;
				var contentHeight = $('#main').height() - 30;

				$('#nav-tabs').stop();
				var scrollToMargin = offsetTop - origTop;
				if (scrollToMargin < 0)
					scrollToMargin = 0;
				else if (scrollToMargin > contentHeight - $('#nav-tabs').height())
					scrollToMargin = contentHeight - $('#nav-tabs').height();

				$('#nav-tabs').animate({ marginTop: scrollToMargin });
			});
			//$(window).scrollTop($(window).scrollTop() + 1); // just trigger the event when first loading the page in case it's a reload on the lower parts of the page...

		}
	},
	megaDropDown: {
		init: function() {

			function megaHoverOver() {
				$(this).addClass("hovering");
			}

			function megaHoverOut() {
				$(this).removeClass("hovering");

			}

			var config = {
				sensitivity: 6, // number = sensitivity threshold (must be 1 or higher)    
				interval: 100, // number = milliseconds for onMouseOver polling interval    
				over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
				timeout: 400, // number = milliseconds delay before onMouseOut    
				out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
			};


			$("#nav ul li").not('#nav .subMenu li').hoverIntent(config);
		}
	},
	eraseInput: {
		init: function() {
			$('#search input').focus(function() {
				if ($(this).val() == $(this).attr('title')) {
					$(this).val("");
				}
			}).blur(function() {
				if ($(this).val() == "") {
					$(this).val($(this).attr('title'));
				}
			});

			$('#nav-search input').focus(function() {
				if ($(this).val() == $(this).attr('title')) {
					$(this).val("");
				}
			}).blur(function() {
				if ($(this).val() == "") {
					$(this).val($(this).attr('title'));
				}
			});


			$("form").submit(function() {
				if ($('#pageSearch .search-main').val() == $('#pageSearch .search-main').attr('title')) {
					$('#search .search-main').val("");
				}
			});
		}
	},
	print: {
		init: function() {
			$('.print').show().click(function() {
				window.print();
				return false;
			});
		}
	},
	navTabs: {
		init: function() {
			$('#nav-tabs li').mouseover(function() {
				$(this).animate({
					marginLeft: '0'
				}, 200);

			});
			$('#nav-tabs li').mouseout(function() {
				$(this).animate({
					marginLeft: '-9px'
				}, 200);

			});

		}
	},
	setupFavouriteSelector: {
		rewireEvents: function() {
			$('.Retailer input').unbind('click');
			$('.Retailer input').click(function(e) {
				e.preventDefault();
				$(this).toggleClass('active');
				updateCookieListItem("FavoriteRetailers", this.value, this.className == 'fav');
			});
		},
		init: function() {
			this.rewireEvents();
		}
	},
	setupFavouriteTooltip:
		{
			rewireEvents: function() {
				$('.Retailer input').unbind('hover');
				$('.Retailer input').hover(function(e) {
					var text;
					if (this.className == "fav active") {
						text = '<p class="remove">Ta bort som favoritbutik</p>';
					} else {
						text = '<p>L&#228;gg till som favoritbutik</p>';
					}

					$('#favoriteTooltip').css({
						top: $(this).offset().top - 80 + 'px',
						left: $(this).offset().left - 33 + 'px'
					});
					$('#favoriteTooltip').show().html(text);
				},
					function() {
						$('#favoriteTooltip').hide();
					});
			},
			init: function() {
				this.rewireEvents();
			}
		}
};


$(document).ready(function () {
	xl.init();
});

function listController() {
	var options = {};
	this.init = function (args) {
		this.options = args;
		var self = this;
		var showMoreButton = $('#' + self.options.showMoreButtonId);
		showMoreButton.bind('click.' + self.options.namespace, { self: this }, this.renderListPageItems);

		if (this.options.loadOnScroll) {
			$(window).bind('scroll.' + this.options.namespace, { self: this }, this.scrollHandler);
		}
		var container = $('#' + self.options.containerId);

		if (container.children().length >= self.options.totalCount) {
			showMoreButton.hide();
		} else {
			showMoreButton.show();
		}
		
	};
	this.reload = function () {
		var self = this;
		self.renderListPageItems(null, true);
	};
	this.scrollHandler = function (e) {
		var self = e.data.self;
		var container = $('#' + self.options.containerId);

		if (container.children().length >= self.options.totalCount || container.is(":hidden")) {
			return;
		}
		if ($(window).scrollTop() >= $('#' + self.options.showMoreButtonId).offset().top - $(window).height()) {
			self.renderListPageItems(null, false, 2000);
		}
	};
	this.renderListPageItems = function (e, clear, delay) {
		var self = this;
		if (e) {
			self = e.data.self;
		}
		if (!delay) {
			delay = 0;
		}
		$(window).unbind('scroll.' + self.options.namespace);
		$('#' + self.options.showMoreButtonId).unbind('click.' + self.options.namespace);
		$('#' + self.options.showMoreButtonId).append('<img src="/Common/Images/ajax-loader.gif" />');
		var container = $('#' + self.options.containerId);
		var currentCount = container.children().length;
		if (clear) {
			currentCount = 0;
		}
		var recursive = '';
		if (self.options.recursive) {
			recursive = ',"recursive": "true"';
		}
		var ajaxData = { pageId: self.options.pageId, extra: self.options.extra, start: currentCount, count: self.options.itemsPerPage, recursive: self.options.recursive };
		window.setTimeout(function () {
			$.ajax({
				type: "POST",
				url: self.options.dataUrl,
				dataType: "json",
				contentType: "application/json",
				data: JSON.stringify(ajaxData),
				success: function (data) {
					if (clear) {
						container.empty();
					}
					if (data.d == '') {
						return;
					}
					var jsonData = JSON.parse(data.d);
					$.each(jsonData.items, function (i, item) {

						container.append(item);
					});

					if (jsonData.totalCount != undefined && jsonData.totalCount > -1) {
						self.options.totalCount = jsonData.totalCount;
					}

					xl.setupFavouriteSelector.rewireEvents();

					$('#' + self.options.showMoreButtonId + ' img').remove();
					self.init(self.options);

					// Bugfix for IE8, there is something fishy with the footer in IE8 causing it to not get updated when we add elements to the list, this will make it move to the bottom after a ajax call
					if ($.browser.msie && jQuery.browser.version == '8.0') {
						$('#footer').addClass('x');
						$('#footer').removeClass('x');
					}
				},
				failure: function (data) {
					$('#' + self.options.showMoreButtonId + ' img').remove();
					self.init(self.options);
				}
			});
		}, delay);
	};
}

function addCookieListItem(cookieName, item) {
    updateCookieListItem(cookieName, item, false);
}

function removeCookieListItem(cookieName, item) {
    updateCookieListItem(cookieName, item, true);
}

function updateCookieListItem(cookieName, item, remove) {
    var currentCookie = getCookie(cookieName);

    var cookieItems;

    if (currentCookie != null && currentCookie != "") {
        cookieItems = currentCookie.split(',');
    }
    else {
        cookieItems = new Array();
    }


    var newCookieItems = new Array();

    for (var i = 0; i < cookieItems.length; i++) {
        if (cookieItems[i] != item) {
            newCookieItems.push(cookieItems[i]);
        }
    }

	if (!remove) {// Add
		newCookieItems.push(item);
		if(_gaq != undefined && _gaq != null) {
			_gaq.push(['_trackEvent', 'Favoritbutik', item, 'Lägga till']);	
		}
    } else {
		if (_gaq != undefined && _gaq != null) {
			_gaq.push(['_trackEvent', 'Favoritbutik', item, 'Ta bort']);
		}
    }
    setCookie(cookieName, newCookieItems.toString(), 90);
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()+";path=/;");
    document.cookie = c_name + "=" + c_value;
}

function getCookie(name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == name) {
            return unescape(y);
        }
    }
}





	
	

