﻿//$(document).ready(function () {
function KernelAdvertisementReferring() {
    //alert(22222);
    //сохраняем сессию:
    try {
        $.ajax(
                {
                    type: "POST",
                    url: "/DirectAction/ToolsAsync/SaveSessionInfo",
                    data: {},
                    success: function (result) {
                            
                    },
                    error: function (req, status, error) {
                    }
                });
    }
    catch (err) { }

    var Referring = '';
    //examples:
    //href == http://localhost:6661/?y=2641525&n=M-10166379#goodtype=Classic&y=2641525&n=M-10166379
    //hash == #goodtype=Classic&y=2641525&n=M-10166379
    //search == ?y=2641525&n=M-10166379
    try {
        var arrParamValues = new Array();
        var hash = window.location.hash;
        hash = hash.replace("#", "");
        var hashArr = hash.split("&");
        var ii = 0;
        $(hashArr).each(function () {
            if (this != '') {
                var paramValue = this.split('=');
                var param = paramValue[0];
                var value = paramValue[1];
                arrParamValues[ii] = new Array();
                arrParamValues[ii][0] = param;
                arrParamValues[ii][1] = value;
                ii++;

                Referring += SetAdvtCookies(param, value);
            }
        });
    }
    catch (err) { }

    try {
        var search = window.location.search;
        search = search.replace("?", "");
        var searchArr = search.split("&");
        $(searchArr).each(function () {
            if (this != '') {
                var paramValue = this.split('=');
                var param = paramValue[0];
                var value = paramValue[1];
                arrParamValues[ii] = new Array();
                arrParamValues[ii][0] = param;
                arrParamValues[ii][1] = value;
                ii++;

                Referring += SetAdvtCookies(param, value, Referring);
            }
        });
    }
    catch (err) { }

    try {
        var referring_id = $.cookie('referring_id');
        if (referring_id == null || referring_id == '') {
            if (Referring == '') {
                Referring = "новая сессия по прямому переходу без параметров";
            }
        }
    }
    catch (err) { }

    var utm_source = null;
    var utm_medium = null;
    var utm_term = null;
    var utm_content = null;
    var utm_campaign = null;
    var utm_user = null;
    var __utmz = null;
    try {
        utm_source = $.cookie('utm_source');
        utm_medium = $.cookie('utm_medium');
        utm_term = $.cookie('utm_term');
        utm_content = $.cookie('utm_content');
        utm_campaign = $.cookie('utm_campaign');
        utm_user = $.cookie('utm_user');
        __utmz = $.cookie('__utmz');
    } catch (e) {
    } 

    //устанавливаем переменные Piwik:
    try {
        piwikTracker.setCustomVariable(1, "utm_source", decodeURI(utm_source), "visit");
        piwikTracker.setCustomVariable(2, "utm_medium", decodeURI(utm_medium), "visit");
        piwikTracker.setCustomVariable(3, "utm_campaign", decodeURI(utm_campaign), "visit");
        piwikTracker.setCustomVariable(4, "utm_content", decodeURI(utm_content), "visit");
        piwikTracker.setCustomVariable(5, "utm_term", decodeURI(utm_term), "visit");
    }
    catch (err) { }

    //если это переход по рекламной ссылке, записываем данные в базу:
    try {
        //пустые данные не передаем на сервер для снижения нагрузки:
        if (utm_source == null && utm_medium == null && utm_term == null && utm_content == null && utm_campaign == null && utm_user == null && __utmz == null) {
            return;
        }
        //если источник перехода еще не записан, то отправляем его на сервер:
        if (Referring != '') {
            $.ajax(
                {
                    type: "POST",
                    url: "/DirectAction/Promotion/Referring",
                    data: { utm_source: utm_source
                            , utm_medium: utm_medium
                            , utm_term: utm_term
                            , utm_content: utm_content
                            , utm_campaign: utm_campaign
                            , utm_user: utm_user
                            , __utmz: __utmz
                    },
                    success: function (result) {
                        if (result.status == 'success') {
                            $.cookie('referring_id', result.referring_id, { path: '/' });

                            //данные на пользователя были успешно записаны, обнуляем на случай если пользователь снова прийдет по рекламе:
                            $.cookie('utm_source', null);
                            $.cookie('utm_medium', null);
                            $.cookie('utm_term', null);
                            $.cookie('utm_campaign', null);
                            $.cookie('utm_content', null);
                            $.cookie('utm_user', null);

                            $.cookie('utm_source_decode', null);
                            $.cookie('utm_medium_decode', null);
                            $.cookie('utm_term_decode', null);
                            $.cookie('utm_campaign_decode', null);
                            $.cookie('utm_content_decode', null);
                            $.cookie('utm_user_decode', null);
                        }
                    },
                    error: function (req, status, error) {
                    }
                });
        }

        //alert(decodeURI($.cookie('utm_content')));
    }
    catch (err) { }


}

//---------------------------------------------------------------------------------------------------------------------
function SetAdvtCookies(param, value) {
//    var exp = 1; //время cookie
//    if (param == 'y' || param == 'g') {
//        if (param == 'y')
//            $.cookie('advt_company', 'yandex', { path: '/' });
//        else
//            $.cookie('advt_company', 'google', { path: '/' });
//        $.cookie('advt_company_name', value, { path: '/' });
//        //$.cookie('advt_company_section', value, { expires: exp, path: '/' });
//    }
//    if (param == 'n') {
//        $.cookie('advt_company_section', value, { path: '/' });
//    }


    var ref = '';
//string.Format("?utm_source={0}&utm_medium={1}&utm_term={2}&utm_content={3}&utm_campaign={4}", "yandex.market", "yandex_cpc", product.GoodGroupNameEng.ToLower().Replace(" ", "_"), product.GoodID, "market_systems");
//новое универсальное промо с остальных каталогов:
    switch (param) 
    {
//старый формат: 
        case 'y':
            $.cookie('utm_source', 'yandex.direct', { path: '/' });
            $.cookie('utm_medium', 'yandex_cpc', { path: '/' });
            $.cookie('utm_campaign', value, { path: '/' });
            ref = '&utm_source=yandex.direct&utm_medium=yandex_cpc&utm_campaign=' + value;
            break;
        case 'g':
            $.cookie('utm_source', 'google.adwords', { path: '/' });
            $.cookie('utm_medium', 'adwords_cpc', { path: '/' });
            $.cookie('utm_campaign', value, { path: '/' });
            ref = '&utm_source=google.adwords&utm_medium=adwords_cpc&utm_campaign=' + value;
            break;
        case 'n':
            $.cookie('utm_content', value, { path: '/' });
            ref = '&utm_content=' + value;
            break;

//новый формат:
        case 'utm_source':
            $.cookie('utm_source', value, { path: '/' });
            try { $.cookie('utm_source_decode', decodeURI($.cookie('utm_source')), { path: '/' }); } catch (err) { }
            ref = '&utm_source=' + value;
            break;
        case 'utm_medium':
            $.cookie('utm_medium', value, { path: '/' });
            try { $.cookie('utm_medium_decode', decodeURI($.cookie('utm_medium')), { path: '/' }); } catch (err) { }
            ref = '&utm_medium=' + value;
            break;
        case 'utm_term':
            $.cookie('utm_term', value, { path: '/' });
            try { $.cookie('utm_term_decode', decodeURI($.cookie('utm_term')), { path: '/' }); } catch (err) { }
            ref = '&utm_term=' + value;
            break;
        case 'utm_content':
            $.cookie('utm_content', value, { path: '/' });
            try { $.cookie('utm_content_decode', decodeURI($.cookie('utm_content')), { path: '/' }); } catch (err) { }
            ref = '&utm_content=' + value;
            break;
        case 'utm_campaign':
            $.cookie('utm_campaign', value, { path: '/' });
            try { $.cookie('utm_campaign_decode', decodeURI($.cookie('utm_campaign')), { path: '/' }); } catch (err) { }
            ref = '&utm_campaign=' + value;
            break;
        case 'utm_user':
            $.cookie('utm_user', value, { path: '/' });
            try { $.cookie('utm_user_decode', decodeURI($.cookie('utm_user')), { path: '/' }); } catch (err) { }
            ref = '&utm_user=' + value;
            break;
    }
    return ref;
}
