﻿var language = "";
var currentSearch = "";
var en = false;
var gettingData = 0;
var lastShown = '';

(function ($) {
	$.fn.center = function () {
		this.css("position", "absolute");
		this.css("top", ((($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px"));
		this.css("left", ((($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px"));
		return this;
	};

	$.effects.fade = function (o) {

		return this.queue(function () {

			// Create element
			var el = $(this);

			// Set options
			var speed = o.options.speed || 230;
			var mode = o.options.mode || 'show'; // Set Mode

			// Animate
			if (mode == 'show') {
				el.fadeIn(speed);
			} else {
				el.fadeOut(speed);
			};
			el.queue('fx', function () { el.dequeue(); });
			el.dequeue();
		});
	};

})(jQuery);

function doSearch() {
	var search = encodeURIComponent($('#tbSearchField').val());
	//var option = $('#searchExtras input:radio:checked').val();
	if (search !== "") {
		var url = en ? '/en/s/' : '/sv/s/';

		location.href = url + search + '?listId=filtrRestaurang';  // + '&option=' + option;
	} else {
		language == 'en' ? alert("Please enter something to search for") : alert("Du måste ange minst ett sökord");

	}
}

$(".articleThreeCol").live("mouseover mouseout", function (event) {
    if (event.type == "mouseover") {
        $(".articleImageHover", this).css("display", "block");
        $(".articleCaption", this).css("display", "none");
    }
    if (event.type == "mouseout") {
        $(".articleImageHover", this).css("display", "none");
        $(".articleCaption", this).css("display", "block");
    }
});

function doQuickSearch() {
	var query = $("#tbSearchField").val();

	if (query.length > 2) {
		var url = en ? '/en/quicksearch' : '/sv/quicksearch';
		$.getJSON(url, { query: query, language: language },
			function (json) {
				//console.log(json.rests);
				if (json != "") {
					$("div#searchExtras").html('');
					if (json.rests != '') {
						$("div#searchExtras").append("<h3>Restauranger</h3>");
						$("div#searchExtras").append(json.rests);
					}
					if (json.orter != '') {
						$("div#searchExtras").append("<h3>Orter</h3>");
						$("div#searchExtras").append(json.orter);
					}
					if (json.inriktningar != '') {
						$("div#searchExtras").append("<h3>Inriktningar</h3>");
						$("div#searchExtras").append(json.inriktningar);
					}
					//					if (json.searchSudgestions != '') {
					//						$("div#searchExtras").append("<h3>Sökförslag</h3>");
					//						$("div#searchExtras").append(json.searchSudgestions);
					//					}
					$("div#searchExtras").show();
				} else {
					$("div#searchExtras").html('');
					$("div#searchExtras").hide();
				}
			}
		);
	} else {
		$("div#searchExtras").html('');
		$("div#searchExtras").hide();
	}
}

//On Hover Over
function megaHoverOver() {
	$(this).find(".sub").stop().fadeTo(100, 1).show(); //Find sub and fade it in
	(function ($) {
		//Function to calculate total width of all ul's
		jQuery.fn.calcSubWidth = function () {
			rowWidth = 0;
			//Calculate row
			$(this).find("ul").each(function () { //for each ul...
				rowWidth += $(this).width(); //Add each ul's width together
			});
		};
	})(jQuery);

	if ($(this).find(".row").length > 0) { //If row exists...

		var biggestRow = 0;

		$(this).find(".row").each(function () {	//for each row...
			$(this).calcSubWidth(); //Call function to calculate width of all ul's
			//Find biggest row
			if (rowWidth > biggestRow) {
				biggestRow = rowWidth;
			}
		});

		$(this).find(".sub").css({ 'width': biggestRow }); //Set width
		$(this).find(".row:last").css({ 'margin': '0' });  //Kill last row's margin

	} else { //If row does not exist...

		$(this).calcSubWidth();  //Call function to calculate width of all ul's
		$(this).find(".sub").css({ 'width': rowWidth }); //Set Width

	}
}
//On Hover Out
function megaHoverOut() {
	$(this).find(".sub").stop().fadeTo(100, 0, function () { //Fade to 0 opactiy
		$(this).hide();  //after fading, hide it
	});
}

$(document).ready(function () {

	var config = {
		sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
		interval: 100, // number = milliseconds for onMouseOver polling interval
		over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
		timeout: 100, // number = milliseconds delay before onMouseOut
		out: megaHoverOut // function = onMouseOut callback (REQUIRED)
	};

	$("#rgHeadNavInner ul li .sub").css({ 'opacity': '0' }); //Fade sub nav to 0 opacity on default
	$("#rgHeadNavInner ul li").hoverIntent(config); //Trigger Hover intent with custom configurations
	$("#rgHeadNavInner ul li a.hasSub").attr('href', '#');

	$("#rgRestListFilterFlikar a").click(function (a) {
		if (gettingData == 0) {
			gettingData = 1;
			if (a.target.id != lastShown) {
				$("#rgRestListFilterFlikar a").removeClass("selected");
				$.getJSON("/handlers/getInrList", { listId: a.target.id }, function (json) {
					$("div#filtrList").html(json.html);
					lastShown = a.target.id;
					$(a.target).addClass("selected");
					gettingData = 0;
					$('#filtrList').slideDown('normal', function () {
						$("#filtrShowHide img").attr("src", "/_images/mainDesign/filter-up.jpg").addClass("filtrClose");
					});
				});
			}
			else {
				$('#filtrList').slideUp('normal', function () {
					$("#filtrShowHide img").attr("src", "/_images/mainDesign/filter-down.jpg").removeClass("filtrClose");
					lastShown = ''; oldType = 1; gettingData = 0;
					$("#rgRestListFilterFlikar a.selected").removeClass("selected");
				});
			}
		}
		return false;
	});

	$('a.rgShowFilterInrFull').live('click', function (a) {
		$(a.target.hash).show();
		$.colorbox({ inline: true, href: a.target.hash, opacity: 0.4, initialWidth: 100, initialHeight: 100, onCleanup: function () { $(a.target.hash).hide(); } });
	});

	$("#filtrShowHide img").click(function (a) {
		if (gettingData == 0) {
			gettingData = 1;
			if (!$(a.target).hasClass("filtrClose")) {
				$("#rgRestListFilterFlikar a").removeClass("selected");
				$.getJSON("/sv/handlers/getInrList", { listId: "filtrRestaurang" }, function (json) {
					$("div#filtrList").html(json.html);
					lastShown = "filtrRestaurang";
					$("#filtrRestaurang").addClass("selected");
					gettingData = 0;
					$('#filtrList').slideDown('normal', function () {
						$("#filtrShowHide img").attr("src", "/_images/mainDesign/filter-up.jpg").addClass("filtrClose");
					});
				});
			}
			else {
				$('#filtrList').slideUp('normal', function () {
					$("#filtrShowHide img").attr("src", "/_images/mainDesign/filter-down.jpg").removeClass("filtrClose");
					lastShown = ''; oldType = 1; gettingData = 0;
					$("#rgRestListFilterFlikar a.selected").removeClass("selected");
				});
			}
		}
	});

//		$(".queryPopup ul#subAreas li a").live('click', function (a) {
//			var inrId = $(a.target).attr("id");
//			if (inrId) {
//				// Hämta in filters, omrId, nya inriktningen som ska till
//				// Kolla i filter om den inriktningen du ska lägga till redan finns där genom att splitta upp filters till en array och kolla igenom den.
//				// Skapa sedan en url och skicka användaren till den urlen...
//				var baseUrl = window.location.pathname;
//				var arrFilters = filters.split(',');
//				var arrMainFilters = mainfilters.split(',');
//				if ($.inArray(arrFilters, mainFilters, inrId) == -1) {
//					var strFilters = filters;
//					if (filters == '') { strFilters += inrId; } else { strFilters += ',' + inrId; }
//					var strMainFilters = mainfilters;
//					if (mainfilters == '') { strMainFilters += inrId; } else { strMainFilters += ',' + inrId; }
//					var intOmrId = '';
//					if (omrId == 0) { intOmrId = ''; } else { intOmrId = omrId; }
//					var url = baseUrl + "?omr=" + intOmrId + "&h=" + strMainFilters + "&f=" + strFilters + "&page=";
//					window.location = url;
//				}
//			}
//			return false;
//		});

	$("#filterList").live('click', function (a) {
		var inrId = $(a.target).attr("id");
		if (inrId) {
			// Hämta in filters, omrId, nya inriktningen som ska till
			// Kolla i filter om den inriktningen du ska lägga till redan finns där genom att splitta upp filters till en array och kolla igenom den.
			// Skapa sedan en url och skicka användaren till den urlen...
			var baseUrl = window.location.pathname;
			var arrFilters = filters.split(',');
			var arrMainFilters = mainfilters.split(',');
			if ($.inArray(arrFilters, inrId) == -1) {
				var strFilters = filters;
				if (filters == '') { strFilters += inrId; } else { strFilters += ',' + inrId; }
				var strMainFilters = mainfilters;
				//if (mainfilters == '') { strMainFilters += inrId; } else { strMainFilters += ',' + inrId; }
				var intOmrId = '';
				if (omrId == 0) { intOmrId = ''; } else { intOmrId = omrId; }
				var url = baseUrl + "?listId=" + listId + "&omr=" + intOmrId + "&h=" + strMainFilters + "&f=" + strFilters + "&page=&c=" + capacity;
				window.location = url;
			}
		}
		return false;
	});

	$(".buttonFilter").live("click", function (a) {
		var inrId = $(this).attr("id");
		if (inrId) {
			// Hämta in filters, omrId, nya inriktningen som ska till
			// Kolla i filter om den inriktningen du ska lägga till redan finns där genom att splitta upp filters till en array och kolla igenom den.
			// Skapa sedan en url och skicka användaren till den urlen...
			var baseUrl = window.location.pathname;
			var arrFilters = filters.split(',');
			var arrMainFilters = mainfilters.split(',');
			if ($.inArray(arrFilters, inrId) == -1) {
				arrFilters.remove(arrFilters.indexOf(inrId));
				var strFilters = arrFilters.join(",");
				arrMainFilters.remove(arrMainFilters.indexOf(inrId));
				var strMainFilters = arrMainFilters;
				var intOmrId = '';
				if (omrId == 0) { intOmrId = ''; } else { intOmrId = omrId; }
				var url = baseUrl + "?listId=" + listId + "&omr=" + intOmrId + "&h=" + strMainFilters + "&f=" + strFilters + "&page=&c=" + capacity;
				window.location = url;
			}
		}
		return false;
	});


	//	$(".buttonFilter").live("click", function (a) {
	//		var inrId = $(a.target).attr("id");
	//		if (inrId) {
	//			var baseUrl = window.location.pathname;
	//			var arrFilters = mainfilters.split(',');
	//			var arrMainFilters = mainfilters.split(',');
	//			if ($.inArray(arrFilters, arrMainFilters, inrId) == -1) {
	//				arrFilters.remove(arrFilters.indexOf(inrId));
	//				var strFilters = arrFilters.join(",");
	//				arrMainFilters.remove(arrMainFilters.indexOf(inrId));
	//				var strMainFilters = arrMainFilters.join(",");
	//				var intOmrId = '';
	//				if (omrId == 0) { intOmrId = ''; } else { intOmrId = omrId; }
	//				var url = baseUrl + "?omr=" + intOmrId + "&h=" + strMainFilters + "&f=" + strFilters + "&page=";
	//				window.location = url;
	//			}
	//		}
	//		return false;
	//	});

	$("span.rgRestGridImage").hover(function (e) {
		$(this).children("span").stop(true, true).fadeTo("fast", 0.8);
	}, function (e) {
		$(this).children("span").stop(true, true).fadeTo("fast", 0);
	});

	$("span#bytOmrade").click(function (e) {
		$('#restDivOmraden').show();
		$.colorbox({ inline: true, href: "#restDivOmraden", opacity: 0.4, initialWidth: 100, initialHeight: 100, onCleanup: function () { $("#restDivOmraden").hide(); } });
	});

	$("a#guideLoginButton").click(function (e) {
		$("div#loginWindow").toggle();
		e.preventDefault();
	});

	$("#loginWindowClose").click(function () {
		$("div#loginWindow").hide();
	});

	$("a#guideMemberButton").click(function (e) {
		$("div#memberWindow").toggle();
		e.preventDefault();
	});

	$("#memberWindowClose").click(function () {
		$("div#memberWindow").hide();
	});

	$("a#guideSaveSearch").click(function (e) {
		$("div#guideSaveSearchWindow").toggle();
		e.preventDefault();
	});

	$("#guideSaveSearchClose").click(function () {
		$("div#guideSaveSearchWindow").hide();
	});

	if (language == 'en') en = true;

	$('#tbSearchField').focusin(function () {
		//$('#tbSearchField').addClass(' rg-search-focus ');
		if (this.value.length > 2) {
			$('div#searchExtras').css('display', 'block');
		}
		if (this.value == '') {
			$('div#searchExtras').val('<div style="padding-top:5px;">Skriv in något för att söka efter en restaurang, inriktning eller vad du vill!</div>');
		} else {
			doQuickSearch();
		}
	});

	$('#tbSearchField').focusout(function () {
		$(this).val("");
		//$('#tbSearchField').removeClass(' rg-search-focus ');
	});

	$('body').bind('click', function (e) {
		//    		if ($('div#searchDiv').closest('div#searchDiv').length == 0) {
		//    			$('div#searchExtras').css('display', 'none');
		//            }
		$('div#searchExtras').css('display', 'none');
		//            else if ($(e.target).closest('div#selStart').length == 0) {
		//    			$('div#selStartWhatDiv').css('display', 'none');
		//    		}
	});

	$("body").append('<div id="ajaxBusy"><img src="/_images/ajax-loader2.gif" style="display: block;" /></div>');

	// Ajax activity indicator bound 
	// to ajax start/stop document events
	$(document).ajaxStart(function () {
		$('#ajaxBusy').center().show();
	}).ajaxStop(function () {
		$('#ajaxBusy').hide();
	});

	var searchDelay = undefined;
	if (currentSearch) {
		if (currentSearch != '') {
			var query = unescape(currentSearch);
			$("#tbSearchField").val(query);
		}
	}

	$("#tbSearchField").bind('keyup', function (e) {
		if (searchDelay != undefined) {
			clearTimeout(searchDelay);
		}
		searchDelay = setTimeout(doQuickSearch, 300);

		if (e.keyCode == 13) {
			doSearch();
			return false;
		}
	});

});

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function (from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
};

var msie6 = $.browser == 'msie' && $.browser.version < 7;

if (!msie6) {
	var top = $('#rgSharebox').offset().top - parseFloat($('#rgSharebox').css('margin-top').replace(/auto/, 0));

	$(window).scroll(function (event) {
		var y = $(this).scrollTop();

		if (y >= top) {
			$('#rgSharebox').addClass('fixed');
			//$('#previousSearch').addClass('fixed');
		} else {
			$('#rgSharebox').removeClass('fixed');
			//$('#previousSearch').removeClass('fixed');
		}
	});
}

$('#rgSharebox').hover(
	function () {
		$('#rgSharebox').animate({
			right: '0px',
			width: '113px'
		}, 500);
	},
	function () {
		$('#rgSharebox').animate({
			right: '0px',
			width: '36px'
		}, 500);
	}
);
