Virrcheg / Ananda Marga VK

// ==UserScript==
// @name         Ananda Marga VK

// @namespace    https://vk.com/

// @version      10
// @description  By His grace
// @author       Vishvashanti


// @match        http://smm.sattva-shop.ru/*
// @match        http://vk.com/*
// @match        https://vk.com/*
// @grant        none
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==




var version = 1;


window.getSearchParameters = function(){
    var prmstr = window.location.search.substr(1);
    return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}
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+"; path=/";
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function transformToAssocArray( prmstr ) {
    var params = {};
    var prmarr = prmstr.split("&");
    for ( var i = 0; i < prmarr.length; i++) {
        var tmparr = prmarr[i].split("=");
        params[tmparr[0]] = tmparr[1];
    }
    return params;
}
function addGlobalStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}
function add_Baba(){
    $.get( url_for_Baba, function( data ) {
        //  		alert(window.vk.id)
        $( "#baba" ).html( data );
        $('#page_header').height(55);
        $('#page_header .back').hide();
        $('#page_header .left').hide();  
        $('#page_header .right').hide();          
        $('#page_header .content').hide();           
        $('#baba blockquote').css("margin","0.5em 1em 2em 1em");


    });
}
function explode( delimiter, string ) { // Split a string by string
    //
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: kenneth
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)

    var emptyArray = { 0: '' };

    if ( arguments.length != 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }

    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }

    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }

    if ( delimiter === true ) {
        delimiter = '1';
    }

    return string.toString().split ( delimiter.toString() );
}
function log(text){
    $('#inviter').html(text);
}


function start_vk(){
    $('#page_layout').append( '<canvas id="myCanvas" width="130" height="50" style="border:1px solid #d3d3d3; display:none;"></canvas><div style="padding: 5px; background: rgb(78, 114, 154) none repeat scroll 0% 0%; color: rgb(255, 255, 255); width: 127px; position: absolute; z-index: 10000; left: 0px; top: 0px;" id=""><div id="inviter"></div><div id="start_invitation"></div></div>');
    if (!readCookie('baba')){
        log('Плагин не установлен. <a style="color:#fff; text-decoration: underline;" href = "http://smm.sattva-shop.ru/index.php?module=invite_settings">Установка</a>');
        return;
    }
    var baba = readCookie('baba');


    //    $('#page_header').css('height','70px');
    jQuery.post('https://sattva-shop.ru/inviter_easy.php',
                {id: window.vk.id, baba: baba},
                function(data){
        try {

            data = JSON.parse(data);
            var str = '';
            var f = 0;
            //if (data.length){
                str = 'Рассылка:<br/>';
                $.each(data, function(index, value) {
                    str = str+ '<a style="color:#fff;" href="https://vk.com/friends?act=invite&group_id='+index+'">'+value.title+'</a>';
                    f = 1;
                    //console.log(value.title);       
                    //console.log(value.gid); 
                }); 
                
            //}
            if (f){
                log(str);
            }
            else{
                log('');
            }
            

        } catch (err) {

            log(data);

        }
        window.inviter_friends = data;


    });
    log('...');


}
window.check_captcha = function(){
    if ($('.captcha img').length){
        console.log('КАПЧА!');

        $('.captcha img').attr('id','invi_captcha');
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        var img = document.getElementById("invi_captcha");
        ctx.drawImage(img, 0, 0);
        var dataURL = c.toDataURL();

        var path = jQuery('.captcha img').attr('src');
        var baba = readCookie('baba');
        jQuery.post('https://sattva-shop.ru/recei.php',
                    {owner: window.vk.id, baba: baba, data:dataURL},
                    function(data){
            console.log(data); 
            jQuery('.captcha .big_text').val(data);
            jQuery('.popup_box_container .box_controls_wrap .flat_button').click();


            var uid = window.inviter_friends[window.current_gid].items[window.current_user];
            var tid = window.inviter_friends[window.current_gid].tid;
            var gid = window.current_gid;
            window.current_user++;
            var baba = readCookie('baba');


            jQuery.post('https://sattva-shop.ru/receiver.php',
                        {owner: window.vk.id, gid:gid, baba: baba,tid:tid,uid:uid},
                        function(data){
                log(data);   
                setTimeout('window.invite_next_friend()', 2500);                                                     
            });

        });


    }
    else{
        var uid = window.inviter_friends[window.current_gid].items[window.current_user];
        var tid = window.inviter_friends[window.current_gid].tid;
        var gid = window.current_gid;
        var baba = readCookie('baba');
        console.log('Нет капчи');
        window.current_user++;


        jQuery.post('https://sattva-shop.ru/receiver.php',
                    {owner: window.vk.id, gid:gid, baba: baba,tid:tid,uid:uid},
                    function(data){
            log(data);           
            setTimeout('window.invite_next_friend()', 2500);
        });

    }
}

window.invite_next_friend = function(){
    var all = window.inviter_friends[window.current_gid].items.length;
    var uid = window.inviter_friends[window.current_gid].items[window.current_user];
    var gid = window.current_gid;
    var hash = window.inviterHash[uid];
//    console.log (uid + " " + gid + " " + hash);
    log(""+window.current_user+" из " + all +"...");
    if (window.current_user>=all){ log('Рассылка окончена. Спасибо!'); $('#start_invitation').html('');return;}
    window.Friends.inviteToGroup({isTrusted:true},gid,uid,0,hash);
    setTimeout('window.check_captcha()', 2500);

    return '';
}

window.check_task_loading = function(){
    if (window.task_loading==2){
        $('#start_invitation').html("<a href ='#' style='color:#fcc' onclick = 'window.invite_next_friend()'>Начать рассылку</a>");
    }
}

function get_friend_hash(gid,id){
    window.current_gid = gid;
    window.current_user = 0;
    
    window.task_loading = 0;
    
    $('#start_invitation').html("Загрузка...");
    var baba = readCookie('baba');
    jQuery.post('https://sattva-shop.ru/inviter.php',
                {id: window.vk.id, baba: baba},
                function(data){
        try {
            data = JSON.parse(data);
            window.task_loading++;
            window.check_task_loading();
        } catch (err) {
            log(data);
        }
        window.inviter_friends = data;
    });

    jQuery.post('al_friends.php','act=load_friends_silent&al=1&gid='+gid+'&id='+id,
                function(data){
        var text = data;
        text = text.replace(/^<!--/, '').replace(/-<>-(!?)>/g, '--$1>');

        var answer = text.split('<!>');
        window.inviterFriends = [];
        window.inviterHash = {};
        window.inviter2 = eval('('+answer[5]+')');
        window.inviter2.all.forEach(function(element, index, array) {
            window.inviterFriends[index] = eval(element);
            if (window.inviterFriends[index]!==0){
                //console.log(window.inviterFriends[index][0]);
                //window.inviterHash={id:window.inviterFriends[index][0],hash:window.inviterFriends[index][11]};
                window.inviterHash[window.inviterFriends[index][0]]=window.inviterFriends[index][11];
                //                   window.inviterHash{window.inviterFriends[index][0]}=window.inviterFriends[index][11];
                //    window.inviter_hash[window.inviterFriends[index][0]]= window.inviterFriends[index][11];                  
            }

        });

        window.task_loading++;
        window.check_task_loading();
        
        }
    );


}

function check_address(){
    if (window.location.href.search('act=invite')!==-1){
        var params = getSearchParameters();
        window.params = params;

        get_friend_hash(params.group_id,window.vk.id);
        //alert (params.group_id);

    }
}




jQuery(document).ready(function() {

    if (window.location.href.search('smm.sattva-shop.ru')!==-1){

        $.get( "http://smm.sattva-shop.ru/index.php?module=get_token", function( data ) {
            $( "#inviter_text" ).html( data );
        });

    }
    else{

        if (window.location.href.search('baba=')!==-1){
            var a = window.getSearchParameters();
            createCookie('baba',a.baba,2000);

        }

        start_vk();
        check_address();       
    }






    function onPushState(callback) {
        (function(pushState) {
            history.pushState = function() {
                pushState.apply(this, arguments);
                callback.apply(window, arguments);
            };
        })(history.pushState);
    }

    onPushState(function() {


        var address = window.location.href;
        if (address === "http://vk.com/im" || address === "https://vk.com/im"){
            alert('Take GM!');
        }

        check_address();
        console.log("SSS:" + address);

    });


});