a",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="
";
actual.empty().html(phone_added);
phones_compara.push(id_modelo);
if (phones_compara.length == 3) {
$("#comparabtn a").trigger("click");
}
} else {
alert("Perfavore selezionare un altro telefono");
}
};
var remove_phone_callback = function (e) {
// console.log("entra a este call_back");
actual = $(this).parents('.pholder');
nodes = actual.nextAll('.pholder');
siguiente = nodes.eq(0);
futuro = nodes.eq(1);
if (siguiente.length > 0) {
actual.empty().html(siguiente.contents());
if (futuro.length > 0)
siguiente.empty().html(futuro.contents());
} else {
actual.html('');
new Autocomplete("#sb1", "#sb1_text", 'short', show_phone_callback);
}
elid_phone = $(this).attr('data-id');
// console.log(phones_compara)
phones_compara.splice(phones_compara.indexOf(elid_phone), 1);
}
function Autocomplete(thecontainer, thefield, layer_type, call_back) {
var d = "autocomplete" + AUTOCOMPLETE_COUNT++;
var e = '
';
$(thecontainer).append(e);
this.autocomplete = $("#" + d);
this.list = $("#" + d + " ul");
if ((call_back) && (typeof call_back === 'function')) this.call_back = call_back;
this.field = $(thefield);
/*eventos asignados a el campo*/
this.field.focus({ self: this }, mostrar_layer_callback);
this.field.keyup({ self: this }, mostrar_layer_callback);
this.field.blur({ self: this }, function (a) {
var b = a.data.self;
setTimeout(function () {
b.hide()
}, 200)
});
this.layer_type = (!layer_type) ? 'default' : layer_type;
if (this.layer_type === "short") this.list.addClass('autocomplete-short');
this.maxLines = AUTOCOMPLETE_MAX_LINES;
this.result = [];
this.selected = -1;
this.fullsearchTimeout = null; // used to avoid consecutive calls
this.fullsearchReady = {}; // use to avoid repeat the ajax calls
}
Autocomplete.prototype.setList = function (a) {
if (AUTOCOMPLETE_DISABLED) return;
// this.list.empty();
this.selected = -1;
if (this.layer_type === "default") {
var b = "";
for (var c = 0; c < a.length; c++) {
if (c == AUTOCOMPLETE_MAX_LINES) break;
var itema = a[c];
// Determina se un nuovo prodotto (smartwatch, tablet, laptop)
// Questi prodotti NON devono mostrare il tasto "Compara"
var isNewProduct = itema.product_type && (itema.product_type === 'smartwatch' || itema.product_type === 'tablet' || itema.product_type === 'laptop');
// Usa il link diretto se disponibile (per nuovi prodotti), altrimenti usa il redirect
var productLink = itema.link ? itema.link : '/new_files/redirs/model.php?id=' + itema.id;
// Gestisci l'immagine: per nuovi prodotti usa tag img diretto, altrimenti background CSS
var imageTag = '';
if (isNewProduct && itema.image_url) {
// Nuovo prodotto: usa tag img diretto
var imageUrl = itema.image_url;
if (imageUrl.indexOf('?') === -1) {
imageUrl += '?h=40&fit=clip';
} else {
imageUrl += '&h=40&fit=clip';
}
imageTag = '';
} else {
// Smartphone: usa background CSS
imageTag = '';
}
b += '
';
b += 'Video Review';
b += "";
} else {
b += '';
}
if (itema.price && itema.price != 1) {
var priceHref = (typeof itema.link === 'string' && itema.link)
? (conf_site_url + itema.link.replace(/schede-tecniche/g, 'prezzi'))
: (conf_site_url + '/new_files/redirs/price.php?id=' + itema.id);
b += '€' + itema.price + '';
} else {
b += '';
}
b += "
";
}
} else if (this.layer_type === "short") {
var b = "";
for (var c = 0; c < a.length; c++) {
if (c == AUTOCOMPLETE_MAX_LINES) break;
var itema = a[c];
// Usa il link diretto se disponibile (per nuovi prodotti), altrimenti usa il redirect
var productLink = itema.link ? itema.link : '/new_files/redirs/model.php?id=' + itema.id;
b += '
",
pagerEvent: pager_type_event
});
the_slider.hover(function () {
$(this).addClass('slider_hover');
}, function () {
$(this).removeClass('slider_hover');
});
the_slider.find('.cycle-prev,.cycle-next,.bar_thumb').hover(
function () {
the_slideshow.cycle('pause');
},
function () {
the_slideshow.cycle('resume');
});
if (reveal == true) {
// ###########################################
// INICIO EFECTO BOTON NEXT Y PREV
// para el efecto hover de los botones next y prev, es lo mejor que pude hacer
// hay algunas fallitas pero son inotables
ancho_total = w;
_offset_sides = 80;
the_slider.find('.cycle-prev').hover(
function () {
// console.log("probando");
// the_slideshow.cycle('pause');
actual = the_slideshow.find('.cycle-slide-active');
previo = actual.prev();
// previo=actual.prev().not('.cycle-sentinel');
// if(previo.length > 0){
// previo.css('left','-100%');
previo.css({ 'left': -ancho_total, 'display': 'block', 'z-index': '100' });
// actual.css('left','6%');
previo.animate({ left: (-ancho_total + _offset_sides) }, { queue: false, duration: 260 });
actual.animate({ left: _offset_sides }, { queue: false, duration: 260 });
// }
}, function () {
// console.log("fuera");
// console.log(previo);
if (!previo.hasClass('cycle-slide-active')) {
previo.animate({ left: -ancho_total }, {
queue: false,
duration: 200,
complete: function () {
// console.log("su lugar");
$(this).css({ 'left': '0', 'display': 'none', 'z-index': 92 });
}
});
actual.animate({
left: "0"
}, { queue: false, duration: 200 });
}
// actual.css('z-index','100');
// the_slideshow.cycle('resume');
}
);
the_slider.find('.cycle-next').hover(
function () {
// the_slideshow.cycle('pause');
actual = the_slideshow.find('.cycle-slide-active');
siguiente = actual.next();
// console.log("probando");
// previo.css('left','-100%');
siguiente.css({ 'left': ancho_total, 'display': 'block', 'z-index': '100' });
// actual.css('left','6%');
siguiente.animate({ left: (ancho_total - _offset_sides) }, { queue: false, duration: 260 });
actual.animate({ left: -_offset_sides }, { queue: false, duration: 260 });
}, function () {
// console.log("fuera");
// console.log(siguiente);
if (!siguiente.hasClass('cycle-slide-active')) {
siguiente.animate({ left: ancho_total }, {
queue: false,
duration: 200,
complete: function () {
// console.log("su lugar");
$(this).css({ 'left': '0', 'display': 'none', 'z-index': 92 });
}
});
actual.animate({
left: "0"
}, { queue: false, duration: 200 });
}
// actual.css('z-index','100');
// the_slideshow.cycle('resume');
}
);
// ############################################33
// Fin de los Efectos boton next y prev
}
// console.log("fin llamada make_slider");
return the_slideshow;
}
/**
* Funcion que vincula un grupo de anchors ( tags a) , y carga su contenido en un target
* @param {[String]} wich_group [aqui va el identificador del grupo que sale del data-group de los anchors]
* @param {[String]} target_load [identificador del layer donde se va cargar el contenido de los anchor]
* @param {[String]} active_class [nombre de la clase que se va usar cuando el anchor este activo]
* @param {[String]} event_type [nombre el evento que resopnden los anchors, puede ser 'mouseenter' o click]
*/
var data_tab_global = null;
var id_tab_news_active = null;
function link_tabs (wich_group, target_load, active_class, event_type, calltype) {
// the_links=$("a[data-group='"+wich_group+"']").not(".hide");
the_links = $("a[data-group='" + wich_group + "']");
// holder_left=the_links.eq(0).parents('.tiles_holder.left');
if (typeof target_load == 'object') {
for (var i = 0; i < target_load.length; i++) {
if ($("#" + target_load[i]).length == 0) {
// console.log("no existe el div:" + target_load[i]);
return;
}
}
if ((calltype == 'homenews' || calltype == 'homenewsbig') && (data_tab_global == null && $(".tiles_holder.left").length)) {
link_activo = $(".tiles_holder.left").eq(0).find('.label_links a.active');
// console.log( $(the_link[0]).attr('id') );
if (link_activo.length) {
id_cat = link_activo.attr('id').split('_')[1];
id_tab_news_active = id_cat;
// $.cookie('id_tab_news_active',id_tab_news_active);
// id_cat=the_links.eq(0).attr('id').split('_')[1];
data = "type=" + calltype + "&tab=" + id_cat + "&divs=" + target_load.join();
data_tab_global = "type=" + calltype + "&tab=" + id_cat;
// console.log('fsadf');
}
}
the_links.on(event_type, {
'active_class': active_class,
'target_load': target_load,
'calltype': calltype
}, loadNotizes);
}
else
the_links.on(event_type, {
'active_class': active_class,
'target_load': target_load,
'calltype': calltype
}, switchTab);
}
var paginas_consultadas = [];
function loadNotizes (e) {
e.preventDefault();
t = $(this);
$tiles_holder_right = t.parents('.tiles_holder.right.responsive');
//cuando se hace click en un tab eliminamos el preload (result_page) para que la proxima pagina no pertenezca al
// tab anterior
result_page = null;
if (t.hasClass(e.data.active_class) == false) {
t.addClass(e.data.active_class).siblings().removeClass(e.data.active_class);
if (typeof(cblog) == "undefined") cblog = "";
base_url = "/new_files/ajax/generic.php?ctp=superpippo&cblog=" + cblog;
id_cat = t.attr('id').split('_')[1];
data = "type=" + e.data.calltype + "&tab=" + id_cat + "&divs=" + e.data.target_load.join();
d_extra = t.attr('data-extra');
if (d_extra) {
data += "&" + d_extra;
}
if (e.data.calltype == 'homenews' || e.data.calltype == 'homenewsbig') {
id_tab_news_active = id_cat;
// $.cookie('id_tab_news_active',id_tab_news_active);
data_tab_global = "type=" + e.data.calltype + "&tab=" + id_cat;
window.location.hash = "?t=" + id_tab_news_active + "&b=" + zonas_loading_news.length;
}
var zonas_loading_pages = e.data.target_load;
var $zona_loading_page;
for (var i = 0; i < zonas_loading_pages.length; i++) {
$zona_loading_page = $("#" + zonas_loading_pages[i]);
// var alto_actual= $zona_loading_page.outerHeight();
// solo para las columnas derechas
// $zona_loading_page.empty().addClass('loading_indicator');
$zona_loading_page.addClass('loading_indicator');
// if($tiles_holder_right.length)
// $zona_loading_page.css('height',alto_actual);
}
var notfoundcachepage = true;
var key, $tkey;
if (paginas_consultadas.length) {
for (var t = 0, len = paginas_consultadas.length; t < len; t++) {
var pag_consul_temp = paginas_consultadas[t];
if (id_cat == pag_consul_temp.tab) {
console.log('iguales');
var llaves_temp = Object.keys(pag_consul_temp.datos);
var ultimo = llaves_temp[llaves_temp.length - 1];
if (ultimo == 'load_more_url')
llaves_temp.pop();
if (JSON.stringify(zonas_loading_news) == JSON.stringify(llaves_temp)) {
console.log('cantidad de zonas iguales');
for (var i = 0, len2 = llaves_temp.length; i < len2; i++) {
key = llaves_temp[i];
var new_content = pag_consul_temp.datos[key];
$tkey = $("#" + key);
if ($tkey.css('position') == 'static') {
$tkey.empty().append(new_content).removeClass('loading_indicator').css('style', 'relative');
} else {
$tkey.empty().append(new_content).removeClass('loading_indicator');
}
// $tkey.empty().append(new_content).removeClass('loading_indicator').removeAttr('style');
var temp_img_founded = $tkey.find('img[data-src]');
if (temp_img_founded.length)
temp_img_founded.unveil();
}
notfoundcachepage = false;
break;
}
}
}
}
if (notfoundcachepage) {
$.get(base_url, data, function (response) {
var check_insert_new = true;
if (paginas_consultadas.length)
for (var i = 0, len2 = paginas_consultadas.length; i < len2; i++) {
var tmp_pages = Object.keys(paginas_consultadas[i].datos);
var ultimo = tmp_pages[tmp_pages.length - 1];
if (ultimo == 'load_more_url')
tmp_pages.pop();
if (paginas_consultadas[i].tab == id_cat) {
console.log("i" + i);
if (JSON.stringify(zonas_loading_news) == JSON.stringify(tmp_pages)) {
check_insert_new = false;
} else {
paginas_consultadas.splice(i, 1);
}
break;
}
}
if (check_insert_new)
paginas_consultadas.push({ tab: id_cat, datos: response });
// localStorage.setItem('pag_consul',JSON.stringify(paginas_consultadas));
llaves = Object.keys(response);
console.log("Existen " + (llaves.length - 1) + " resultados para los ids: " + llaves.join(', '));
console.log("En el array de posiciones estan: " + e.data.target_load.join(', '));
if (zonas_loading_pages.length != (llaves.length - 1)) {
console.log("####### Existen divs que no tuvieron resultado y se quedaron cargando....####")
}
if (response.load_more_url) {
console.log("se cambio el href del load more por :" + response.load_more_url);
$(".more_content .btn_more").attr('href', response.load_more_url);
}
for (var t = 0, len = llaves.length; t < len; t++) {
key = llaves[t];
if (key != 'load_more_url') {
var new_content = response[key];
$tkey = $("#" + key);
if ($tkey.css('position') == 'static') {
$tkey.empty().append(new_content).removeClass('loading_indicator').css('style', 'relative');
} else {
$tkey.empty().append(new_content).removeClass('loading_indicator');
}
var temp_img_founded = $tkey.find('img[data-src]');
if (temp_img_founded.length)
temp_img_founded.unveil();
}
}
if (typeof(_gaq) != "undefined") {
//_gaq.push(['_trackEvent', 'TabClick', 'Open', document.title]);
}
}, 'json');
}
}
}
function switchTab (e) {
e.preventDefault();
t = $(this);
if (t.hasClass(e.data.active_class) == false) {
t.addClass(e.data.active_class).siblings().removeClass(e.data.active_class);
if (t.attr('data-content')) { // recoge del html, ya sc vuelve a hacer la peticion ajax nuevamente
hidden_div = t.attr('data-content');
if (!$("#" + hidden_div).length) {
console.log("no existe el layer a cargar :" + hidden_div);
} else {
contenido = $("#" + hidden_div).html();
$("#" + e.data.target_load).html(contenido);
}
} else { // si no tiene el data-content significa que va cargar la url del href por ajax
url = t.attr('href');
data = {};
$("#" + e.data.target_load).html("
");
$.get(url, data, function (response) {
$("#" + e.data.target_load).html(response).hide().fadeIn('slow');
id = t.index() + "_" + t.attr('data-group');
//aqui guarda el resultado en el dom, la siguiente vez solo recupera del dom y no hace la peticion
// con ajax
new_hidden_layer = "
" + response + "
";
$(new_hidden_layer).appendTo('body').hide();
t.attr('data-content', id);
});
}
}
}
var temp = "";
var result_page = null;
var urls_cached = [];
/**
* Funcion que carga una pagina en un div mediante ajax o de una variable si ya tiene valor
* @param {[String]} url [ La url que se va cargar, debe devolver html ]
* @param {[String]} id_target [ ID del div donde se va cargar ]
* @param {[Object]} link [ El link 'a' que lanza el evento, para que pueda ser escondigo ]
* @return {[Boolean]} [ Retona False para que no termine la accion del link]
*/
var ajuste_animacion = false;
function load_next_page (url, id_target, link, e) {
// console.log('numpages_loades:'+num_pages_loaded);
if (MAX_NUM_PAGES > 2) {
if (num_pages_loaded >= (MAX_NUM_PAGES - 2)) {
// console.log('llego al tope');
return;
}
} else {
throw "Error: No esta configurado MAX_NUM_PAGES correctamente";
}
if (link != 'fix_sidebar') {
elv = e || event;
if (elv.button == 1) {
return true;
}
}
var $div_target = $('#' + id_target);
var $css3_loading = $(css3_loading);
var num_page = url.split('=')[1];
if (typeof(cblog) == "undefined") cblog = "";
if (url.indexOf('cblog') < 0)
url += '&cblog=' + cblog;
if (result_page != undefined && result_page != null) {
ajuste_animacion = true;
if (link != 'fix_sidebar')
$(link).parent('.more_content').slideUp(function () {
$(this).remove()
});
else {
// borrar_botones_more();
}
$div_target.append(result_page); // sin animacion
borrar_botones_more();
add_target_load_tile(result_page);
if (num_page >= 4 && $(window).width() >= 1016 && link != 'fix_sidebar') {
// $(".threcolums").last().css('background','red');
// var new_top=$(".threcolums").last().offset().top;
$('.movingbox').css({ 'top': 0, 'position': 'fixed' });
}
// hide_banners();
// buildZonasPositions();
result_page = null;
limitNextPage = $(document).height() - offset_next_page;
bandLoadPage = false;
num_pages_loaded++;
$btn_mores = $('.btn_more');
} else {
ajuste_animacion = true;
$css3_loading.css('margin', '20px auto').appendTo($div_target);
if (data_tab_global) {
url += "&" + data_tab_global + "";
}
if (link != 'fix_sidebar')
$(link).parent('.more_content').slideUp(function () {
$(this).remove()
});
console.log('sin Cache, realizando consulta: ' + url);
$.get(url, function (response) {
$css3_loading.fadeOut('slow', function () {
$(this).remove();
$div_target.append(response);
$div_target.children("section").last().find("img[data-src]").unveil(100);
add_target_load_tile(response);
if (num_page >= 4 && link != 'fix_sidebar') {
$('.movingbox').css({ 'top': 0, 'position': 'fixed' });
}
if (link == 'fix_sidebar') {
borrar_botones_more();
}
limitNextPage = $(document).height() - offset_next_page;
bandLoadPage = false;
num_pages_loaded++;
});
urls_cached.push(url);
});
}
// hide_banners();
//_gaq.push(['_trackEvent', 'MoreClick', 'Open', document.title]);
return false;
}
// esta funcion agrega el nuevo id al array donde se cargan las noticias del 'HomePage'
// el array zonas_loading_news esta en homepage
// actualizando para que funcione ne todas las paginas ...
function add_target_load_tile (the_new_page) {
new_target_id = $(the_new_page).find('.loader').attr('id');
if (new_target_id) {
zonas_loading_news.push(new_target_id);
// $.cookie('zonas_loading_news',zonas_loading_news);
window.location.hash = "?t=" + id_tab_news_active + "&b=" + zonas_loading_news.length;
}
else
console.log("no existe un id en la nueva pagina que se cargo");
}
/**
* [Funcion que precarga la url y lo guarda en una variable, toma como limite de top el id_prefetch]
* @param {[String]} url [ La url que se va cargar, debe devolver html ]
* @param {[String]} id_prefetch [ ID del div que va servir de top, a partir de donde se va a precargar ]
*/
function preload_next_page (url, id_prefetch) {
if (loading_from_hash == true) { // si se esta cargando desde el hash ya no se necesita el preload
console.log('no se realizo la precarga por que sigue cargando del hash');
return;
}
var sw = true;
if (typeof(cblog) == "undefined") cblog = "";
if (url.indexOf('cblog') < 0)
url += '&cblog=' + cblog;
if (!id_prefetch) {
console.log("PRELOADING PAGE, with url sin lIMITE:");
if (data_tab_global) {
// console.log('adjuntando datos');
url += "&" + data_tab_global + "";
}
console.log(url);
if (urls_cached.indexOf(url) < 0 && sw) {
sw = false;
preload_next(url);
}
} else {
// console.log('llamada preload_next_page');
var limit_id_top = $('#' + id_prefetch).offset().top;
$(window).on('scroll', function () {
if (($(window).scrollTop() >= limit_id_top ) && (result_page == null) && ( urls_cached.indexOf(url) < 0 ) && sw) {
//if (gtag !== undefined) gtag('event', 'HalfPage', {'page_title': document.title });
console.log("PRELOADING PAGE, with url:");
if (data_tab_global && url.indexOf(data_tab_global) == -1) {
url += "&" + data_tab_global + "";
}
console.log(url);
preload_next(url);
}
});
}
}
function preload_next (url) {
urls_cached.push(url);
$.get(url, function (response) {
var $temp_response = $(response);
var len = $temp_response.find('img[data-src]').length;
var $tempimg;
for (var i = len - 1; i >= 0; i--) {
$tempimg = $temp_response.find('img[data-src]').eq(i);
$tempimg.attr('src', $tempimg.attr('data-src'));
$tempimg.removeAttr('data-src');
}
result_page = $temp_response.get();
const event = new CustomEvent("hpSectionLoaded");
document.dispatchEvent(event);
});
}
function loadAsyncScripts () {
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script');
dsq.type = 'text/javascript';
dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('sc')[0]).appendChild(dsq);
})();
}
function loadSocialButtons () {
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/it_IT/all.js#xfbml=1&appId=236665699772514";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
(function () {
var po = document.createElement('script');
po.type = 'text/javascript';
po.async = true;
po.src = 'https://apis.google.com/js/platform.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'twitter-wjs'));
}
function openpopup (url, width, height, name) {
window.open(url, name, 'width=' + width + ', height=' + height + ', scrollbars=yes');
}
function loadScriptsOffset (keys, offset) {
var offset = offset || $(document).height() / 2;
var keys = keys || [];
var sw = 0;
// console.log(offset);
$(window).on('scroll', function () {
// console.log($(window).scrollTop());
if ($(window).scrollTop() >= offset && sw == 0) {
sw = 1;
console.log("pasa limite");
for (var i = 0; i < keys.length; i++) {
// console.log("################## ejecutando "+ keys[i]+" () ");
keys[i]();
}
}
});
}
function skincompatibility () {
trackSkin();
var st1, st2, st3, st4;
st1 = setTimeout(function () {
removeSideBars();
clearTimeout(st1);
st1 = null;
}, 50);
st2 = setTimeout(function () {
removeSideBars();
clearTimeout(st2);
st2 = null;
}, 200);
st3 = setTimeout(function () {
removeSideBars();
clearTimeout(st3);
st3 = null;
}, 1000);
st4 = setTimeout(function () {
removeSideBars();
clearTimeout(st4);
st4 = null;
}, 2000);
}
function checkIfPreview () {
if (getParameterByName("google_preview") == null && getParameterByName("creativeId") == null && getParameterByName("gdfp_req") == null) {
return false;
}
console.log("dfp preview");
return true;
}
function trackMastehad () {
console.log("Track Mastehad");
if (!checkIfPreview()) {
var numMastheads = readCookie("mh1");
if (numMastheads <= 0 || numMastheads == null) {
numMastheads = 0;
}
numMastheads++;
createCookie("mh1", numMastheads, 3600*12, ".hdblog.it");
if (typeof(_gaq) != "undefined") {
//_gaq.push(['_trackEvent', 'RichMediaAdv', 'Masthead', numMastheads.toString()]);
}
}
}
function trackSkin () {
console.log("Track Skin");
if (!checkIfPreview()) {
var numSkins = readCookie("skn1");
if (numSkins <= 0 || numSkins == null) {
numSkins = 0;
}
numSkins++;
createCookie("skn1", numSkins, 3600*12, ".hdblog.it");
if (typeof(_gaq) != "undefined") {
//_gaq.push(['_trackEvent', 'RichMediaAdv', 'Skin', numSkins.toString()]);
}
}
}
function trackOverlay () {
console.log("Track Overlay");
if (!checkIfPreview()) {
createCookie("ovrl", 1, 0, ".hdblog.it");
createCookie("ovrl2", 1, 3600*12, ".hdblog.it");
} else {
console.log("Track Overlay: no action, dfp preview");
}
}
function displayOverlay () {
var rndNum = getRandomInt(1, 2);
if (readCookie("ovrl2") == 1 && !checkIfPreview()) {
return false;
}
if (rndNum != 1) {
return false;
}
return true;
}
function displayRichMedia () {
if (readCookie("ovrl") == 1 && !checkIfPreview()) {
if (typeof(_gaq) != "undefined") {
if (typeof this.logged == "undefined") {
this.logged = true;
//if (gtag !== undefined) gtag('event', 'richmedia_disabled', {'page_title': document.title });
}
}
return false;
}
return true;
}
function removeSideBars () {
var contenedores = document.querySelectorAll('.container');
for (var i = 0; i < contenedores.length; i++) {
if (contenedores[i].classList.contains('bordes_container')) {
// console.log(contenedores[i].getAttribute('id'));
contenedores[i].classList.remove('bordes_container');
}
}
}
function make_counter (tipo, direccion, url, futureDate, clase) {
/*
console.log("============================");
console.log('currentDate:');
console.log(currentDate);
console.log('futureDate:');
console.log(futureDate);*/
if (!futureDate) return;
var start = true;
if (currentDate > futureDate) {
console.log('The Date ( ' + futureDate.toLocaleString() + ' ) is less than the Current (' + currentDate.toLocaleString() + '), please change it.');
futureDate = currentDate;
start = false;
// return;
}
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
var $countd = $("#countd");
var custom_position_counter = function (url, direccion, tipo) {
// console.log('la url:'+url);
if (url)
$countd.wrap("");
var prop = { 'position': 'absolute', 'z-index': '102' }
if (clase)
$countd.addClass(clase);
else
console.log('se aplica el estilo por defecto');
// if(tipo=='timeto')
// prop['max-width']='480px';
if (clase == "white_digits") {
prop.margin = '28px 10px 10px';
} else {
prop.margin = '10px';
}
switch (direccion) {
case 'topleft':
prop.left = '18px';
prop.top = '0px';
if (tipo == 'flipclock')
prop.top = '10px';
$countd.css(prop);
break;
case 'topright':
prop.right = '18px';
prop.top = '0px';
if (tipo == 'flipclock')
prop.top = '10px';
$countd.css(prop);
break;
case 'bottomleft':
prop.left = '18px';
prop.bottom = '0px';
$countd.css(prop);
break;
case 'bottomright':
prop.right = '18px';
prop.bottom = '0px';
$countd.css(prop);
break;
default:
prop.left = '0';
prop.right = '0';
prop.top = '0';
prop.bottom = '0';
prop.margin = 'auto auto';
if (tipo == 'flipclock') {
prop.width = 438;
prop.height = 63;
if (clase == 'white_digits') {
prop.width = "340px";
}
if (clase == 'black_background') {
prop.width = 456;
prop.height = 66;
}
}
if (tipo == 'timeto')
prop.height = '85px';
$countd.css(prop);
break;
}
};
var clock;
switch (tipo) {
case 'flipclock':
clock = $countd.FlipClock(Math.round(diff), {
countdown: true,
clockFace: 'DailyCounter',
language: 'it'
// autoStart: start
});
custom_position_counter(url, direccion, tipo);
break;
case 'timeto':
var secondes = (diff == 0) ? 1 : diff;
clock = $countd.timeTo({
seconds: secondes,
// timeTo:futureDate,
displayDays: 2,
displayCaptions: true,
fontSize: 45,
captionSize: 11,
theme: 'white',
lang: 'it',
start: start
});
custom_position_counter(url, direccion, tipo);
break;
}
return clock;
}
global_alertboxname = "pricealertbox";
function getElementById (a) {
return document.getElementById(a)
}
function bestpriceover (a, b, c) {
"" != a && (objPrice = document.getElementById(a));
"" != b && (objPrice2 = document.getElementById(b));
null != objPrice && ("" != a && (objPrice.style.backgroundColor = "#" + c), "" != b && (objPrice2.style.backgroundColor = "#" + c))
}
function bestpriceout (a, b) {
"" != a && (objPrice = document.getElementById(a));
"" != b && (objPrice2 = document.getElementById(b));
null != objPrice && ("" != a && (objPrice.style.backgroundColor = "#fff"), "" != b && (objPrice2.style.backgroundColor = "#fff"))
}
function submitpricealert2 (a, b) {
frmprice = null == a ? document.frmalertprice : document.forms[a];
null != b && (global_alertboxname = b);
if (null != frmprice) {
amail = frmprice.alertmail.value;
aid = frmprice.id.value;
str_query_value = "";
if ("dbmodello_alert" == b) {
valore = frmprice.alertprice.options[frmprice.alertprice.selectedIndex].value;
if ("" == valore) return window.alert("Erro, Escolha seu pre\u00e7o."), !1;
str_query_value = "&valore=" + valore
}
if (null != amail && "" != amail && null != aid && "" != aid) {
var c = new Date,
f = getElementById(global_alertboxname);
httpAlertObj && null != f && (httpAlertObj.open("get", "/new_files/ajax/pricealert.asp?action=insert&modelid=" + aid + "&email=" + amail + str_query_value + "&k=" + c.getTime()), httpAlertObj.onreadystatechange = handleResponse_alert, httpAlertObj.send(null), objLoadingAlert = document.getElementById("divLoadingAlert"), null == objLoadingAlert && (objLoadingAlert = document.createElement("div"), objLoadingAlert.setAttribute("id", "divLoadingAlert"), f.appendChild(objLoadingAlert)), objLoadingAlert.style.display = "block", alert_flag_loading =
setTimeout("alert_removeLoading();", 2E4));
return !1
}
}
window.alert("Erro, e-mail não válida.");
return !1
}
function handleResponse_alert () {
if (4 == httpAlertObj.readyState) {
var a = httpAlertObj.responseText;
clearTimeout(alert_flag_loading);
message = "BHO" == a ? "Si è verificato un errore. Perfavore riprova più tardi." : a;
alert_flag_reply = setTimeout("alert_reply('" + message + "')", 500)
}
}
function alert_removeLoading () {
clearTimeout(alert_flag_loading);
objLoadingAlert = document.getElementById("divLoadingAlert");
null != objLoadingAlert && (objLoadingAlert.style.display = "none")
}
function alert_removeReply () {
clearTimeout(alert_flag_removeReply);
objReplyAlert = document.getElementById("divReplyAlert");
var a = getElementById("pricealertcontent");
null != a && (a.style.display = "block");
null != objReplyAlert && (objReplyAlert.style.display = "none")
}
function alert_reply (a) {
clearTimeout(alert_flag_loading);
clearTimeout(alert_flag_reply);
var b = getElementById("pricealertcontent"),
c = getElementById(global_alertboxname);
null != c && null != b && (b.style.display = "none", objReplyAlert = document.getElementById("divReplyAlert"), null == objReplyAlert && (objReplyAlert = document.createElement("div"), objReplyAlert.setAttribute("id", "divReplyAlert"), c.appendChild(objReplyAlert)), objReplyAlert.innerHTML = a + '[Chiudi]', objReplyAlert.style.display =
"block", alert_flag_removeReply = setTimeout("alert_removeReply()", 2E4));
alert_removeLoading()
}
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getParameterByName (name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
if (typeof Banner === 'undefined') {
function Banner(id, arr) {
}
}
if (typeof buildZonasPositions === 'undefined') {
function buildZonasPositions() {}
}
var thebanners = [];
function config_banners(thebanners) {}
function isInteger (value) {
return (value == parseInt(value));
}
function create_fotos_compare (obj) {
if (!obj.id)
return;
var data = obj.data || [];
var $el = $("#" + obj.id);
var w = obj.w || 700;
var h = obj.h || 400;
var show_controls = true;
if (obj.controls === false) {
show_controls = false;
}
var c = 0;
$.preloadImages = function (images) {
// console.log(images);
for (var i = 0; i < images.length; i++) {
var $theimg = $("");
$theimg.attr("src", images[i]);
$theimg.load(function () {
c++;
});
}
};
// preloadImg('http://yoururl/to/the/picture.jpg');
var listas_repetidas = (function () {
var repeated = { images: [], controls: [] };
var all_images = [];
for (var i = 0; i < data.length; i++) {
var obj = data[i];
all_images.push(obj.img);
if (obj.iconclass) {
repeated.images.push('
');
}
}
// console.log(all_images.join(' ,'));
// $.preloadImages(all_images);
return repeated;
})();
var html = '';
html += ' ';
html += "";
html += listas_repetidas.images.join('\n');
html += "";
if (show_controls) {
html += "";
html += listas_repetidas.controls.join('\n');
html += "";
}
$el.css({ width: w, height: h });
// $el.html('
Loading...
');
$el.html(html);
/* var myinter=setInterval(function(){
if(c===data.length) {
clearInterval(myinter);
$el.html(html).hide();*/
make_magic_gallery($el, w, h, data);
/* }
},100);*/
}
function make_magic_gallery ($el, w, h, data) {
var photo_compare_jq = $el;
photo_compare_jq.fadeIn();
/*
photo_compare_jq.animate({
opacity:1
});
*/
var $images_li = photo_compare_jq.find('ol.images li');
var $controls_li = photo_compare_jq.find('ol.controls li');
var width_li = w / data.length;
if (!isInteger(width_li)) {
console.log($el.attr('id') + ' === no es exacto');
if ((width_li % 1) > (0.5)) {
width_li = Math.ceil(width_li);
} else {
width_li = Math.floor(width_li);
}
photo_compare_jq.width(width_li * data.length);
}
$images_li.css('width', width_li);
$controls_li.css('width', width_li);
$images_li.css('height', h);
$images_li.find('div').css('width', width_li - 1);
$images_li.on('click', function (e) {
if (photo_compare_jq.hasClass('has_selected'))
return;
/* console.log('target 2');
console.log(e.target);*/
var name = $(e.target).parents('li')[0].className.replace('hover', '').replace('selected', '').replace('collapsing', '').trim();
photo_compare_jq.addClass('noanim has_selected');
var $div_inside = $images_li.filter('.' + name).find('div');
// console.log($div_inside);
$div_inside.css({ 'left': $div_inside.position().left + 'px' });
setTimeout(function () {
photo_compare_jq.removeClass('noanim');
photo_compare_jq.find('li.' + name).addClass('selected');
$div_inside.css('width', '100%');
}, 150);
});
$controls_li.on('click', function (e) {
/* console.log('target:');
console.log(e.target);*/
var name = e.target.className.replace('hover', '').replace('selected', '').trim();
// console.log(name);
if (!photo_compare_jq.hasClass('has_selected')) {
// photo_compare_jq.find('ol.images li.'+name).trigger('click');
photo_compare_jq.find('ol.images li.' + name + ' div img').trigger('click');
} else if ($(e.target).hasClass('selected')) {
photo_compare_jq.find('.collapse').trigger('click');
} else {
//photo_compare_jq.find('ol.images li').removeClass('hover');
photo_compare_jq.addClass('noanim');
photo_compare_jq.find('.images li.' + name + ' div').css({ 'left': photo_compare_jq.find('.images li.' + name).position().left + 'px' });
photo_compare_jq.find('ol.controls li.selected').removeClass('selected');
var hiding = photo_compare_jq.find('ol.images li.selected');
photo_compare_jq.find('ol.images li.selected').addClass('disappearing');
photo_compare_jq.find('li.' + name).addClass('selected');
photo_compare_jq.find('li.' + name).find('div').css('width', '100%');
setTimeout(function () {
photo_compare_jq.removeClass('noanim');
}, 500 + 150);
setTimeout(function () {
hiding.find('div').css('width', width_li - 1);
hiding.removeClass('disappearing').removeClass('selected');
}, 500);
}
});
$controls_li.on('mouseover', function (e) {
if (photo_compare_jq.hasClass('has_selected'))
return;
var name = e.target.className;
photo_compare_jq.find('ol.images li.' + name).addClass('hover');
});
$controls_li.on('mouseout', function (e) {
if (photo_compare_jq.hasClass('has_selected'))
return;
var name = e.target.className;
photo_compare_jq.find('ol.images li.' + name).removeClass('hover');
});
photo_compare_jq.find('.collapse').on('click', function (e) {
photo_compare_jq.find('ol.images li').removeClass('hover');
photo_compare_jq.removeClass('has_selected');
photo_compare_jq.find('ol.images li.selected').addClass('collapsing');
photo_compare_jq.find('ol.images li.selected').find('div').css('width', width_li - 1);
photo_compare_jq.find('li.selected').removeClass('selected');
setTimeout(function () {
photo_compare_jq.find('li').removeClass('collapsing');
}, 250);
});
photo_compare_jq.find('.zoom').on('click', function (ev) {
console.log('click en zoom');
var path_img = $(this).parent('.photo_compare').find('li.selected').find('img').attr('data-src2');
window.open(path_img);
});
}
/**
* Sobreescribe la funcion alert para mostrar algo mas estilizado
*
* @param message
* @param onOkHandler es un callback que se ejecuta cuando se hace click en el boton ok|aceptar|accettare
*/
function newalert(message, onOkHandler) {
if (newalert.queue === undefined) {
newalert.queue = [];
newalert.old = alert;
}
if (newalert.isWorking) {
newalert.queue.push(message);
return;
}
newalert.isWorking = true;
var html = '
[message]
';
var html$ = $(html.replace('[message]', message));
html$.find('button').click(function(e){
e.preventDefault();
e.stopPropagation();
if ($.isFunction(onOkHandler)) {
onOkHandler();
}
html$.animate({
opacity: 0
}, {
duration: 'fast',
complete: function(){
html$.remove();
newalert.isWorking = false;
if (newalert.queue.length > 0) {
newalert(newalert.queue.shift());
}
}
});
});
html$.appendTo('body');
};
// window.alert = newalert;
/*
* Session functions
*/
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+";domain=.hdblog.it;path=/";
}
function readCookie (name) {
cookie_name = name + '=';
cookie_length = document.cookie.length;
cookie_begin = 0;
while (cookie_begin < cookie_length) {
value_begin = cookie_begin + cookie_name.length;
if (document.cookie.substring(cookie_begin, value_begin) == cookie_name) {
var value_end = document.cookie.indexOf(';', value_begin);
if (value_end == -1) {
value_end = cookie_length;
}
return unescape(document.cookie.substring(value_begin, value_end));
}
cookie_begin = document.cookie.indexOf(' ', cookie_begin) + 1;
if (cookie_begin == 0) {
break;
}
}
return null;
}
function deleteCookie (name) {
document.cookie = name + '=' + ';expires=Thu, 01-Jan-70 00:00:01 GMT' + ';path=/;domain=.hdblog.it';
}
function setCookie (name, value, expires) {
document.cookie = name + '=' + escape(value) + ';path=/' + (typeof expires != 'undefined' ? ';domain=.hdblog.it;expires=' + expires.toGMTString() : '');
}
/**
* Created by j on 9/10/15.
*/
_forEach = function (arr, callback) {
for (var i = 0; i < arr.length; i++) {
var r = callback.call(arr[i], i);
if (r === false) return;
}
};
recaptchaCallback = function () {
if (typeof(grecaptcha) == "undefined") {
return;
}
var rcs = document.querySelectorAll('.g-recaptcha:not(.setted)');
_forEach(rcs, function () {
var rc = this;
var recaptchaid = 'recaptcha' + document.querySelectorAll('.g-recaptcha.setted').length;
rc.setAttribute('id', recaptchaid);
var widgetId = grecaptcha.render(rc.getAttribute('id'), {
sitekey: rc.getAttribute('data-sitekey')
});
rc.className += ' setted';
rc.setAttribute('data-recaptcha-widget-id', widgetId);
});
};
window.get_global_interaction_event =
window.get_global_interaction_event || function () {
return 'click';
};
// price alert popup
(function ($) {
var defaults = {
type: 'ajax', // ajax, iframe
width: '90%',
height: 'auto',
price: null,
modelid: null
};
$.fn.priceAlertPopup = function () {
var body$ = $('body');
return this.each(function () {
var trigger$ = $(this);
if (!trigger$.attr('href')) {
return;
}
trigger$.on(get_global_interaction_event(), function (e) {
e.preventDefault();
e.stopPropagation();
if (trigger$.hasClass('triggered')) {
return false;
}
trigger$.addClass('triggered');
e.preventDefault();
e.stopPropagation();
var opts = {};
for (option in defaults) {
if (trigger$.attr('data-' + option)) {
opts[option] = trigger$.attr('data-' + option);
}
}
if (!trigger$.attr('href')) {
alert('no hay una url para cargar el popup');
return;
}
console.log('final options: ', opts);
var popupBody$ = $(
'
' +
'' +
'
' +
'' +
'
' +
'
'
);
var _closeHandler = function (e) {
e.preventDefault();
e.stopPropagation();
var target$ = $(this);
if (!target$.is('.fancybox-close') && !target$.is('.popup-bg')) {
return false;
}
trigger$.removeClass('triggered');
popupBody$.remove();
popupBody$ = [];
$(window).off('resize scroll', centerBody);
};
// para que se cierre el popup al hacer click en el boton de cerrar
popupBody$.find('.fancybox-close, .popup-bg').on(get_global_interaction_event(), _closeHandler);
var centerBody = function () {
// la version mobilelight establece una variable global llamada Mobile
// en esta version el scroll se hace con el body por eso hay que usar el
// scrollTop para centrar el popup
if (!window.Mobile && window.Zepto) { // mobile
popupBody$.find('.popup-wrapper').css('left', Math.floor($(window).width() - popupBody$.find('.popup-wrapper').width()) / 2);
popupBody$.find('.popup-wrapper').css('top', Math.floor($(window).height() - popupBody$.find('.popup-wrapper').height()) / 2);
} else {
popupBody$.find('.popup-wrapper').css('left', Math.floor($(window).width() - popupBody$.find('.popup-wrapper').width()) / 2);
popupBody$.find('.popup-wrapper').css('top', $(window).scrollTop() + Math.floor($(window).height() - popupBody$.find('.popup-wrapper').height()) / 2);
}
};
var ajaxURL = trigger$.attr('href');
if (ajaxURL.indexOf('?') != -1) {
ajaxURL += '&from_ajax=1';
} else {
ajaxURL += '?from_ajax=1';
}
$.ajax({
url: ajaxURL,
type: 'get',
success: function (response) {
body$.append(popupBody$);
popupBody$.find('.popup-wrapper').append(response);
centerBody();
}
});
$(window).on('resize scroll', centerBody);
/*
* esto es para revisar el height del contenido del popup
*/
setTimeout(function _() {
return; // quitar esto si se quiere que el popup se reposicione al cambiar el height
if (!_.lastHeight) {
_.lastHeight = popupBody$.find('.popup-wrapper').height();
}
if (popupBody$.length) {
if (window.Zepto) {
// esta linea hace que el cuadro de imagenes a seleccionar en el captcha se mantenga siempre en el top
popupBody$.next('div').css('top', $(window).scrollTop());
}
if (_.lastHeight != popupBody$.find('.popup-wrapper').height()) {
_.lastHeight = popupBody$.find('.popup-wrapper').height();
centerBody();
}
setTimeout(_, 100);
}
}, 0);
});
});
};
})($);
function subscribeUser (serviceWorkerRegistration) {
if (typeof serviceWorkerRegistration === "undefined") {
serviceWorkerRegistration = null;
}
var checkUserSubscription = function (reg) {
if (Notification.permission === 'denied') {
clearAppState();
return;
}
reg.pushManager.getSubscription().then(function(sub) {
if (sub === null) {
// Not subscribed
askPermission(reg);
} else {
// Subscribed
refreshSubscription(sub);
console.log('Subscription object: ', sub);
}
});
};
if (serviceWorkerRegistration === null) {
if ('serviceWorker' in navigator && 'PushManager' in window) {
navigator.serviceWorker.ready.then(function (reg) {
checkUserSubscription(reg);
});
}
return;
}
checkUserSubscription(serviceWorkerRegistration);
}
function urlB64ToUint8Array(base64String) {
var padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
var rawData = window.atob(base64);
var outputArray = new Uint8Array(rawData.length);
for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function askPermission (serviceWorkerRegistration) {
if (typeof serviceWorkerRegistration === "undefined") {
serviceWorkerRegistration = null;
}
var ask = function (reg) {
reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlB64ToUint8Array('BAK_30eg61k8QN5JrNgwKGSsqCRBYbvlYJWuPZkPs0G6lnAPL__fnCO169kUnNPU7uiLClIg7DVPW5L6vEMGjk0')
}).then(function(sub) {
console.log('Endpoint URL: ', sub.endpoint);
submitSubscription(sub);
}).catch(function(e) {
if (Notification.permission === 'denied') {
console.warn('Permission for notifications was denied');
createCookie('end_point', 'denied', 365 * 10);
} else {
console.error('Unable to subscribe to push', e);
}
});
};
if (serviceWorkerRegistration === null) {
if ('serviceWorker' in navigator && 'PushManager' in window) {
navigator.serviceWorker.ready.then(function (reg) {
ask(reg);
});
}
return;
}
ask(serviceWorkerRegistration);
}
function subscribeSafari (pushn_safari_web_push_id, pushn_safari_web_service_url) {
var permissionData = window.safari.pushNotification.permission(pushn_safari_web_push_id);
var subscribeCallback = function (permissionData) {
if (permissionData.permission === 'granted') {
console.log('Device Token: ', permissionData.deviceToken);
submitSubscription(permissionData);
}
};
var uid = "0";
if (window.userid) {
uid = window.userid + "";
}
if (permissionData.permission === 'default') {
window.safari.pushNotification.requestPermission(
pushn_safari_web_service_url, // The web service URL.
pushn_safari_web_push_id, // The Website Push ID.
{ user_id: uid }, // Data that you choose to send to your server to help you identify the user.
subscribeCallback // The callback function.
);
} else if (permissionData.permission === 'denied') {
console.log('Push notification permission denied');
clearAppState();
} else if (permissionData.permission === 'granted') {
console.log('Device Token: ', permissionData.deviceToken);
refreshSubscription(permissionData);
} else {
console.log('Safari browser is not subscribed ' + permissionData);
}
}
function submitSubscription (subscription) {
updateAppState (subscription);
updateSubscriptionOnServer (subscription);
}
function refreshSubscription (subscription) {
var appState = getAppState();
var userIdentifier = window.userid;
if (isSafari && window.userid) {
userIdentifier = str_pad(window.userid, 26, 0);
}
var contentToTrack = getContentToTrack (),
needSubmit = false;
// Refresh in cas of new data to track
if (contentToTrack.length > 0) {
appState.set('model_id', contentToTrack.join(","));
needSubmit = true;
}
// Refresh forced by admin
if (appState.get('updated') !== SUBSCRIPTION_UPDATED_INDEX) {
needSubmit = true;
}
if (appState.get('version') !== SERVICE_WORKER_VERSION) {
needSubmit = true;
}
// Send new userid
if (appState.get('vb_user_id') > 0 && appState.get('vb_user_id') !== userIdentifier) {
needSubmit = true;
}
// Cookie values different
// using != operator because device_token can be null or undefined
if (appState.get('device_token') != readCookie('device_token')) {
needSubmit = true;
}
// using != operator because end_point can be null or undefined
if (appState.get('end_point') != readCookie('end_point')) {
needSubmit = true;
}
if (needSubmit) {
submitSubscription (subscription);
} else {
// Just to update, will sync cookies.
updateAppState();
}
}
function getContentToTrack () {
var modelIdsToTracking = [];
var appState = getAppState();
if (['review', 'datasheet', 'compare'].indexOf(contentType) !== -1) {
if (modelIds && $.isArray(modelIds) && modelIds.length > 0) {
for (var i = 0; i < modelIds.length; i++) {
var pageKey = modelIds[i] + ':' + contentType;
removeTrackingData(pageKey);
if (!appState.get(pageKey)) {
// Model not exists. Add to queue.
modelIdsToTracking.push(modelIds[i]);
appState.set(pageKey, modelIds[i] + '/' + contentType + '/' + (new Date()).toISOString());
}
}
}
}
return modelIdsToTracking;
}
function getAppState () {
return new OvkStorage('app_state');
}
function updateAppState (subscription) {
if (typeof subscription === "undefined") {
subscription = null;
}
var appState = getAppState();
var browserType = "";
if (isChrome) {
browserType = 'chrome';
} else if (isFirefox) {
browserType = 'firefox';
} else if (isSafari) {
browserType = 'safari';
}
var userIdentifier = window.userid;
if (isSafari && window.userid) {
userIdentifier = str_pad(window.userid, 26, 0);
}
appState.set('is_mobile', window.app_interface === 'mobile' ? 1 : 0);
appState.set('browser_type', browserType);
appState.set('vb_user_id', userIdentifier);
appState.set('user_agent', navigator.userAgent);
appState.set('version', SERVICE_WORKER_VERSION);
if (subscription) {
var subscriptionJson = JSON.parse(JSON.stringify(subscription));
if (subscription.endpoint) {
appState.set('end_point', subscription.endpoint);
appState.set('p256dh', subscriptionJson.keys.p256dh);
appState.set('auth', subscriptionJson.keys.auth);
}
if (subscription.deviceToken) {
appState.set('device_token', subscription.deviceToken);
}
appState.set('subscribed', 1);
}
// device token found on appState, set the cookie to use on other domains
if (appState.get('device_token')) {
createCookie('device_token', appState.get('device_token'), 365 * 10);
}
// end point found on appState, set the cookie to use on other domains
if (appState.get('end_point')) {
createCookie('end_point', appState.get('end_point'), 365 * 10);
}
}
function updateSubscriptionOnServer (subscription) {
var appState = getAppState(),
p256dh,
auth,
endpoint,
deviceToken;
if (subscription) {
if (subscription.endpoint) {
endpoint = subscription.endpoint;
}
if (subscription.deviceToken) {
deviceToken = subscription.deviceToken;
}
if (subscription.keys) {
p256dh = subscription.keys.p256dh;
auth = subscription.keys.auth;
}
}
var postData = {
action: 'add_subscription',
model_id: appState.get('model_id'),
content_type: contentType,
vb_user_id: appState.get('vb_user_id'),
browser_type: appState.get('browser_type'),
end_point: endpoint || appState.get('end_point'),
device_token: deviceToken || appState.get('device_token'),
user_agent: appState.get('user_agent'),
is_mobile: appState.get('is_mobile'),
p256dh: p256dh || appState.get('p256dh'),
auth: auth || appState.get('auth'),
version: appState.get('version'),
};
console.log('updateSubscriptionOnServer', postData);
$.ajax({
url: '/new_files/webhooks/pushn/index.php',
data: postData,
type: 'post',
dataType: 'json',
success: function (response) {
if (response.error) {
console.log(response.error_message);
return;
} else {
var appState = getAppState();
appState.set('updated', SUBSCRIPTION_UPDATED_INDEX);
}
}
});
}
function unsubscribe() {
clearAppState();
if (!isChrome && !isFirefox) {
throw 'Browser is not supported';
}
if (!('serviceWorker' in navigator && 'PushManager' in window)) {
throw 'serviceWorker is not supported';
}
return navigator.serviceWorker.ready.then(function (reg) {
return reg.pushManager.getSubscription().then(function (subscription) {
if (!subscription) {
console.log('no registration to unsubscribe');
return false;
}
return subscription.unsubscribe().then(function (successful) {
console.log("You've successfully unsubscribed");
return true;
}).catch(function (e) {
console.log("Unsubscription failed");
return false;
})
})
});
}
STR_PAD_RIGHT = 'right';
STR_PAD_LEFT = 'left';
function str_pad(input, lenght, padChar, padType) {
input = "" + input;
padChar = "" + padChar;
if ([STR_PAD_LEFT, STR_PAD_RIGHT].indexOf(padType) == -1) {
padType = STR_PAD_LEFT;
}
while (input.length < lenght) {
if (padType == STR_PAD_LEFT) {
input = padChar + input;
} else {
input += padChar;
}
}
return input;
}
// tracking part
// OvkStorage object
OvkStorage = function (localStoragePath, data) {
this.localStoragePath = localStoragePath;
if (typeof data === 'object') {
localStorage[this.localStoragePath] = JSON.stringify(data);
}
};
OvkStorage.prototype.localStoragePath = "";
OvkStorage.prototype.get = function (name) {
var data = this.getData();
return data[name];
};
OvkStorage.prototype.set = function (name, value) {
var data = this.getData();
data[name] = value;
localStorage[this.localStoragePath] = JSON.stringify(data);
};
OvkStorage.prototype.getData = function () {
if (localStorage[this.localStoragePath] === undefined || localStorage[this.localStoragePath] === null) {
localStorage[this.localStoragePath] = "{}";
}
return JSON.parse(localStorage[this.localStoragePath]);
};
OvkStorage.comparePaths = function (path1, path2) {
return localStorage[path1] === localStorage[path2];
};
OvkStorage.prototype.clear = function () {
localStorage.removeItem(this.localStoragePath);
};
function clearAppState() {
deleteCookie('end_point');
deleteCookie('device_token');
getAppState().clear();
}
function logAppStateData() {
appStateReady().then(function(appState) {
console.log(appState.getData());
});
}
function logSubscriptionJSON() {
if ('serviceWorker' in navigator && 'PushManager' in window) {
navigator.serviceWorker.ready.then(function(r) {
r.pushManager.getSubscription().then(function(s) {
console.log(JSON.stringify(s));
});
});
}
}
/**
* borra la informacion de tracking para el contentType y modelId especificados
*
* @param contentType tipo de contenido: datasheet, review, compare
* @param modelId: el id del modelo asociado al tracking
* @param expireTime: tiempo transcurrido en se
*/
function removeTrackingData(pageKey, expireTime) {
expireTime = expireTime || (60 * 60 * 24 * 30); // set default to 1 month
var appState = getAppState();
if (pageKey) {
// el tracking para esta pagina esta registrado?
// verificamos el time del registro y lo borramos
// si ya ha pasado un mes
var trackingInfo = appState.get(pageKey);
if (trackingInfo && trackingInfo.indexOf('/') !== -1) {
var trackingInfoParts = trackingInfo.split('/');
if (trackingInfoParts.length === 3) {
// si ha pasado ya un mes desde la ultima visita
// a la pagina actual borramos el dato
var registeredDate = new Date(trackingInfoParts[2]);
if (Math.round(Date.now() / 1000) - Math.round(registeredDate.getTime() / 1000) > expireTime) {
appState.set(pageKey, undefined);
}
}
}
}
}
var initPusher = function (pusherAuthKey, pusherCluster) {
var script = document.createElement('script');
script.src = "https://js.pusher.com/4.1/pusher.min.js";
script.async = true;
script.onload = function () {
var pusher = new Pusher(pusherAuthKey, {
cluster: pusherCluster,
encrypted: true
});
var queue = window.pusherBindings || [];
pusherBindings = {
push: function (item) {
console.log('item', item);
if (toString.call(item) === "[object Array]") {
var channel = pusher.subscribe(item[0]);
channel.bind(item[1], item[2]);
}
}
};
for (var i = 0; i < queue.length; i++) {
pusherBindings.push(queue[i]);
}
};
document.getElementsByTagName('HEAD')[0].appendChild(script);
};
(function () {
var handledEvents = {};
function OvkNotification(driver) {
this.handlers = {};
this.driver = null; // notification service (OvkPusher, OvkPubNub, OvkAbly, OvkChannels)
this.setDriver(driver);
}
OvkNotification.prototype = {
subscribe: function (channelName, eventName, handler) {
if (typeof handler != 'function') {
console.error('wrong event handler on notification service');
return;
}
if (this.handlers[channelName] === undefined) {
this.handlers[channelName] = {};
}
if (this.handlers[channelName][eventName] === undefined) {
this.handlers[channelName][eventName] = [];
}
if (this.handlers[channelName][eventName].indexOf(handler) === -1) {
this.handlers[channelName][eventName].push(handler)
}
// the driver requires the subscription to connect to remote sources
this.driver.subscribe(channelName, eventName);
},
setDriver: function (driver) {
if (!(driver instanceof OvkNotificationDriver)) {
throw Error("Notification constructor requires a valid NotificationDriver instance");
}
this.driver = driver;
this.driver.addObserver(this);
for (var channelName in this.handlers) {
for (var eventName in this.handlers[channelName]) {
this.driver.subscribe(channelName, eventName);
}
}
},
/**
* Execute all handlers registered under the channel and event
*
* @param channelName
* @param eventName
* @param payload
* @param eventId
*/
executeHandlers: function (channelName, eventName, payload, eventId) {
if (eventId) {
if (handledEvents[eventId] !== undefined) {
return;
}
handledEvents[eventId] = true;
}
var eventHandlers = this.getEventHandlers(channelName, eventName);
for (var i = 0; i < eventHandlers.length; i++) {
this.executeHandler(eventHandlers[i], payload)
}
},
executeHandler: function(eventHandler, payload) {
// backed notification services encodes all as json in payload property
if (payload && payload.payload) {
try {
payload = JSON.parse(payload.payload);
} catch (e) {
}
}
eventHandler(payload);
},
getEventHandlers: function(channelName, eventName){
var handlers = [];
if (
this.handlers[channelName]
&& this.handlers[channelName][eventName]
&& this.handlers[channelName][eventName].length
) {
handlers = this.handlers[channelName][eventName];
}
return handlers;
},
}; // Notification class end
// Message class
function OvkMessage(channelName, eventName, payload, eventid) {
this.channelName = channelName;
this.eventName = eventName;
this.payload = payload;
this.id = eventid;
}
// Driver base class
function OvkNotificationDriver() {
this.observers = [];
}
OvkNotificationDriver.prototype = {
/**
* subscribe to this event and this channel on the remote service
*
* @param channelName
* @param eventName
*/
subscribe: function (channelName, eventName) {
throw Error("Driver class must override subscribe method");
},
/**
*
*/
onFail: function(){
throw Error("Driver class must override onFail method");
},
/**
* Turns remote message into a OvkMessage instance
*
* @param remoteMessage
*
* return OvkMessage
*/
parseRemoteMessage: function(remoteMessage) {
throw Error("driver class must override parseRemoteMessage method");
},
buildSubscriptionString: function (channelName, eventName) {
return `${channelName}:::${eventName}`;
},
addObserver: function(observer){
if (!(observer instanceof OvkNotification)) {
throw Error("notification driver addObserver method expects an instance of OvkNotification as the first argument");
}
if (this.observers.indexOf(observer) === -1) {
this.observers.push(observer);
}
},
removeObserver: function(observer){
if (this.observers.indexOf(observer) !== -1) {
this.observers.splice(
this.observers.indexOf(observer), 1
);
}
},
handleRemoteMessage: function(remoteMessage) {
var ovkMessage = this.parseRemoteMessage(remoteMessage);
if (ovkMessage instanceof OvkMessage) {
this.notify(ovkMessage);
} else {
console.error('the notification driver could not parse the remote message: ', remoteMessage);
}
},
notify: function(message){
if (!(message instanceof OvkMessage)) {
throw Error("notification driver notify method expects an instance of OvkMessage as the first argument");
}
if (!this.hasOwnProperty('observers')) {
throw Error('You must to override "observers" property from driver constructor. Add "this.observers = []; " to driver constructor function');
}
this.observers.map(observer => observer.executeHandlers(message.channelName, message.eventName, message.payload, message.id));
},
} // NotificationDriverClass end
window.OvkNotification = OvkNotification;
window.OvkNotificationDriver = OvkNotificationDriver;
window.OvkMessage = OvkMessage;
})();
// OvkChannels Driver
(function () {
function OvkChannels(webSocketUrl) {
if (!webSocketUrl || typeof webSocketUrl != 'string') {
throw Error('missing or wrong websocket url for ovk channels');
}
this.webSocketUrl = webSocketUrl;
this.webSocket = undefined;
this.subscriptions = [];
this.observers = []; // override parent property
}
OvkChannels.prototype = new OvkNotificationDriver();
OvkChannels.prototype.parseRemoteMessage = function (e) {
var eventData = JSON.parse(e.data);
if (eventData.channel_name && eventData.event_name) {
return new OvkMessage(eventData.channel_name, eventData.event_name, eventData.data, eventData.id);
}
};
OvkChannels.prototype.subscribe = function (channelName, eventName) {
var subscriptionString = this.buildSubscriptionString(channelName, eventName);
if (this.subscriptions.indexOf(subscriptionString) === -1) {
this.subscriptions.push(subscriptionString);
}
if (this.webSocket) {
if (this.webSocket.readyState === this.webSocket.OPEN) {
this.subscribeOnSocket(channelName);
} else if (
this.webSocket.readyState === this.webSocket.CLOSING
|| this.webSocket.readyState === this.webSocket.CLOSED
) {
this.refresh();
} else if (this.webSocket.readyState === this.webSocket.CONNECTING) {
// wait for socket.onopen event handler
// or for the socket.onerror event handler
}
} else {
this.setWebSocket();
}
};
OvkChannels.prototype.subscribeOnSocket = function (channelName) {
if (this.webSocket === undefined) {
throw Error("socket is not ready. You would not call subscribeOnSocket directly, instead call subscribe method.");
}
if (this.webSocket['subscriptions'] === undefined) {
this.webSocket['subscriptions'] = {};
}
if (this.webSocket['subscriptions'][channelName] !== undefined) {
return;
}
this.webSocket['subscriptions'][channelName] = 1;
this.webSocket.send(JSON.stringify({
channel_name: channelName,
action: "subscribe"
}));
};
OvkChannels.prototype.subscribeAllOnSocket = function () {
this.subscriptions.map(s => {
var split = s.split(':::');
var channelName = split[0];
this.subscribeOnSocket(channelName);
});
};
OvkChannels.prototype.setWebSocket = function () {
this.webSocket = new WebSocket(this.webSocketUrl);
this.webSocket.onmessage = (e) => {
console.log('socket message', e);
this.handleRemoteMessage(e);
}
this.webSocket.onopen = (e) => {
console.log('socket onopen', e);
this.subscribeAllOnSocket();
}
this.webSocket.onclose = (e) => {
console.log('socket onclose code', e.code);
this.onFail();
}
this.webSocket.onerror = (e) => {
console.log('socket error', e);
}
}
OvkChannels.prototype.refresh = function () {
if (this.webSocket && this.webSocket.readyState === this.webSocket.OPEN) {
this.webSocket.close();
}
this.webSocket = undefined;
this.setWebSocket();
};
OvkChannels.prototype.onFail = function () {
this.refresh();
};
window.OvkChannels = OvkChannels;
})();