var StopApp = ;
var SecForSite = ;
var iPages = ;
var iShowHour = ;
var iCupGets = ;
var StopRegions = '';
var AddMinutes = ;
var RegionOk = true;
var dc78_frame_open = 'no';
var dc78_no_order = true;
// получениe GET параметров из url
var result = getUrlVar();
if(result['dc78'] == 'show'){
StopApp = 'yes';
ShowCoupon();
//setTimeout(CreateFrame(dc78_frame_open), 1000);
}
if(StopApp){ //Если показы объявлений остановленны - незачем писать куки
// ----------- Cookies ---------------
var time_zone = new Date().getTimezoneOffset();//Получаем разницу для часловой зоны (москва= -180)
time_zone = time_zone * 60 * 1000;//Получаем разницу для часловой зоны (москва= -180)
//Дата создания куки в секундах
var CookiesTime = new Date().getTime(); //Дата создания куки
//Дата захода в секундах
if(getCookie('coup_date') == null){ //куков еще нет
setCookie('coup_date', CookiesTime, '/', (new Date).getTime() + time_zone + 60000);
}
//Посетил страниц
if(getCookie('coup_pages') == null){ //куков еще нет
setCookie('coup_pages', '1', '/', (new Date).getTime() + time_zone + 60000);
}else{//кука есть
var coup_pages = getCookie('coup_pages');
coup_pages++;
setCookie('coup_pages', coup_pages, '/', (new Date).getTime() + time_zone + 60000);
}
//Сделал заказ
var lh = document.location.pathname;
if(lh.indexOf('new_order') + 1){
dc78_no_order = false;
setCookie('coup_order', 'Yes', '/', (new Date).getTime() + time_zone + 60000);
}
if(getCookie('coup_order') == 'Yes'){
dc78_no_order = false;
}
//Автообновление времени истечения кукисов Каждые 10 секунд переназначаем время на 20 секунд вперед
function CookiesReTime(CookiesTime) {
setInterval(function() {
if(getCookie('coup_date') != null){
setCookie('coup_date', getCookie('coup_date'), '/', (new Date).getTime() + time_zone + 20000);
}
if(getCookie('coup_pages') != null){
setCookie('coup_pages', getCookie('coup_pages'), '/', (new Date).getTime() + time_zone + 20000);
}
if(getCookie('coup_order') != null){
setCookie('coup_order', 'Yes', '/', (new Date).getTime() + time_zone + 20000);
}
}, 10000);
}
CookiesReTime();
// ----------- END Cookies -----------
}
//Создаем тег link чтоб подгрузить стили
var dc78_css = document.createElement("link");
dc78_css.rel = 'stylesheet';
dc78_css.href = 'https://dc78.ru/coupons/style.css';
document.querySelector("body").append(dc78_css);
//Создаем контейнер чтоб потом в него подгрузить фрейм
var dc78_div = document.createElement("div");
dc78_div.id = 'dc78_coupon';
var html = '
';
dc78_div.innerHTML = html;
document.querySelector("body").append(dc78_div);
// Проверяем подключена ли jQuery. Если нет - подключаем
if (window.jQuery){
console.log('jQuery подключена');
GetRegion();//jQuery подключена, Определяем регион
}else {
//Подключаем jQuery
var jql = document.createElement("script");
jql.type = "text/javascript",
jql.src = "//code.jquery.com/jquery-1.12.0.min.js",
jql.async = !0,
document.getElementsByTagName("body")[0].appendChild(jql),
jqlR = function() {
document.head.insertBefore(jql, null);
}, jqlR(), jql.onload = function() {
GetRegion();//Определяем регион
}
}
//Определение региона
function GetRegion() {
$.ajax({
url: 'https://kladr.insales.ru/current_location.json',
type: 'get',
dataType: 'jsonp',
success: function(data){
//console.log('Ваш регион: ' + data.region);
CompRegion(data.region);
}
});
}
//Сравниваем регион юзера с запрещенными регионами показа
function CompRegion(UserRegion) {
var regions = StopRegions.split(', ');
regions.forEach(function(item, i, regions) {
if(item === UserRegion){
RegionOk = false;
}
});
if(RegionOk){
console.log('dc78 >> В этом регионе показ предложения разрешен');
СheckStop(StopApp);
}else{
console.log('dc78 >> В этом регионе показ предложения запрещен');
}
}
function СheckStop(StopApp) {
if(StopApp){
console.log('dc78 >> Показы разрешены');
СheckGetsCupon(iCupGets);
}else{
console.log('dc78 >> Показы остановленны в настройках приложения или баланс меньше стоимости купона');
}
}
function СheckGetsCupon(iCupGets) {
if( (getCookie('coup_get') != null) && (new Date().getTime() <= (getCookie('coup_get')*1) + (iCupGets * 24 * 60 * 60 * 1000)) ){
console.log('dc78 >> Подарок получен N дней назад');
}else{
console.log('dc78 >> Пользователь не получал подарка или уже прошло N дней');
СheckOrder();
}
}
function СheckOrder() {
if(dc78_no_order){
console.log('dc78 >> Пользователь еще не делал заказ');
СheckShow();
}else{
console.log('dc78 >> Пользователь уже сделал заказ');
}
}
function СheckShow() {
if(getCookie('coup_show') == null){
console.log('dc78 >> Предложение еще не показывалось');
ShowCoupon();
}else{
console.log('dc78 >> Предложение уже показывалось');
}
}
function ShowCoupon() {
//Пытается уйти
$(window).on('mouseleave', function(e) {
if (e.clientY < 10 && dc78_frame_open == 'no') {
//Показываем если дата куков+задержка < текущего времени
if( (getCookie('coup_date')*1) + (SecForSite*1000) <= new Date().getTime() ){
CreateFrame(dc78_frame_open);
dc78_frame_open = 'yes';
//Пишем куку что предложение уже показанно
setCookie('coup_show', '1', '/', (new Date).getTime() + time_zone + (iShowHour * 60 * 60 * 1000) );
}
}
});
//Посетил больше страниц чем
if(getCookie('coup_pages') > iPages){
setTimeout( function(){CreateFrame(dc78_frame_open);}, 3000);
dc78_frame_open = 'yes';
//Пишем куку что предложение уже показанно
setCookie('coup_show', '1', '/', (new Date).getTime() + time_zone + (iShowHour * 60 * 60 * 1000) );
}
}
function CreateFrame(dc78_frame_open) {
//Создаем фрейм
dc78_frame = document.createElement("iframe");
dc78_frame.src = 'https://dc78.ru/coupons/widget.html';
dc78_frame.id = 'dc78_frame';
dc78_frame.name = 'dc78_frame';
document.getElementById("dc78_modabody").append(dc78_frame);
document.getElementById("dc78_exitblock").style.display = 'block';
//setTimeout(SendData, 500);
}
//Передаем данные во фрейм
/*
function SendData() {
var win = window.frames.dc78_frame;
//Дата создания куки в смекундах
var CookiesTime = new Date().getTime(); //Дата создания куки
CookiesTime = 'CookiesTime'+CookiesTime; //Дата создания куки
win.postMessage(CookiesTime, "*");
var site = document.location.host; //Дата создания куки
site = 'siteHost'+site; //Дата создания куки
console.log(site);
win.postMessage(site, "*");
}
*/
//закрыть окно
document.getElementById('dc78_closeblock').onclick = function() {
document.getElementById("dc78_coupon").style.display = 'none';
}
//Пришло сообщение от из фрейма
function listener(event) {
if (event.origin != 'https://dc78.ru') {
return; // что-то прислали с неизвестного домена - проигнорируем..
}
//отказываюсь от скидки
if(event.data == 'nosale'){
document.getElementById("dc78_coupon").style.display = 'none';
setCookie('coup_get', new Date().getTime(), '/', (new Date).getTime() + (365 * 24 * 60 * 60 * 1000) + time_zone );
}
//закрыть окно
if(event.data == 'close'){
document.getElementById("dc78_coupon").style.display = 'none';
}
if(event.data == 'yes'){
//console.log("купон получен");
//Купон получен
setCookie('coup_get', new Date().getTime(), '/', (new Date).getTime() + (365 * 24 * 60 * 60 * 1000) + time_zone );
}
}
//Прослушиваем сообщения от фрейма по postMessage
if (window.addEventListener) {
window.addEventListener("message", listener);
} else {
window.attachEvent("onmessage", listener); // IE8
}
//функция получения GET параметров из url
function getUrlVar(){
var urlVar = window.location.search; // получаем параметры из урла
var arrayVar = []; // массив для хранения переменных
var valueAndKey = []; // массив для временного хранения значения и имени переменной
var resultArray = []; // массив для хранения переменных
arrayVar = (urlVar.substr(1)).split('&'); // разбираем урл на параметры
if(arrayVar[0]=="") return false; // если нет переменных в урле
for (i = 0; i < arrayVar.length; i ++) { // перебираем все переменные из урла
valueAndKey = arrayVar[i].split('='); // пишем в массив имя переменной и ее значение
resultArray[valueAndKey[0]] = valueAndKey[1]; // пишем в итоговый массив имя переменной и ее значение
}
return resultArray; // возвращаем результат
}
// возвращает cookie с именем name, если есть, если нет, то undefined
function getCookie(name) {
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
function setCookie(name, value, path, expires, domain, secure) {
var c_domain = "." + document.location.host;
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + (new Date(expires)) : "") +
((path) ? "; path=" + path : "") +
((c_domain) ? "; domain=" + c_domain : "") +
((secure) ? "; secure" : "");
}