Yack / Castle Age Gift Trading

// ==UserScript==
// @name        Castle Age Gift Trading
// @namespace   Gift Trading
// @author      Yack
// @description Accept friend's gift and resend DIFFERENT gift back

// @include     https://web3.castleagegame.com/castle_ws/*
// @exclude     https://web3.castleagegame.com/castle_ws/connect_login.php
// @require     http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js
// @version     0.08
// @grant       GM_registerMenuCommand
// @grant       GM_xmlhttpRequest
// @grant       GM_info

// ==/UserScript==

var times = 0;
var str;
var acceptLink = [];
var senderID = [];
var senderName = [];
var itemName = [];
var idForGift = [];
var current = 0;
var accepted = "";
var giftNames = [];
var giftID = [];

$.get( "gift.php", function( data ) {
    if(/padding\:10px 0 0 0;">+(.*)<\/div>/gi.test(data)) {
       var reName = /padding\:10px 0 0 0;">+(.*)<\/div>/gi;
       var reNum = /'gift\.php\?giftSelection\=+(.*)'\); return/gi;
       var m;

       while ((m = reName.exec(data)) != null) {
          if (m.index === reName.lastIndex) reName.lastIndex++;
          giftNames.push(m[1]);
       }
       while ((m = reNum.exec(data)) != null) {
          if (m.index === reNum.lastIndex) reNum.lastIndex++;
          giftID.push(m[1]);
       }
    }
});

function check(){
    str = "";
    acceptLink = [];
    senderID = [];
    senderName = [];
    itemName = [];
    idForGift = [];
    current = 0;
    accepted = "";
    
    var url = "https://web3.castleagegame.com/castle_ws/news_feed_view.php?feed=allies";
       
    $.get(url, function(data,status){
        if(/You received a Gift!/.test(data)) {
            str = data;
            saveSender();
        }else{
            document.getElementById("results_main_wrapper").innerHTML = '<div class="results" style="background-image: url("https://castleagegame1-a.akamaihd.net/graphics/bg_main_middle.jpg");background-color:#D0B682;width:700px;">'+
					'<div class="result">'+
				'<span class="result_body">				<div style="width:700px;">'+
					'<div style="width:700px;height:20px;background-image:url("https://castleagegame1-a.akamaihd.net/graphics/gift_background.jpg");">'+
					'	<div style="clear:both;"></div>'+
					'	<div style="float:left;width:700px;height:20px;">'+
					'		<div style="width:700px;height:20px;">'+
					'			<div style="font-weight:bolder;color:#000000;">'+
					'				<center>You got no gifts to accept.</center>'+
					'			</div>'+
					'		</div>'+
					'	</div>'+
					'	<div style="clear:both;"></div>'+
					'</div>'+
			'	</div>'+
			'	</span>'+
			'</div>'+
			'	</div>'+
		'<br />';
            setTimeout( function() {check();}, 15000);
        }
    });
}


function saveSender(){
    if(/You received a Gift!/.test(str)){
        var accLink = str.substring(str.indexOf("index.php?feed=allies&news_feed_accept=1&sender_id="));
        var url = "https://web3.castleagegame.com/castle_ws/";
        acceptLink.push(url + accLink.substring(0,accLink.indexOf('" onclick=')))
        str = str.substring(str.indexOf("index.php?feed=allies&news_feed_accept=1&sender_id=")+51);
        senderID.push(str.substring(0, str.indexOf("&")));
        str = str.substring(str.indexOf('<div style="width:275px;text-align:center;">'));
        senderName.push($.trim(str.substring(44, str.indexOf("has sent you a"))));
        str = str.substring(str.indexOf("has sent you a ")+15);
        itemName.push($.trim(str.substring(0, str.indexOf("</div>"))));
        saveSender();
    }
    else acceptGift();
}

function acceptGift(){
    if(current < senderID.length){
        document.getElementById("results_main_wrapper").innerHTML = '<div class="results" style="background-image: url("https://castleagegame1-a.akamaihd.net/graphics/bg_main_middle.jpg");background-color:#D0B682;width:700px;">'+
					'<div class="result">'+
				'<span class="result_body">				<div style="width:700px;">'+
					'<div style="width:700px;height:20px;background-image:url("https://castleagegame1-a.akamaihd.net/graphics/gift_background.jpg");">'+
					'	<div style="clear:both;"></div>'+
					'	<div style="float:left;width:700px;height:20px;">'+
					'		<div style="width:700px;height:20px;">'+
					'			<div style="color:#000000;">'+
					'				<center>Accepting <b>' + itemName[current] + '</b> from ' + senderName[current] +'...</center>'+
					'			</div>'+
					'		</div>'+
					'	</div>'+
					'	<div style="clear:both;"></div>'+
					'</div>'+
			'	</div>'+
			'	</span>'+
			'</div>'+
			'	</div>'+
		'<br />';
        $.post(acceptLink[current], function(data,status){
            if(/You have accepted the gift:/.test(data)) {
                var gift = data.substring(data.indexOf("You have accepted the gift:")+27);
                gift = $.trim(gift.substring(0,gift.indexOf(".<br/>")));
                accepted += "You got <b>" + itemName[current] + "</b> - " + gift + " - from " + senderName[current] +".<br/>";
                setTimeout( function() { current++; acceptGift();}, 3000); 
            }
        });
    }else{
        current = 0;
        findGiftID();
    }
}

                
function findGiftID(){
    for(var i = 0; i < itemName.length; i++){
        for(var k = 0; k < giftNames.length; k++){
            if(itemName[i] == giftNames[k]) 
                idForGift[i] = k;
        }
    }
    
    giftBack();
}

function giftBack(){
    if(current < itemName.length){
        times = times+1;
        var currentGift = Math.floor((Math.random()*giftNames.length));
       
        document.getElementById("results_main_wrapper").innerHTML = '<div class="results" style="background-image: url("https://castleagegame1-a.akamaihd.net/graphics/bg_main_middle.jpg");background-color:#D0B682;width:700px;">'+
					'<div class="result">'+
				'<span class="result_body">				<div style="width:700px;">'+
					'<div style="width:700px;height:20px;background-image:url("https://castleagegame1-a.akamaihd.net/graphics/gift_background.jpg");">'+
					'	<div style="clear:both;"></div>'+
					'	<div style="float:left;width:700px;height:20px;">'+
					'		<div style="width:700px;height:20px;">'+
					'			<div style="color:#000000;">'+
                    '				<center>Returning the favor to ' + senderName[current] + ' with <b>' + giftNames[currentGift] + '</b>....</center>'+
					'			</div>'+
					'		</div>'+
					'	</div>'+
					'	<div style="clear:both;"></div>'+
					'</div>'+
			'	</div>'+
			'	</span>'+
			'</div>'+
			'	</div>'+
		'<br />';
		var url = "https://web3.castleagegame.com/castle_ws/gift.php?selected_army%5B%5D=" + senderID[current] + '&action=send_non_facebook_gift&giftSelection=' + giftID[currentGift];
        $.post(url, function(data,status){   
            if(/You have sent /.test(data)) {
                accepted += "You sent <b>" + giftNames[currentGift] + "</b> to " + senderName[current] +".<br/>";
                setTimeout( function() { current++; giftBack();}, 3000); 
            }
        });
    }
    else {
        document.getElementById("results_main_wrapper").innerHTML = '<div class="results" style="background-image: url("https://castleagegame1-a.akamaihd.net/graphics/bg_main_middle.jpg");background-color:#D0B682;width:700px;">'+
					'<div class="result">'+
				'<span class="result_body">				<div style="width:700px;">'+
					'<div style="width:700px;height:'+40*senderID.length+'px;background-image:url("https://castleagegame1-a.akamaihd.net/graphics/gift_background.jpg");">'+
					'	<div style="clear:both;"></div>'+
					'	<div style="float:left;width:700px;height:'+40*senderID.length+'px;">'+
					'		<div style="width:700px;height:'+40*senderID.length+'px;">'+
					'			<div style="color:#000000;">'+
					'				<center>'+ accepted +'</center>'+
					'			</div>'+
					'		</div>'+
					'	</div>'+
					'	<div style="clear:both;"></div>'+
					'</div>'+
			'	</div>'+
			'	</span>'+
			'</div>'+
			'	</div>'+
		'<br />';
        //setTimeout( function() {check();}, 15000);
    }
    
}

//Updation of script
function checkUpdate() {
    GM_xmlhttpRequest({
        method : 'GET',
        url    : 'https://openuserjs.org/install/Yack/Castle_Age_Gift_Trading.user.js',
        onload : function( response ) {
            var remoteVersion = response.responseText.match(/^\/\/\s\@version\s+(\d+\.\d+)/m)[1];
            if( GM_info.script.version < remoteVersion ) {
                if( confirm( 'There is a newer version available.' + '\nClick OK to update' ) ) {
                    setTimeout( function() { unsafeWindow.location.href = 'https://openuserjs.org/install/Yack/Castle_Age_Gift_Trading.user.js'; }, 3000 );
                }
            }
            else {
                alert('No Updates for CA - Gift Trading');
            }
    }
    });
}

GM_registerMenuCommand('Accept and Return Different Gifts', check);
GM_registerMenuCommand('CA Gift Trade - Check for Updates', checkUpdate);