function isBlank(text) {
    return /^\s*$/.test(text);
}

function applySearchFilter(url,field) {
	var f='#'+field;
	if(!isBlank($(f).val())) {
		var sep='?'; if(url.indexOf('?') >= 0) sep='&';
		window.location.href=url+sep+$(f).attr('name')+'='+$(f).val();
	} else $(f)[0].selectedIndex = 0;
}

function changBrandTechnicalFilter(field) {
	var f='#'+field;
	if(!isBlank($(f).val())) window.location.href=$(f).val();
	else $(f)[0].selectedIndex = 0;
}

function changeTechnicalFilter(field) {
	var f='#'+field;
	if(!isBlank($(f).val())) {
		var sep='?';
		form=document.forms['frmtekfilter']
		var url=form.action;
		if(url.indexOf('?')>=0) url=url.substring(0, url.indexOf('?'));
		elems=form.elements;
		for(i=0;i<elems.length;i++) {
			if(elems[i].name.substring(0,2)=='tf' && elems[i].value!='') {
				url=url+sep+elems[i].name+'='+elems[i].value;
				sep='&';
			}
		}
		window.location.href=url;
	} else $(f)[0].selectedIndex = 0;
}

function submitReview(state) {
	if(state==1) {
		form=document.forms['review'];
		if(isBlank($('input[name=title]').val()) || isBlank($('textarea[name=textreview]').val()) || $('#rating').val()==-1) alert(G_LBLPLZFILLALL);
		else if($('textarea[name=textreview]').val().length > $('textarea[name=textreview]').attr('maxlength')) alert(G_LBLCONTENTTOOLONG);
		else form.submit();
	} else if(state==2) {
		form=document.forms['reviewvalidate'];
		form.submit();
	}
}

function submitPhoto() {
	form=document.forms['photo'];
	if(isBlank(form.legende.value) || isBlank(form.filename.value)) alert(G_LBLPLZFILLALL);
	else form.submit();
}

function openPhotoFullSize(id, w, h) {
	url = '/shopping/core/photofullsize.jsp?id='+id;
	return openCenterWnd(url,'fullscreenwnd',1000,800,'yes','yes');
}

function openCenterWnd(url,name,w,h,size,scroll){
 	var str='width='+w;
	str+=',height='+h;
	str+=',left='+(screen.width-w)/2;
	str+=',top='+(screen.height-h)/2;
	str+=',resizable='+((size) ? 'yes' : 'no');
	str+=',scrollbars='+((scroll) ? 'yes' : 'no');
	str+=',menubar=no,status=no,toolbar=no';
  	g_lastOpenedWnd=window.open(url,name,str);
	g_Window_Height=h;
	g_Window_Width=w;
	g_lastOpenedWnd.opener=window;
	g_NB_WAIT=0;
  	return g_lastOpenedWnd;
}

function rateThistPhoto() {
	voted=0;
	form=document.forms['ratethisphoto'];
	for(var i=0;i<form.vote.length;i++) {
		if (form.vote[i].checked) {
			voted=form.vote[i].value;
			break;
		}
	}
	if(voted==0)
		alert(G_LBLPLZMAKEACHOICE);
	else {
		$('#updater001').load('/shopping/actions/dophotovote.jsp', {'id':$('#img001').attr('value'), 'rate':voted});
		votebutton=$('#submit001').attr('disabled',true);
	}
	return false;
}

function openProductPhotoSize2(t,c,u) {
	jQuery.slimbox(u, t+'<br/>'+c, {counterText: c});
	return false;
}

function nextVendors(id,type,producttype,sort,order,zipcode) {
	var url='/shopping/includes/iproductvendors.jsp';
	if($('#marchandBloc')!=undefined && !$('#marchandBloc').is(':visible'))
		blocktoupdate='#rtypecontent1';
	else {
		if($('#marchand1')!=undefined && $('#marchand1').is(':visible')) blocktoupdate='#marchand1';
		else blocktoupdate='#marchand2';
	}
	$(blocktoupdate).load(url, {'rp': id, 'type': type, 'pt':producttype, 'sort': sort,'order':order, 'zipcode': zipcode});
	return false;
}

function showMarchandTabs(on,off) {
	if($('#marchand'+off)!=null) {
		$('#marchand'+off).hide();
		$('#marchantTab'+off).removeClass('active');
	}
	if($('#marchand'+on)!=null) {
		$('#marchand'+on).show();
		$('#marchantTab'+on).addClass('active');
	}
	return false;
}

function switchOverviewTabs(id,producttype,contenttype,on,page,filter) {
	var zipcodeparam='';
	for(i=1;i<10;i++) {
		if($('#rtype'+i)!=undefined) {
			if(i!=on) $('#rtype'+i).removeClass('active');
			else $('#rtype'+i).addClass('active');
		}
	}
	var url='/shopping/includes/ireviewslist.jsp';
	if(contenttype==0) url='/shopping/includes/ioverview.jsp';
	else if(contenttype==1) url='/shopping/includes/inewslist.jsp';
	else if(contenttype== 6015) url='/shopping/includes/ivideoslist.jsp';
	else if(contenttype==2) {
		if(on==8) { 
			contenttype=0;
			if($('#zipcode01')!=undefined && !isBlank($('#zipcode01').val())){
				zipcodeparam='&zipcode='+$('#zipcode01').val();
			}
		} else {
			contenttype=1;
		}
		url='/shopping/includes/iproductvendors.jsp';
	} else if(contenttype==6023) url='/shopping/includes/iphotoslist.jsp';
	if(filter==undefined) filter=0;
	$('#rtypecontent1').load(url,
		{'rp':id,'type':contenttype,'tabidx':on,'filter':filter,'page':page,'pt':producttype,'zipcode':zipcodeparam},
		function(){if(producttype==6 && contenttype==0) window.onload = displayGoogleMap();});
	if($('#marchandBloc')!=undefined) {
		if(on==8 || on==9) $('#marchandBloc').hide();
		else if(!$('#marchandBloc').is(':visible')) $('#marchandBloc').show();
	}
	return false;
}

var G_SHOPTIMEOUT;
function delayedShowAssocietedPhoto(block,id) {
	G_SHOPTIMEOUT=top.setTimeout('showAssocietedPhoto('+block+','+id+')',150);
}

function normalShowAssocietedPhoto(block,id) {
	top.clearTimeout(G_SHOPTIMEOUT);
	if($('#photo'+block+''+id)!=undefined)
		showAssocietedPhoto(block,id);
}

function showAssocietedPhoto(block,id) {
	for(i=0;i<5;i++) {
		if(i==id) {
			$('#photo'+block+''+i).show();
			$('#td'+block+''+i).css('backgroundColor','#FFFFFF');
			$('#td'+block+''+i).css('fontWeight','bold');
		} else {
			if($('#photo'+block+''+i)!=undefined) {
				$('#photo'+block+''+i).hide();
				$('#td'+block+''+i).css('backgroundColor','#f2f2f2');
				$('#td'+block+''+i).css('fontWeight','normal');
			}
		}
	}
}

function voteForThisProduct(id, type) {
	var content='#votecontent'+id;
	$(content).onclick=function(){ return false; };
	$(content).addClass('clicked');
	$(content).load('/shopping/actions/doproductvote.jsp',{'rp':id,'pt':type});
	return false;
}

function openTrackingIPH(iphElementid) {
	window.open($('#iphurl'+iphElementid).attr('href'));
}

function openTrackingIPV(ipvElementid) {
	window.open($('#ipvurl'+ipvElementid).attr('href'));
}

function highlightPhoto(id, on) {
	if(on == true) $('#photo'+id).setStyle('border: 1px solid #ccc;');
	else $('#photo'+id).setStyle('border: 1px solid #edeef0;');
}

function shopSendToaFriend(id,type) {
	var div='#staf'+id;
	$(div).load('/shopping/includes/tools/itsendtoafriendform.jsp', {'rp':id,'pt':type}, function(){onCompleteSTAF(id, type);});
	$(div).show();
	return false;
}

function onCompleteSTAF(id,type) {
	$('#ifstaf'+id).attr('src','/shopping/includes/shared/istafcontent.jsp?preview=true&rp='+id+'&pt='+type);
	$('#stafrr'+id).val(document.location.href);
	var c = $.ajax({url: '/shopping/includes/shared/istafcontent.jsp', data: {'rp':id, 'pt': type}, async: false});
	var div='#stafrc'+id;
	$(div).val(c.responseText);
	return false;
}

function submitSendToaFriend(id) {
	ok=true;
	form=document.forms['stafform'+id];
	elems=form.elements;
	for(i=0;i<elems.length;i++) {
		if(isBlank(elems[i].value)) {
			alert(G_LBLPLZFILLALL);
			elems[i].focus();
			ok=false;
			break;
		}
	}

	if(ok) {
		if(elems['stafcaptcha']!=undefined && !checkCaptcha(elems['stafcaptcha'].value)) {
			ok=false;
			alert(G_LBLERRCAPTCHA);
			document.location.reload();
		} else {
			idoc = getFrameDocument('ifstaf'+id);
			if(idoc!=undefined && idoc.getElementById('stafmsg'+id)) {
				msg = jQuery.trim(idoc.getElementById('stafmsg'+id).innerHTML);
				if(msg.length > 500) msg = msg.substring(0, 500);
				if(msg.indexOf('&nbsp;')==0) msg = msg.substring(6);
				if(msg.lastIndexOf('&nbsp;')==msg.lenght-7) msg = msg.substring(0,msg.length-6);
				content=$('#stafrc'+id).val();
				i=content.indexOf('<body>');
				if(i>0) {
					content = content.substring(0,i+6)+msg+content.substring(i+6,content.length);
					$('#stafrc'+id).val(content);
				}
			}
			document.body.style.cursor='wait';
			form.submit();
		}
	}
}

function getFrameDocument(framename) {
	var iframe = document.getElementById(framename)
	var doc=iframe.contentWindow || iframe.contentDocument;
    if(doc.document) doc=doc.document;
    return doc;
}

function checkCaptcha(code) {
	var r=false;
	var c=$.ajax({url:'/shopping/actions/docontrolcaptcha.jsp',data:{'code':code},async:false});
	if(c.responseText=='OK') r=true;
	return r;
}

function cancelSendToaFriend(id) {
	var form='#stafform'+id;
	$(form).parent().hide();
}

function activeEmbeddedVideo(id,url) {
	$('#video-'+id).html('<span style="margin:3px 9px 10px 0pt;"><object width="150" height="115"><param name="movie" value="'+url+'"></param><param name="allowfullscreen" value="true"></param><embed src="'+url+'" type="application/x-shockwave-flash" width="150px" height="115px" allowfullscreen="true"></embed></object></span>');
}

function showAllRefinementValues(refinename,page) {
	return _refinementsFunction(page, refinename);
}

var G_SHOPREFINEMENT;
function displayRefinement(name) {
	if(G_SHOPREFINEMENT) {
		oldNode = G_SHOPREFINEMENT;
	} else {
		sub=$('#rf01').children('div');
		oldNode=sub[3];
	}
	$(oldNode).hide();
	$('#rf'+name).show();
	G_SHOPREFINEMENT=$('#rf'+name);
	var menus=$('#lim'+name).parent().children('li');
	for(i=0;i<menus.length;i++) $(menus[i]).removeClass('active');
		$('#lim'+name).addClass('active');
}

function showAllRefinements(page) {
	return _refinementsFunction(page);
}

function closeAllRefinements() {
	$('#pl01').show();
	$('#pl02').remove();
}

function _refinementsFunction(page, refinename) {
	var divtoshow='#dzall_page'+page;
	if(refinename!=undefined && !isBlank(refinename)) {
		divtoshow='#dzrf'+refinename+'_page'+page;
	}
	var content='#pl01';
	$(content).hide();
	if($('#pl02')!=undefined) $('#pl02').remove();
	var elem=$(divtoshow).clone(true);
	elem.attr('id','pl02');
	$(content).before(elem);
	return true;
}

function displayHiddenRefinement(name) {
	var n='#lim'+name;
	closeAllRefinements();
	if(!$(n).is(':visible')) {
		parentNode = $(n).parent();
		parentNode.children('li:first').hide();
		oldNode = $(n).clone(true);
		$(n).remove();
		parentNode.children('li:first').before(oldNode);
		$(n).show();
	}
	displayRefinement(name);
}

function submitGistKeyword() {
	sep='?';
	url=$('#shurl01').val();
	if(url.indexOf('?')>0) sep='&';
	url=url+sep+'gk='+$('#shkeyword01').val();
	window.location.href=url;
}

function displayRestrictiveContent() {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+1);
	document.cookie="wsRestrictedContent=true;expires="+exdate.toGMTString();
}

function closeAllSelect() {
	$('div[class="shopfselectul"]').hide();
}

function openSelect(event, id) {
	$('div[class="shopfselectul"][id!="'+id+'"]').hide();
	var s = '#'+id;
	if($(s).is(':visible')) $(s).hide();
	else $(s).show();
	stopEventPropagation(event);
}

function stopEventPropagation(event) {
	event = event || window.event;
	if(event.stopPropagation) event.stopPropagation();
	else event.cancelBubble = true;
}

// google maps
var _WSHKEY;
var _WSHLATTITUDE;
var _WSHLONGITUDE;
var _WSHMSG;
function showGGNavigation(lattitude, longitude, key, msg) {
	$('#map_static').hide();
	$('#map_canvas').show();
	_WSHKEY = key;
	_WSHMSG = msg;
	_WSHLATTITUDE = lattitude;
	_WSHLONGITUDE = longitude;
	loadGGMapApi();
}

function loadGGMapApi() {
	if (typeof GMap2 != 'function') {
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = 'http://www.google.com/jsapi?key=' + _WSHKEY + '&callback=cbGGloadMap';
		document.getElementsByTagName("head")[0].appendChild(script);
	}
}

function cbGGloadMap() {
	google.load("maps", "2",{"callback" : cbGGInitMap});
}

function cbGGInitMap() {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById('map_canvas'));
		map.setCenter(new GLatLng(_WSHLATTITUDE, _WSHLONGITUDE), 15);
		map.setUIToDefault();
		map.openInfoWindow(map.getCenter(), document.createTextNode(_WSHMSG));
	}
}

// hotels prices
var _WSSIGLE;
var _WSDEFVAL;
var _WSJSONURL;
var _WSJSONTIMER;
var _WSSIGLE_POS; // 0 before, 1 after
var _WSJSONBLANKTIMER;

function startHotelPricesRetriever(url, sigle, defvalue, sigleposition) {
	_WSJSONURL=url;
	_WSSIGLE=sigle;
	_WSDEFVAL=defvalue;
	_WSSIGLE_POS=sigleposition;
	// everything will be blanked in 20s
	_WSJSONBLANKTIMER=top.setTimeout('setDefaultValueToHotelPrices()',20000);
	if(!isBlank(_WSJSONURL)) {
		$.getJSON('/shopping/actions/doremotejson.jsp?remoteurl='+escape(_WSJSONURL),
			function(json) {
				for(var i=0;i<json.length;i++) {
					if(json[i]['event'] && json[i]['event']=='search-handle') {
						var pos = _WSJSONURL.indexOf('/', 8);
						if(pos > 0 && json[i]['meta-id'] && !isBlank(json[i]['meta-id']) && json[i]['search-id'] && !isBlank(json[i]['search-id'])) {
							_WSJSONURL = _WSJSONURL.substring(0, pos)+'/svc/meta/hotel/'+json[i]['meta-id']+'/results?start=0&length=100&search_id='+json[i]['search-id'];
							_WSJSONTIMER=top.setTimeout('callJSONDatas()',1500);
						}
						break;
					}
				}
			}
		);
	}
}

function callJSONDatas() {
	$.getJSON('/shopping/actions/doremotejson.jsp?remoteurl='+escape(_WSJSONURL),
		function(json){
			var reloadAgain=true;
			for(var i=0;i<json.length;i++) {
				if(json[i]['event'] && json[i]['event']=='end-of-results') {
					reloadAgain=false;
					top.clearTimeout(_WSJSONTIMER);
					top.clearTimeout(_WSJSONBLANKTIMER);
					setDefaultValueToHotelPrices();
				} else if(json[i]['event'] && json[i]['event']=='result') {
					if(json[i]['status']=='OK' && json[i]['currency']!='AAA') {
    					hotecode=json[i]['supplier'];
    					var price=''+json[i]['price'];
    					if(price.indexOf('.') > 0)  price = price.substring(0,price.indexOf('.'));
    					if(_WSSIGLE_POS==0) $('#'+hotecode).html(_WSSIGLE+price);
    					else $('#'+hotecode).html(price+' '+_WSSIGLE);
                    } else if(!isBlank(json[i]['supplier'])) {
    					hotecode=json[i]['supplier'];
    					$('#'+hotecode).html(_WSDEFVAL);
                    }
				}
			}
			if(reloadAgain) {
				_WSJSONTIMER=top.setTimeout('callJSONDatas()',1500);
			}
		}
	);
}

function setDefaultValueToHotelPrices() {
	$("td[class='prix']:has(img)").html(_WSDEFVAL);
}