var currentWidth = 0;
var map;
var supportsOrientationChange;
var orientationEvent;


$(document).ready(function() {
	hideAddressBar();	
	toggleClearSearchForm();	
	displayTextBox();	
	showCallButton();
	toggleTab();		
	hideBrandFilter();

	// New js
	initAppPresentation();
	ShowShareOptions();
	iniMultimedia();	
	collapseBussinessInfo();
	disableLink();
	closePopUpFilter();
	searchFilter();
	setInterval(GetWidthHeigthMap, 500);	
	
	$(".link:not(.unica)").live("click", function(e) {
		window.location = $(this).attr("href");
		
		e.stopPropagation();
	});
	
	hideCategorieLandscape();
	onOrientationChange(function() {ResizeListingLine();});
	onOrientationChange(function() {hideAddressBar();});

	initTypeAhead();
	ResizeListingLine();
	
});

function closePopUpFilter(){	
	if($(".btnClose").length > 0){
		$(".btnClose").click(function(e) {
			if ($(this).parents('.reveal-small').length > 0) {
				$(".reveal-small").css('right', '-180px');
				$(".reveal-small").css('display', 'none');
				
			} else {
				$(this).parent().parent().hide();
			}
			
			e.preventDefault();
			e.stopPropagation();
		});
	}
}

function hideSticky(){
	$("#sliderDeals").removeClass('open').addClass('bgRedGradient').removeClass('bgWhiteGradient');
}

function iniMultimedia(){
	if($(".multimedia").length > 0){	
		$(window).load(function(){	
			SetWidthMultimedia();			
		});
		
		onOrientationChange(function() {SetWidthMultimedia();});	
	}
}

function collapseBussinessInfo(){
	$('.businessInfo .bgYellowGradient').click(function(){
		$(this).next().toggle();
		$(this).children('h3').children('span').toggleClass('collapse');
	});
}

function SetWidthMultimedia(){	
	$('.multimedia').each(function(index) {
		$(this).find('a.prev').css("padding-left", '0');
		var withContainerImage= $(this).parent('.images').width();
		var btnWidth = $(this).find("a.prev").outerWidth(true) +  $(this).find("a.next").outerWidth(true);
		var sliderWidth = withContainerImage - btnWidth; 
		var nbImagesRow = Math.floor(sliderWidth / $(this).find(".overview li").first().width());	
		
		if(nbImagesRow < $(this).find(".overview li").length){
			$(this).find('a.prev').css("padding-left", (sliderWidth % $(this).find(".overview li").first().width())/2);
			sliderWidth = nbImagesRow * $(this).find(".overview li").first().width();		
		}		
		else {
			sliderWidth = $(this).find(".overview li").first().width() * $(this).find(".overview li").length;	
			$(this).find('a.prev').css("padding-left", ($(this).parent().width() - sliderWidth - $(this).find('a.prev').outerWidth(true) - $(this).find('a.next').outerWidth(true)) /2);		
		}
		
		$(this).find('.viewport').width(sliderWidth);			
		$(this).tinycarousel({ display: nbImagesRow });
	});		
}

function ShowShareOptions() {
	$('.share').click(function(e) {
		$('.action').toggleClass('move');
		$(this).toggleClass('unica');
		e.preventDefault();
	});
}

function ResizeListingLine() {
	$('.list>h4').width(function(index, width) {return $(this).parent().width() - $(this).next('.rightInfo').outerWidth(true);});
	$('.list.msp>.address').width(function(index, width) {return $(this).parent().width() - $(this).prev('.rightInfo').outerWidth(true);});
	
	if ($('.merchantName').length > 0) {
		var info = $('.merchantName');
		var contentWidth = info.prev('h3').innerWidth();
		
		info.width(function (index, width) { return contentWidth - $(this).next().outerWidth(); });
	}
}



function hideCategorieLandscape(){	
	if (isBlackBerry() && window.innerWidth > window.innerHeight)
		$(".cats tr").hide();
}
// End new js

function hideAddressBar() {
	setTimeout(function() {
		window.scrollTo(0, 1);
	}, 1000);
}

function initAppPresentation() {
	if ($('#appPres').length != 0) {
		if ($('#appPres').hasClass('checkResolution') && window.innerWidth > window.innerHeight) {
			//$('#appPres').addClass('landscape');
			return false;
		}

		$('#appPres').reveal({
			animation : 'none'
		});
		
		
		if (window.innerWidth < window.innerHeight) {
			freezeScreen();
			onOrientationChange(function() {unfreezeScreen();});
		}

		$('#appPres a').click(function(e) {
			$('#appPres').trigger('reveal:close');
			$('.downloadAppLink').hide();
			unfreezeScreen();
		});
	}
}

function freezeScreen() {
	$('body').bind("touchmove", function(event) {
		event.preventDefault();
	});

	$('body').css('overflow', 'hidden');
}

function unfreezeScreen() {
	$('body').unbind();
	$('body').css('overflow', '');
}

function initTypeAhead() {
	if ($("#searchwhat:not(.noComplete) input") != null) {
		$("#searchwhat:not(.noComplete) input").autocomplete({
			source : function(request, response) {
				$.ajax({
					url : "/business/suggest",
					dataType : "jsonp",
					data : {
						text : request.term,
						field : "what"
					},
					delay : 200,
					success : function(data) {
						response($.map(data.suggestedValues, function(item) {
							return {
								label : item.value,
								value : item.value
							};
						}));
					}
				});
			},

			minLength : 2,
			position: {
				  my: "left top",
				  at: "left top",
				  of: ".cats"
			},

			select : function(event, ui) {
				this.value = ui.item.label;
			},

			open : function() {
				if ($("#searchwhat:not(.noComplete) input").is(":focus")) {
					$(".ui-corner-top").removeClass("ui-corner-top").addClass("ui-corner-all");
					$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
				} else {
					$("#searchwhat:not(.noComplete) input").autocomplete( "close" );
				}
			},

			close : function() {
				$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
			}
		});

		$("#searchwhat:not(.noComplete) input").focus(function() { window.scrollTo(0, $('.inputForm').position().top); });
	}

	var whereField = $("#searchwhere:not(.noComplete) input");
	if (whereField.length > 0) {
		whereField.autocomplete({
			source : function(request, response) {
				$.ajax({
					url : "/business/suggest",
					dataType : "jsonp",
					data : {
						text : request.term,
						field : "where"
					},
					delay : 200,
					success : function(data) {
						response($.map(data.suggestedValues, function(item) {
							return {
								label : item.value,
								value : item.value
							};
						}));
					}
				});
			},

			minLength : 2,
			position: {
				  my: "left top",
				  at: "left top",
				  of: ".cats"
			},

			select : function(event, ui) {
				this.value = ui.item.label;
			},

			open : function() {
				if ($("#searchwhere:not(.noComplete) input").is(":focus")) {
					$(".ui-corner-top").removeClass("ui-corner-top").addClass("ui-corner-all");
					$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
				} else {
					$("#searchwhere:not(.noComplete) input").autocomplete( "close" );
				}
			},

			close : function() {
				$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
			}
		});
		
		$("#searchwhere:not(.noComplete) input").focus(function() { window.scrollTo(0, $('.inputForm').position().top); });
	}
}

function onOrientationChange(funct) {
	supportsOrientationChange = "onorientationchange" in window;	
	orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

	window.addEventListener(orientationEvent, funct, false);
}

function isAppleDevice() {
	return isIpad() || isIphone() || isIpod() ? true : false;
}

function isIphone() {
	return navigator.platform == 'iPhone' ? true : false;
}

function isIpod() {
	return navigator.platform == 'iPod' ? true : false;
}

function isIpad() {
	return navigator.platform == 'iPad' ? true : false;
}

function isAndroid() {
	return navigator.platform == 'Android' ? true : false;
}

function isBlackBerry(){
	return navigator.platform == 'BlackBerry' ? true : false;
}

function toggleClearSearchForm() {
	var clickEvent = "ontouchstart" in window
			&& navigator.userAgent.toLowerCase().search("iphone os [3-9]") != -1 ? "touchstart"
			: "mousedown";

	$('.search-field-outer').addClass('full');

	$(".search-field").bind(
			"keyup",
			function(e) {
				$(this).parent().next().children('._clear_button').css(
						'display', $(this).val() != '' ? 'block' : 'none');
				$(this).parent().parent().removeClass('full');
			});

	$("._clear_button").bind(clickEvent, function(e) {
		$(this).parent().prev().children().focus();
		$(this).parent().prev().children().val("");
		$(this).hide();
		$(this).parent().parent().addClass('full');
		$(".ui-menu").hide();
		e && e.preventDefault();
	});

	$(".search-field").bind("blur", function(e) {
		$("._clear_button").hide();
		$(this).parent().parent().addClass('full');
	});

	$(".search-field").bind("focus", function(e) {
		if ($(this).val() != '' && $(this).val() != $(this).attr('default')) {
			$(this).parent().next().children('._clear_button').show();
			$(this).parent().parent().removeClass('full');
		} else {
			$(this).parent().next().children('._clear_button').hide();
			$(this).parent().parent().addClass('full');
		}
	});
}

function showCallButton() {
	if (!isIpod() && !isIpad()) {
		$(".btnCall").show();
		$(".btnCall").css('visibility', 'visible');		
	}
	else if (isIpod() || isIpad()){
		$(".call").addClass("desactivate").attr('href', '#');
		
	}

}

function disableLink(){	
		$(".desactivate").click(function(e){
			e.preventDefault();
		});	
}

function displayTextBox() {
	$(".errorCheckBox").click(
			function(e) {
				$(this).is(':checked') ? $(this).nextAll(
						'div.reportErrorDiv:first').show() : $(this).nextAll(
						'div.reportErrorDiv:first').hide();
			});

	$('.errorCheckBox:checked').nextUntil('.errorCheckBox', '.reportErrorDiv')
			.show();
}

function fillup(param) {
	document.getElementById("whatwho").value = param;
	document.getElementById("inputForm").submit();
}

function fillup(param, mobiCode) {
	document.getElementById("whatwho").value = param;
	document.getElementById("mobiCode").value = mobiCode;
	document.getElementById("inputForm").submit();
}

function filterUsage() {
	var value = '';
	
	$('.boxFilter input[type=checkbox]').each(function(index, item) {
		if ($(item).is(':checked')) {
			value = item.value;
			
			return false;
		}
	});
	
	if (value == '') {
		$('.boxFilter input[type=checkbox]').removeAttr('disabled');
	} else if (value.indexOf('dl') == 0) {
		$('.boxFilter input[type=checkbox]:not([value*=dl])').attr('disabled', 'disabled');
	} else {
		$('.boxFilter input[type=checkbox][value*=dl]').attr('disabled', 'disabled');
	}
}

function searchFilter() {
	$('.boxFilter input[type=checkbox]').change(filterUsage);
	
	if ($("#sflag").val() != undefined) {
		var listFlag = $("#sflag").val().split('-');

		$('.boxFilter input[type=checkbox]').attr('checked', false);

		for ( var i = 0; i < listFlag.length; i++) {
			if (listFlag[i].length > 0) {
				$('.boxFilter input[value*=' + listFlag[i].substr(0, 2) + ']').attr('checked', true);
			}
		}
		
		filterUsage();

		$(".findlocation .btn").click(function(e) {
			$("#sflag").val('');
		});

		$(".filterBtn a").click(function(e) {
			
			var filterText = "";
			$('.boxFilter input').each(function(index) {
				if ($(this).is(':checked')) {
					if (filterText != "")
						filterText += '-' + $(this).val();
					else
						filterText += $(this).val();
				}
			});

			if ($('#tabmap').is(':visible')) {
				var action = $('#inputForm').attr('action');
				var zoom = "&zoom=" + map.getZoom();
				action = action + "?map=true" + zoom;
				$('#inputForm').attr('action', action);
			}

			document.getElementById("sflag").value = filterText;
			document.getElementById("inputForm").submit();
		});

		$('.rightBlock_en .btn').click(function() {
			document.getElementById("sflag").value = '';
		});
	}
}

function GetWidthHeigthMap() {
	var topMenuHeight = ($(".titlebar").height());
	var footerHeight = 0;// + ($(".footer").outerHeight(true));
	var errorMessageHeight = $(".alertLink:visible").outerHeight();
	var tabHeight = 0;
	var screenHeight = window.innerHeight;
	var mapWidth = $("#map-wrapper").width();

	if ($(".tabsSearch").length > 0)
		tabHeight = ($(".tabsSearch").outerHeight(true));

	if (isAppleDevice() || isAndroid()) {
		mapWidth = "100%";
	}

	var mapHeight = screenHeight - footerHeight - topMenuHeight - tabHeight - errorMessageHeight;

	$("#map_canvas").height(mapHeight);
	$("#map_canvas").width(mapWidth);

}

// need to check if this function hover(obj, s) is called
function hover(obj, s) {
	obj.className = (s == true ? 'listhover' : 'list');
}

$('.unica:not(.desactivate)').live("click", function(e) {
	var url = $(this).attr('href');
	var target = $(this).attr('target') != undefined && $(this).attr('target') == '_blank';
		
	$.ajax({
		async : false,
		url : $(this).attr('unica'),
		success : function(data) {
			$('#unicaImg').html(data);
			$('#unicaImg img').bind("load", function(e) {
				$(this).unbind(e);
				
				if ($(this).attr('unicaType') == 'strick' && url != undefined) {
					if(target)
						window.open(url);					
					else
						window.location = url;
				}
			});
		}
	});
	
	if ($(this).attr('unicaType') != 'strick' && url != undefined) {
		if(target)
			window.open(url);					
		else
			window.location = url;
	}

	
	e.preventDefault();
	e.stopPropagation();
});

$('a.unicaPhoto').live("click", function(e) {
	$.ajax({
		async : false,
		url : $(this).attr('unica'),
		success : function(data) {
			$('#unicaImg').html(data);
		}
	});
});
var posImage;


function getnewUnica(btn, iterator) {
	var unicaUrl = btn.attr('unica').split('/');
	unicaUrl[3] = "photo_" + iterator;
	var newUnica = '';
	for ( var i = 1; i != unicaUrl.length; ++i) {
		newUnica += '/' + unicaUrl[i];
	}

	btn.attr('unica', newUnica);
}

function toggleTab() {
	$(".tabsSearch li.menu").click(function(e) {
		if (!$(this).hasClass('active')) {
			$('.tab').toggle();
			$('.tabsSearch li.menu').toggleClass('active');
			$('#sliderDeals').toggle();
			$('#popupFilter').hide();
			e.preventDefault();
			ResizeListingLine();
		}
	});
	
	$("li#btnFilter a:first").click(function(e) {
		$('.tabsSearch .boxFilter').toggle();
		$(this).toggleClass("open");
		
		if ($('#popupFilter .btnClose').length > 0) {
			$('#popupFilter .btnClose').click();
		}
			
		e.preventDefault();
	});

	$(".tabsSearch .menu").click(function(e) {
		$('.alertLink').hide();
		e.preventDefault();
	});
}

function hideBrandFilter() {
	$('#map').click(function(e) {
		$('#bottomMenuBF').toggleClass('hideMBF');
		e.preventDefault();
	});

	$('#list').click(function(e) {
		$(".footer").css("margin-top", "");
		$('#bottomMenuBF').toggleClass('hideMBF');
		e.preventDefault();
	});
}


function getCookie(c_name) {
	var name, value, ARRcookies = document.cookie.split(";");

	for ( var i = 0; i < ARRcookies.length; i++) {
		name = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
		value = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
		name = name.replace(/^\s+|\s+$/g, "");

		if (name == c_name) {
			return unescape(value);
		}
	}

	return false;
}



function setPosImageViewer(){	
	if($('#photoViewer .image').length > 0){
		widthImage = $('#photoViewer .image').outerWidth() - $('.btnCloseImage').position().left;//pos left btnCloseImage negative 
		heightImage = $('#photoViewer .image').height() - $('.btnCloseImage').position().top;//pos top btnCloseImage negative 
		topPos = ((window.innerHeight - heightImage)/2) + window.scrollY;
		leftPos = ((window.innerWidth - widthImage)/2) + window.scrollX;		
		$('#photoViewer').height(window.innerWidth);
		
		$('#photoViewer').css('top', topPos + "px");    
		$('#photoViewer').css('left', leftPos + "px");	
	}
}

