MY TEST 12345

By warakuni Uploaded Sep 20, 2009

Add Syntax Highlighting (this will take a few seconds, probably freezing your browser while it works)

// ==UserScript==
// @name         MafiaWars Gift Sender
// @namespace    
// @description  MafiaWars Gift Sender
// @copyright    2009 - Don Papy
// @version      2.3
// @include      http://apps.facebook.com/inthemafia/*
// @include      http://apps.new.facebook.com/inthemafia/*
// @contributor  Don Papy
// @contributor  Canis Lupis
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
// @unwrap
// ==/UserScript==


GM_registerMenuCommand('GiftSender - Show/Hide GiftSender', ToggleGiftSender);
GM_registerMenuCommand('GiftSender - Save Giftkey from Gifting page', getGiftKey);
GM_registerMenuCommand('GiftSender - Save Giftkey from Profile page', getGiftKeyFromProfile);
GM_registerMenuCommand('GiftSender - Save Recipient from Profile page', getRecipientFromProfile);
GM_registerMenuCommand('GiftSender - Save GiftKey + Recipient from Profile page', getBothFromProfile);
GM_registerMenuCommand('GiftSender - Change maximum Log length', setMaximumLog);
GM_registerMenuCommand('GiftSender - Quality vs. Speed of execution', setQorS);
GM_registerMenuCommand('GiftSender - Check for updates', updateScript);

var SCRIPT = {
  url: 'http://userscripts.org/scripts/source/55035.user.js',
  version: '2.3',
  build: '14',
  news:'New capability: sending entire Collection Pack.',
};

//======================================================================
// Enabling DEBUGGING functionality
//======================================================================

var GM_Debug = 1; //DEBUG

if(!GM_Debug) {
   var GM_log = function(){}; // disable GM_log functionality
}
else if(unsafeWindow.console){ //Firebug is available
   var GM_log = unsafeWindow.console.log; //log to firebug console
   var console = unsafeWindow.console; //enable the firebug console commands
}

//**********************************************************************************************
//  IMAGES USED IN SCRIPT (BASE64 ENCODED)
//**********************************************************************************************

var StartIMG = '<img src="data:image/gif;base64,R0lGODlhEAAQAMQAAP8A/2K1SIHOEXbIAIPTHZXbMIDRFnbIAXfJA33OEM/vqIbWJHrMC5HLf3jKB/D/3/X/6fn/8uz/1ej/zJjcRc7vpv3/+qHfVP///+T/xAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAAQABAAAAVqICCOZEk2QaqmTRlUSizHVTA21LXs/H5RLUCAQCRgikib0MA0WCzNpjKQqCYiWGt1yugyIGCIlzF1mB2P9OPsmCLeCIkc/p4e7ofJBI+fDv4DGYCDSg0Ch4iJh0FCBY6PkEo3KyuMJpcjIQA7'+ '" title="Start" width="16" height="16" BORDER=0/>';

var CloseIMG = '<img src="data:image/gif;base64,R0lGODlhEAAQANUAAP8A//////9fX/+Pj/9/f/93d/+Ojv9wcP90dP+Vlf97e/9tbf+Rkf+YmP+cnP+amv9paf9qav+EhP+Kiv+Cgv9nZ/+vr/+hof+Wlv+fn/+1tf+qqv+lpf+8vP+0tP91df+UlP/Bwf9lZf94eP9zc/+Dg/9xcf+2tv/Z2f/Y2P/V1f+Li/+dnf9ubv/X1/+Zmf/Nzf+AgP+Hh/9kZP+/v//Q0P+mpgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAAQABAAAAaOQIAQMBAYjYOhEiDwoFIuVc0iWDJhHZujgXlYaNWhIHTKbBMMw+SyCQ9emkwggDbMKQ9CUnDhOOYBdnMEEgVVAixngIMKBQiHDw11gASNCAeHGJOLjgcLhyBplICeEFUDJQMTjAVzCxAzSUwrMhSVna8VYUICEjGWnhG6VgIkIx8mLREiu0tFRwKyVtNWQQA7'+ '" title="Stop" width="16" height="16" BORDER=0/>';

var PauseIMG = '<img src="data:image/gif;base64,R0lGODlhEAAQAOYAAP8A/zaa/3O4/xal/6jd//L6//r9/87s/8bp/+r3/+Dz/////9bv/xel/xim/xun/xyn/1zA/1a+/0q5/y6u/yWr/x6o/3nL/0S3/yGp/6fd/xqn/2fE/zmz/zmy/2jF/yKq/4rS/27H/3bK/026/zOw/zGw/z+0/1q//0i4/0O2/0m5/3HI/zax/3fK/ySq/067/1O8/1G8/1m//y2u/z20/2HC/5DU/3vM/1C7/yis/x+o/zCv/6vf/3LI/4vS/yOq/zqz/23H/z+1/z60/zuz/zWx/1i+/1vA/2LC/2rF/33N/0u6/2bE/3PJ/yyu/3jL/2nF/y+v/yms/2TD/4nR/6re/xmm/2DC/ySr/3rM/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAAQABAAAAewgACCg4SFhAIBiYqJAoUBPQSRkRoaBFYBgwI3IThaFxdQLiNLP1WNAAFOPiwLCyJCrUpRH5ioHE1UBgY2WLoRSCi1ATNHEgUFMTLHMCRMwhMrKQkJGCrTQ0Q1wkVBHQoKLUbfJjxSwhQ0TwwMUzrrFVkvwkAgGQcHOxb3EBAPwhsbriBA4MDBwAYNBtQSMKChwwYOHljIUOEUKgolPJzAMCGHhAhJamVatMiioZODAgEAOw=='+ '" title="Close" width="16" height="16" BORDER=0/>';

//**********************************************************************************************
//  DEFINITION OF VARIABLES
//**********************************************************************************************
var giftSet = new Array();  //Order, Col or Loot, Master Group, Item Group, Item Name, Gift Cat, Gift ID
giftSet.push(
  new Array(0, "Loot", "CONSUMABLES", "", "Concealable Camera", 1, 62),
  new Array(1, "Loot", "CONSUMABLES", "", "Computer Set-Up", 1, 63),
  new Array(2, "Loot", "CONSUMABLES", "", "Untraceable Cell Phone", 1, 64),
  new Array(3, "Loot", "CONSUMABLES", "", "Blackmail Photos", 1, 65),
  new Array(4, "Loot", "CONSUMABLES", "", "Illegal Transaction Records", 1, 68),
  new Array(5, "Loot", "CONSUMABLES", "", "Politico Corrupto", 1, 245),
  new Array(6, "Loot", "SPECIAL LOOT", "4th of July", "Bayonet", 1, 223),
  new Array(7, "Loot", "SPECIAL LOOT", "4th of July", "Flintlock Pistols", 1, 222),
  new Array(8, "Loot", "SPECIAL LOOT", "4th of July", "Musket", 1, 226),
  new Array(9, "Loot", "SPECIAL LOOT", "4th of July", "Saber", 1, 227),
  new Array(10, "Loot", "SPECIAL LOOT", "4th of July", "Cannon", 1, 229),
  new Array(11, "Loot", "SPECIAL LOOT", "4th of July", "Tri-Point Hat", 1, 224),
  new Array(12, "Loot", "SPECIAL LOOT", "4th of July", "Davy Crocket Hat", 1, 255),
  new Array(13, "Loot", "SPECIAL LOOT", "4th of July", "Red Coat", 1, 228),
  new Array(14, "Loot", "NEW YORK LOOT", "Weapons", ".22 Pistol", 1, 1),
  new Array(15, "Loot", "NEW YORK LOOT", "Weapons", "Butterfly Knife", 1, 2),
  new Array(16, "Loot", "NEW YORK LOOT", "Weapons", "Brass Knuckles", 1, 3),
  new Array(17, "Loot", "NEW YORK LOOT", "Weapons", "9mm Semi-Automatic", 1, 4),
  new Array(18, "Loot", "NEW YORK LOOT", "Weapons", ".45 Revolver", 1, 5),
  new Array(19, "Loot", "NEW YORK LOOT", "Weapons", "Tactical Shotgun", 1, 6),
  new Array(20, "Loot", "NEW YORK LOOT", "Weapons", "C4", 1, 7),
  new Array(21, "Loot", "NEW YORK LOOT", "Weapons", "Automatic Rifle", 1, 9),
  new Array(22, "Loot", "NEW YORK LOOT", "Weapons", "Semi-Automatic Shotgun", 1, 10),
  new Array(23, "Loot", "NEW YORK LOOT", "Weapons", "Grenade Launcher", 1, 14),
  new Array(24, "Loot", "NEW YORK LOOT", "Weapons", ".50 Caliber Rifle", 1, 15),
  new Array(25, "Loot", "NEW YORK LOOT", "Weapons", "RPG Launcher", 1, 17),
  new Array(26, "Loot", "NEW YORK LOOT", "Weapons", "Napalm", 1, 20),
  new Array(27, "Loot", "NEW YORK LOOT", "Weapons", "Firebomb", 1, 61),
  new Array(28, "Loot", "NEW YORK LOOT", "Weapons", "Bookie\'s Holdout Pistol", 1, 71),
  new Array(29, "Loot", "NEW YORK LOOT", "Weapons", "BA-12 Assault Rifle (AR-15)", 1, 73),
  new Array(30, "Loot", "NEW YORK LOOT", "Armor", "Stab-Proof Vest", 1, 8),
  new Array(31, "Loot", "NEW YORK LOOT", "Armor", "Bodyguards", 1, 18),
  new Array(32, "Loot", "NEW YORK LOOT", "Armor", "Night Vision Goggles", 1, 19),
  new Array(33, "Loot", "NEW YORK LOOT", "Armor", "Lucky Shamrock Medallion", 1, 60),
  new Array(34, "Loot", "NEW YORK LOOT", "Armor", "Falsified Documents", 1, 74),
  new Array(35, "Loot", "NEW YORK LOOT", "Armor", "Federal Agent", 1, 78),
  new Array(36, "Loot", "NEW YORK LOOT", "Vehicles", "Armored Truck", 1, 11),
  new Array(37, "Loot", "NEW YORK LOOT", "Vehicles", "Armored Car", 1, 16),
  new Array(38, "Loot", "NEW YORK LOOT", "Vehicles", "Harley Davidson \"Fat Boy\" Motorcycle", 1, 67),
  new Array(39, "Loot", "NEW YORK LOOT", "Vehicles", "Luxury Yacht", 1, 69),
  new Array(40, "Loot", "NEW YORK LOOT", "Vehicles", "Prop plane", 1, 66),
  new Array(41, "Loot", "NEW YORK LOOT", "Vehicles", "GX9 (Porsche 911)", 1, 70),
  new Array(42, "Loot", "NEW YORK LOOT", "Vehicles", "Multi-Purpose Truck (Humvee)", 1, 72),
  new Array(43, "Loot", "NEW YORK LOOT", "Vehicles", "Private Jet", 1, 75),
  new Array(44, "Loot", "NEW YORK LOOT", "Vehicles", "Police Cruiser", 1, 76),
  new Array(45, "Loot", "NEW YORK LOOT", "Vehicles", "Armored Limousine", 1, 77),
  new Array(46, "Loot", "CUBA LOOT", "Weapons", "Garza 9", 1, 194),
  new Array(47, "Loot", "CUBA LOOT", "Weapons", "RA-92", 1, 195),
  new Array(48, "Loot", "CUBA LOOT", "Weapons", "M16A1", 1, 196),
  new Array(49, "Loot", "CUBA LOOT", "Weapons", "Ru-38 Pistol", 1, 197),
  new Array(50, "Loot", "CUBA LOOT", "Weapons", "Cane Knife", 1, 198),
  new Array(51, "Loot", "CUBA LOOT", "Weapons", "Para 322", 1, 199),
  new Array(52, "Loot", "CUBA LOOT", "Weapons", "Gaff Hook", 1, 200),
  new Array(53, "Loot", "CUBA LOOT", "Weapons", "Aquila HV.50 Sniper Rifle", 1, 202),
  new Array(54, "Loot", "CUBA LOOT", "Weapons", "ASC45 Conquistador", 1, 201),
  new Array(55, "Loot", "CUBA LOOT", "Weapons", "TNT", 1, 203),
  new Array(56, "Loot", "CUBA LOOT", "Weapons", "Canonazo", 1, 261),
  new Array(57, "Loot", "CUBA LOOT", "Armor", "Street Gang Member", 1, 204),
  new Array(58, "Loot", "CUBA LOOT", "Armor", "Camouflage Body Armor", 1, 205),
  new Array(59, "Loot", "CUBA LOOT", "Armor", "Guerilla Squad", 1, 174),
  new Array(60, "Loot", "CUBA LOOT", "Vehicles", "Mara Serpiente", 1, 175),
  new Array(61, "Loot", "CUBA LOOT", "Vehicles", "Chucho FAV", 1, 176),
  new Array(62, "Loot", "CUBA LOOT", "Vehicles", "Ocelot Armored Truck", 1, 177),
  new Array(63, "Loot", "CUBA LOOT", "Vehicles", "Montaine 320", 1, 178),
  new Array(64, "Loot", "CUBA LOOT", "Vehicles", "Cigarette Boat", 1, 179),
  new Array(65, "Loot", "CUBA LOOT", "Vehicles", "Mini-Sub", 1, 180),
  new Array(66, "Loot", "CUBA LOOT", "Vehicles", "SI-14 Cargo Plane", 1, 181),
  new Array(67, "Loot", "CUBA LOOT", "Vehicles", "Hu-9 Helicopter", 1, 182),
  new Array(68, "Loot", "CUBA LOOT", "Vehicles", "Armored State Car", 1, 183),
  new Array(69, "Loot", "CUBA LOOT", "Vehicles", "Track Loader", 1, 262),
  new Array(70, "Collections", "NEW YORK COLLECTIONS", "Diamonds", "Eight of Diamonds", 0, 1036),
  new Array(71, "Collections", "NEW YORK COLLECTIONS", "Diamonds", "Nine of Diamonds", 0, 1037),
  new Array(72, "Collections", "NEW YORK COLLECTIONS", "Diamonds", "Ten of Diamonds", 0, 1038),
  new Array(73, "Collections", "NEW YORK COLLECTIONS", "Diamonds", "Jack of Diamonds", 0, 1039),
  new Array(74, "Collections", "NEW YORK COLLECTIONS", "Diamonds", "Queen of Diamonds", 0, 1040),
  new Array(75, "Collections", "NEW YORK COLLECTIONS", "Diamonds", "King of Diamonds", 0, 1041),
  new Array(76, "Collections", "NEW YORK COLLECTIONS", "Diamonds", "Ace of Diamonds", 0, 1042),
  new Array(77, "Collections", "NEW YORK COLLECTIONS", "Hearts", "Eight of Hearts", 0, 1043),
  new Array(78, "Collections", "NEW YORK COLLECTIONS", "Hearts", "Nine of Hearts", 0, 1044),
  new Array(79, "Collections", "NEW YORK COLLECTIONS", "Hearts", "Ten of Hearts", 0, 1045),
  new Array(80, "Collections", "NEW YORK COLLECTIONS", "Hearts", "Jack of Hearts", 0, 1046),
  new Array(81, "Collections", "NEW YORK COLLECTIONS", "Hearts", "Queen of Hearts", 0, 1047),
  new Array(82, "Collections", "NEW YORK COLLECTIONS", "Hearts", "King of Hearts", 0, 1048),
  new Array(83, "Collections", "NEW YORK COLLECTIONS", "Hearts", "Ace of Hearts", 0, 1049),
  new Array(84, "Collections", "NEW YORK COLLECTIONS", "Sculptures", "Rat Sculpture", 0, 1022),
  new Array(85, "Collections", "NEW YORK COLLECTIONS", "Sculptures", "Sheep Sculpture", 0, 1023),
  new Array(86, "Collections", "NEW YORK COLLECTIONS", "Sculptures", "Rooster Sculpture", 0, 1024),
  new Array(87, "Collections", "NEW YORK COLLECTIONS", "Sculptures", "Monkey Sculpture", 0, 1025),
  new Array(88, "Collections", "NEW YORK COLLECTIONS", "Sculptures", "Tiger Sculpture", 0, 1026),
  new Array(89, "Collections", "NEW YORK COLLECTIONS", "Sculptures", "Snake Sculpture", 0, 1027),
  new Array(90, "Collections", "NEW YORK COLLECTIONS", "Sculptures", "Dragon Sculpture", 0, 1028),
  new Array(91, "Collections", "NEW YORK COLLECTIONS", "Poker Chips", "White Poker Chip", 0, 1029),
  new Array(92, "Collections", "NEW YORK COLLECTIONS", "Poker Chips", "Brown Poker Chip", 0, 1030),
  new Array(93, "Collections", "NEW YORK COLLECTIONS", "Poker Chips", "Red Poker Chip", 0, 1031),
  new Array(94, "Collections", "NEW YORK COLLECTIONS", "Poker Chips", "Blue Poker Chip", 0, 1032),
  new Array(95, "Collections", "NEW YORK COLLECTIONS", "Poker Chips", "Green Poker Chip", 0, 1033),
  new Array(96, "Collections", "NEW YORK COLLECTIONS", "Poker Chips", "Purple Poker Chip", 0, 1034),
  new Array(97, "Collections", "NEW YORK COLLECTIONS", "Poker Chips", "Gold Poker Chip", 0, 1035),
  new Array(98, "Collections", "NEW YORK COLLECTIONS", "Clubs", "Eight of Clubs", 0, 1050),
  new Array(99, "Collections", "NEW YORK COLLECTIONS", "Clubs", "Nine of Clubs", 0, 1051),
  new Array(100, "Collections", "NEW YORK COLLECTIONS", "Clubs", "Ten of Clubs", 0, 1052),
  new Array(101, "Collections", "NEW YORK COLLECTIONS", "Clubs", "Jack of Clubs", 0, 1053),
  new Array(102, "Collections", "NEW YORK COLLECTIONS", "Clubs", "Queen of Clubs", 0, 1054),
  new Array(103, "Collections", "NEW YORK COLLECTIONS", "Clubs", "King of Clubs", 0, 1055),
  new Array(104, "Collections", "NEW YORK COLLECTIONS", "Clubs", "Ace of Clubs", 0, 1056),
  new Array(105, "Collections", "NEW YORK COLLECTIONS", "Boxing", "Hand Tape", 0, 1085),
  new Array(106, "Collections", "NEW YORK COLLECTIONS", "Boxing", "Gloves", 0, 1086),
  new Array(107, "Collections", "NEW YORK COLLECTIONS", "Boxing", "Headgear", 0, 1087),
  new Array(108, "Collections", "NEW YORK COLLECTIONS", "Boxing", "Boxing Trunks", 0, 1088),
  new Array(109, "Collections", "NEW YORK COLLECTIONS", "Boxing", "Speed Bag", 0, 1089),
  new Array(110, "Collections", "NEW YORK COLLECTIONS", "Boxing", "Heavy Bag", 0, 1090),
  new Array(111, "Collections", "NEW YORK COLLECTIONS", "Boxing", "Boxing Ring", 0, 1091),
  new Array(112, "Collections", "NEW YORK COLLECTIONS", "Cigars", "Ebony Cigar", 0, 1001),
  new Array(113, "Collections", "NEW YORK COLLECTIONS", "Cigars", "Sky Cigar", 0, 1002),
  new Array(114, "Collections", "NEW YORK COLLECTIONS", "Cigars", "Rose Cigar", 0, 1003),
  new Array(115, "Collections", "NEW YORK COLLECTIONS", "Cigars", "Ivory Cigar", 0, 1004),
  new Array(116, "Collections", "NEW YORK COLLECTIONS", "Cigars", "Turquoise Cigar", 0, 1005),
  new Array(117, "Collections", "NEW YORK COLLECTIONS", "Cigars", "Gold Cigar", 0, 1006),
  new Array(118, "Collections", "NEW YORK COLLECTIONS", "Cigars", "Royal Cigar", 0, 1007),
  new Array(119, "Collections", "NEW YORK COLLECTIONS", "Spades", "Eight of Spades", 0, 1057),
  new Array(120, "Collections", "NEW YORK COLLECTIONS", "Spades", "Nine of Spades", 0, 1058),
  new Array(121, "Collections", "NEW YORK COLLECTIONS", "Spades", "Ten of Spades", 0, 1059),
  new Array(122, "Collections", "NEW YORK COLLECTIONS", "Spades", "Jack of Spades", 0, 1060),
  new Array(123, "Collections", "NEW YORK COLLECTIONS", "Spades", "Queen of Spades", 0, 1061),
  new Array(124, "Collections", "NEW YORK COLLECTIONS", "Spades", "King of Spades", 0, 1062),
  new Array(125, "Collections", "NEW YORK COLLECTIONS", "Spades", "Ace of Spades", 0, 1063),
  new Array(126, "Collections", "NEW YORK COLLECTIONS", "Billiards", "One Ball", 0, 1092),
  new Array(127, "Collections", "NEW YORK COLLECTIONS", "Billiards", "Two Ball", 0, 1093),
  new Array(128, "Collections", "NEW YORK COLLECTIONS", "Billiards", "Three Ball", 0, 1094),
  new Array(129, "Collections", "NEW YORK COLLECTIONS", "Billiards", "Four Ball", 0, 1095),
  new Array(130, "Collections", "NEW YORK COLLECTIONS", "Billiards", "Five Ball", 0, 1096),
  new Array(131, "Collections", "NEW YORK COLLECTIONS", "Billiards", "Cue Ball", 0, 1097),
  new Array(132, "Collections", "NEW YORK COLLECTIONS", "Billiards", "Eight Ball", 0, 1098),
  new Array(133, "Collections", "NEW YORK COLLECTIONS", "Rings", "Topaz Ring", 0, 1008),
  new Array(134, "Collections", "NEW YORK COLLECTIONS", "Rings", "Opal Ring", 0, 1009),
  new Array(135, "Collections", "NEW YORK COLLECTIONS", "Rings", "Amethyst Ring", 0, 1010),
  new Array(136, "Collections", "NEW YORK COLLECTIONS", "Rings", "Emerald Ring", 0, 1011),
  new Array(137, "Collections", "NEW YORK COLLECTIONS", "Rings", "Sapphire Ring", 0, 1012),
  new Array(138, "Collections", "NEW YORK COLLECTIONS", "Rings", "Ruby Ring", 0, 1013),
  new Array(139, "Collections", "NEW YORK COLLECTIONS", "Rings", "Diamond Ring", 0, 1014),
  new Array(140, "Collections", "NEW YORK COLLECTIONS", "Ties", "Solid Tie", 0, 1064),
  new Array(141, "Collections", "NEW YORK COLLECTIONS", "Ties", "Striped Tie", 0, 1065),
  new Array(142, "Collections", "NEW YORK COLLECTIONS", "Ties", "Checked Tie", 0, 1066),
  new Array(143, "Collections", "NEW YORK COLLECTIONS", "Ties", "Geometric Tie", 0, 1067),
  new Array(144, "Collections", "NEW YORK COLLECTIONS", "Ties", "Dot Tie", 0, 1068),
  new Array(145, "Collections", "NEW YORK COLLECTIONS", "Ties", "Paisley Tie", 0, 1069),
  new Array(146, "Collections", "NEW YORK COLLECTIONS", "Ties", "Knitted Tie", 0, 1070),
  new Array(147, "Collections", "NEW YORK COLLECTIONS", "Paintings", "Warhol Painting", 0, 1015),
  new Array(148, "Collections", "NEW YORK COLLECTIONS", "Paintings", "Cezanne Painting", 0, 1016),
  new Array(149, "Collections", "NEW YORK COLLECTIONS", "Paintings", "Matisse Painting", 0, 1017),
  new Array(150, "Collections", "NEW YORK COLLECTIONS", "Paintings", "Van Gogh Painting", 0, 1018),
  new Array(151, "Collections", "NEW YORK COLLECTIONS", "Paintings", "Dali Painting", 0, 1019),
  new Array(152, "Collections", "NEW YORK COLLECTIONS", "Paintings", "Monet Painting", 0, 1020),
  new Array(153, "Collections", "NEW YORK COLLECTIONS", "Paintings", "Rembrandt Painting", 0, 1021),
  new Array(154, "Collections", "NEW YORK COLLECTIONS", "Cufflinks", "Silver Cufflinks", 0, 1071),
  new Array(155, "Collections", "NEW YORK COLLECTIONS", "Cufflinks", "Gold Cufflinks", 0, 1072),
  new Array(156, "Collections", "NEW YORK COLLECTIONS", "Cufflinks", "Amber Cufflinks", 0, 1073),
  new Array(157, "Collections", "NEW YORK COLLECTIONS", "Cufflinks", "Jasper Cufflinks", 0, 1074),
  new Array(158, "Collections", "NEW YORK COLLECTIONS", "Cufflinks", "Agate Cufflinks", 0, 1075),
  new Array(159, "Collections", "NEW YORK COLLECTIONS", "Cufflinks", "Onyx Cufflinks", 0, 1076),
  new Array(160, "Collections", "NEW YORK COLLECTIONS", "Cufflinks", "Pearl Cufflinks", 0, 1077),
  new Array(161, "Collections", "NEW YORK COLLECTIONS", "Barber", "Barber Pole", 0, 1099),
  new Array(162, "Collections", "NEW YORK COLLECTIONS", "Barber", "Razor", 0, 1100),
  new Array(163, "Collections", "NEW YORK COLLECTIONS", "Barber", "Brush", 0, 1101),
  new Array(164, "Collections", "NEW YORK COLLECTIONS", "Barber", "Seat", 0, 1102),
  new Array(165, "Collections", "NEW YORK COLLECTIONS", "Barber", "Towel", 0, 1103),
  new Array(166, "Collections", "NEW YORK COLLECTIONS", "Barber", "Scissors", 0, 1104),
  new Array(167, "Collections", "NEW YORK COLLECTIONS", "Barber", "Cream", 0, 1105),
  new Array(168, "Collections", "NEW YORK COLLECTIONS", "Great Race Horses", "Mill Reef", 0, 1078),
  new Array(169, "Collections", "NEW YORK COLLECTIONS", "Great Race Horses", "Sea Bird", 0, 1079),
  new Array(170, "Collections", "NEW YORK COLLECTIONS", "Great Race Horses", "Arkle", 0, 1080),
  new Array(171, "Collections", "NEW YORK COLLECTIONS", "Great Race Horses", "Golden Miller", 0, 1081),
  new Array(172, "Collections", "NEW YORK COLLECTIONS", "Great Race Horses", "St Simon", 0, 1082),
  new Array(173, "Collections", "NEW YORK COLLECTIONS", "Great Race Horses", "Ormonde", 0, 1083),
  new Array(174, "Collections", "NEW YORK COLLECTIONS", "Great Race Horses", "Eclipse", 0, 1084),
  new Array(175, "Collections", "NEW YORK COLLECTIONS", "Daily Chance", "Bingo Card", 0, 1106),
  new Array(176, "Collections", "NEW YORK COLLECTIONS", "Daily Chance", "Deck of Cards", 0, 1107),
  new Array(177, "Collections", "NEW YORK COLLECTIONS", "Daily Chance", "Dice", 0, 1108),
  new Array(178, "Collections", "NEW YORK COLLECTIONS", "Daily Chance", "Roulette Wheel", 0, 1109),
  new Array(179, "Collections", "NEW YORK COLLECTIONS", "Daily Chance", "Slot Machine", 0, 1110),
  new Array(180, "Collections", "NEW YORK COLLECTIONS", "Daily Chance", "Craps Table", 0, 1111),
  new Array(181, "Collections", "NEW YORK COLLECTIONS", "Daily Chance", "Baccarat Shoe", 0, 1112),
  new Array(182, "Collections", "CUBA COLLECTIONS", "Rum Drinks", "Pina Colada", 0, 2001),
  new Array(183, "Collections", "CUBA COLLECTIONS", "Rum Drinks", "Hurricane", 0, 2002),
  new Array(184, "Collections", "CUBA COLLECTIONS", "Rum Drinks", "Bahama Mama", 0, 2003),
  new Array(185, "Collections", "CUBA COLLECTIONS", "Rum Drinks", "Mojito", 0, 2004),
  new Array(186, "Collections", "CUBA COLLECTIONS", "Rum Drinks", "Rum Runner", 0, 2005),
  new Array(187, "Collections", "CUBA COLLECTIONS", "Rum Drinks", "Long Island Ice Tea", 0, 2006),
  new Array(188, "Collections", "CUBA COLLECTIONS", "Rum Drinks", "Cuba Libre", 0, 2007),
  new Array(189, "Collections", "CUBA COLLECTIONS", "Tropical Fruits", "Banana", 0, 2008),
  new Array(190, "Collections", "CUBA COLLECTIONS", "Tropical Fruits", "Lime", 0, 2009),
  new Array(191, "Collections", "CUBA COLLECTIONS", "Tropical Fruits", "Pineapple", 0, 2010),
  new Array(192, "Collections", "CUBA COLLECTIONS", "Tropical Fruits", "Papaya", 0, 2011),
  new Array(193, "Collections", "CUBA COLLECTIONS", "Tropical Fruits", "Coconut", 0, 2012),
  new Array(194, "Collections", "CUBA COLLECTIONS", "Tropical Fruits", "Passion Fruit", 0, 2013),
  new Array(195, "Collections", "CUBA COLLECTIONS", "Tropical Fruits", "Dragon Fruit", 0, 2014),
  new Array(196, "Collections", "CUBA COLLECTIONS", "Entertainers", "Magician", 0, 2015),
  new Array(197, "Collections", "CUBA COLLECTIONS", "Entertainers", "Fan Dancer", 0, 2016),
  new Array(198, "Collections", "CUBA COLLECTIONS", "Entertainers", "Comedian", 0, 2017),
  new Array(199, "Collections", "CUBA COLLECTIONS", "Entertainers", "Band Leader", 0, 2018),
  new Array(200, "Collections", "CUBA COLLECTIONS", "Entertainers", "Cabaret Singer", 0, 2019),
  new Array(201, "Collections", "CUBA COLLECTIONS", "Entertainers", "Crooner", 0, 2020),
  new Array(202, "Collections", "CUBA COLLECTIONS", "Entertainers", "Burlesque Dancer", 0, 2021),
  new Array(203, "Collections", "CUBA COLLECTIONS", "Tropical Fish", "Pufferfish", 0, 2022),
  new Array(204, "Collections", "CUBA COLLECTIONS", "Tropical Fish", "Sergeant Major", 0, 2023),
  new Array(205, "Collections", "CUBA COLLECTIONS", "Tropical Fish", "Yellowtail Snapper", 0, 2024),
  new Array(206, "Collections", "CUBA COLLECTIONS", "Tropical Fish", "Great Barracuda", 0, 2025),
  new Array(207, "Collections", "CUBA COLLECTIONS", "Tropical Fish", "Queen Angelfish", 0, 2026),
  new Array(208, "Collections", "CUBA COLLECTIONS", "Tropical Fish", "Reef Shark", 0, 2027),
  new Array(209, "Collections", "CUBA COLLECTIONS", "Tropical Fish", "Blue Marlin", 0, 2028),
  new Array(210, "Collections", "CUBA COLLECTIONS", "Beards", "Garibaldi", 0, 2029),
  new Array(211, "Collections", "CUBA COLLECTIONS", "Beards", "Hulihee", 0, 2030),
  new Array(212, "Collections", "CUBA COLLECTIONS", "Beards", "Vandyke", 0, 2031),
  new Array(213, "Collections", "CUBA COLLECTIONS", "Beards", "Mutton Chops", 0, 2032),
  new Array(214, "Collections", "CUBA COLLECTIONS", "Beards", "Soul Patch", 0, 2033),
  new Array(215, "Collections", "CUBA COLLECTIONS", "Beards", "French Fork", 0, 2034),
  new Array(216, "Collections", "CUBA COLLECTIONS", "Beards", "Fidel", 0, 2035),
  new Array(217, "Extra", "BOOSTS", "Fight defense", "(+3) Extra Pair of Eyes - BUY", 2, 25),
  new Array(218, "Extra", "BOOSTS", "Fight defense", "(+10) Tripwire - DIAMONDS", 2, 1),
  new Array(219, "Extra", "BOOSTS", "Fight defense", "(+18) Bulldog - POKER CHIPS", 2, 4),
  new Array(220, "Extra", "BOOSTS", "Fight defense", "(+25) Injunction - TIES", 2, 11),
  new Array(221, "Extra", "BOOSTS", "Fight defense", "(+30) Shave & A Haircut - BARBER", 2, 14),
  new Array(222, "Extra", "BOOSTS", "Fight defense", "(+35) Sandbag Wall - ENTERTAINERS", 2, 18),
  new Array(223, "Extra", "BOOSTS", "Job energy costs", "(-3) Cappuccino - HEARTS", 2, 2),
  new Array(224, "Extra", "BOOSTS", "Job energy costs", "(-5)Problem Solver - CLUB FLUSH", 2, 5),
  new Array(225, "Extra", "BOOSTS", "Job energy costs", "(-8) Fixer - CIGARS", 2, 7),
  new Array(226, "Extra", "BOOSTS", "Job energy costs", "(-10) Blueprints - RINGS", 2, 10),
  new Array(227, "Extra", "BOOSTS", "Job energy costs", "(-16) Inside Tip - HORSES", 2, 15),
  new Array(228, "Extra", "BOOSTS", "Job energy costs", "(-18) Boosted Smoothie - FRUITS", 2, 17),
  new Array(229, "Extra", "BOOSTS", "Attack", "(+5) Hot Coffee - BUY", 2, 26),
  new Array(230, "Extra", "BOOSTS", "Attack", "(+15) Semi-Pro Boxer - BOXING", 2, 6),
  new Array(231, "Extra", "BOOSTS", "Attack", "(+20) Sting Grenade - SPADES", 2, 8),
  new Array(232, "Extra", "BOOSTS", "Attack", "(+35) Corporate Muscle - CUFFLINKS", 2, 13),
  new Array(233, "Extra", "BOOSTS", "Attack", "(+30) Flaming Shot - RUM DRINKS", 2, 16),
  new Array(234, "Extra", "BOOSTS", "Attack", "(+40) Blowfish Dart - FISH", 2, 19),
  new Array(235, "Extra", "BOOSTS", "Robbing defense", "(+5) Mutt - BUY", 2, 27),
  new Array(236, "Extra", "BOOSTS", "Robbing defense", "(+15) Alarm System - SCULPTURES", 2, 3),
  new Array(237, "Extra", "BOOSTS", "Robbing defense", "(+27) Bouncer - BILLIARDS", 2, 9),
  new Array(238, "Extra", "BOOSTS", "Robbing defense", "(+37) Motion Detector - PAINTINGS", 2, 12),
  new Array(239, "Extra", "BOOSTS", "Robbing defense", "(+60) Hobo Lookout - BEARD", 2, 20)
);


var CollectionSet = new Array();  //Order, GiftCategory, Collection, Item Name, + Gift ID's )
CollectionSet.push(
  new Array(0, 0, "NEW YORK COLLECTIONS", "Diamonds", 1036, 1037, 1038, 1039, 1040, 1041, 1042),
  new Array(1, 0, "NEW YORK COLLECTIONS", "Hearts", 1043, 1044, 1045, 1046, 1047, 1048, 1049),
  new Array(2, 0, "NEW YORK COLLECTIONS", "Sculptures", 1022, 1023, 1024, 1025, 1026, 1027, 1028),
  new Array(3, 0, "NEW YORK COLLECTIONS", "Poker Chips", 1029, 1030, 1031, 1032, 1033, 1034, 1035),
  new Array(4, 0, "NEW YORK COLLECTIONS", "Clubs", 1050, 1051, 1052, 1053, 1054, 1055, 1056),
  new Array(5, 0, "NEW YORK COLLECTIONS", "Boxing", 1085, 1086, 1087, 1088, 1089, 1090, 1091),
  new Array(6, 0, "NEW YORK COLLECTIONS", "Cigars", 1001, 1002, 1003, 1004, 1005, 1006, 1007),
  new Array(7, 0, "NEW YORK COLLECTIONS", "Spades", 1057, 1058, 1059, 1060, 1061, 1062, 1063),
  new Array(8, 0, "NEW YORK COLLECTIONS", "Billiards", 1092, 1093, 1094, 1095, 1096, 1097, 1098),
  new Array(9, 0, "NEW YORK COLLECTIONS", "Rings", 1008, 1009, 1010, 1011, 1012, 1013, 1014),
  new Array(10, 0, "NEW YORK COLLECTIONS", "Ties", 1064, 1065, 1066, 1067, 1068, 1069, 1070),
  new Array(11, 0, "NEW YORK COLLECTIONS", "Paintings", 1015, 1016, 1017, 1018, 1019, 1020, 1021),
  new Array(12, 0, "NEW YORK COLLECTIONS", "Cufflinks", 1071, 1072, 1073, 1074, 1075, 1076, 1077),
  new Array(13, 0, "NEW YORK COLLECTIONS", "Barber", 1099, 1100, 1101, 1102, 1103, 1104, 1105),
  new Array(14, 0, "NEW YORK COLLECTIONS", "Great Race Horses", 1078, 1079, 1080, 1081, 1082, 1083, 1084),
  new Array(15, 0, "CUBA COLLECTIONS", "Rum Drinks", 2001, 2002, 2003, 2004, 2005, 2006, 2007),
  new Array(16, 0, "CUBA COLLECTIONS", "Tropical Fruits", 2008, 2009, 2010, 2011, 2012, 2013, 2014),
  new Array(17, 0, "CUBA COLLECTIONS", "Entertainers", 2015, 2016, 2017, 2018, 2019, 2020, 2021),
  new Array(18, 0, "CUBA COLLECTIONS", "Tropical Fish", 2022, 2023, 2024, 2025, 2026, 2027, 2028),
  new Array(19, 0, "CUBA COLLECTIONS", "Beards", 2029, 2030, 2031, 2032, 2033, 2034, 2035),
  new Array(20, 0, "CUBA COLLECTIONS", "Daily Chance", 1106, 1107, 1108, 1109, 1110, 1111, 1112),
  //BELOW YOU CAN ADD YOUR OWN CUSTOM MADE PACKS
  new Array(21, 1, "LOOT COLLECTIONS", "4th of July", 222, 223, 224, 225, 226, 227, 228, 229),
	new Array(22, 1, "LOOT COLLECTIONS", "Top 5 Crap Loot", 1, 2, 3, 4, 5),
	new Array(23, 1, "LOOT COLLECTIONS", "Top 20 Crap Loot", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 60, 61),
	new Array(24, 1, "LOOT COLLECTIONS", "Top 5 Strong Loot", 261, 262, 174, 200, 201),
	new Array(25, 1, "LOOT COLLECTIONS", "Consumables 6-Pack", 62, 63, 64, 65, 68, 245)
 );


var Quantity, LootText, Loot, LootCat, GiftKey, Recipient, myAction;
var gift_url,last_url=gift_url,chosentype;
var FirstGiftID,NextGiftID,LastGiftID,currentColItem,ColArrayFirstGift=4; 
//ColArrayFirstGift is the position of first gift ID in CollectionSet, starting with 0 for first variable
var wait,gifts=1,sent=0,retries=0,run=1,g,i,s='';

var reportlog = [];

var maximumlog=GM_getValue("Maximumlog", "5");
var wait=GM_getValue("Delaytime", "0");
var qualityfactor=GM_getValue("QFactor", "1");

var xmlHTTP=get_xmlHTTP();
  if(!xmlHTTP){
    alert('Your browser does not support AJAX sending.');
    return;
  }

var gs_running = 
'<style type="text/css">'+
  '.messages img{margin:0 3px;vertical-align:top};'+
  '.messages iframe{border:0;margin:0 3px};'+
  '#start{display:none};'+
  '#pause{display:inline};'+
  '#close{display:inline};'+      
'</style>'+
'<table class="messages">'+
  '<tr><td width="20%">Gifts sent:</td><td id="gifts"></td>'+
  '<td align="right" style="text-align:right;font-size:0.8em">'+
  ' Special credits to: <a href="http://www.spockholm.com/mafia/bookmarklets.php" target="_top">Spockholm Mafia Tools</a> - '+
    '<a href="#" id="play">'+StartIMG+'</a>'+
    '<a href="#" id="pause">'+PauseIMG+'</a>'+
    '<a href="#" id="close">'+CloseIMG+'</a>'+
  '</td></tr>'+
  '<tr><td>Status:</td><td id="status"></td><td align="right" style="text-align:right;">Delay: <span id="delay">'+
  wait+'</span> sec (<a href="#" id="increase">+</a> / <a href="#" id="decrease">-</a>)</td></tr>'+
  '<tr><td valign="top">Log:</td><td colspan="2" id="log"></td></tr>'+
'</table>';


//**********************************************************************************************
//  MAIN FUNCTION: STARTING ACTIONS AFTER THE WINDOW LOADING EVENT HAS COMPLETED
//**********************************************************************************************

$(function(){ // The DOM is ready, document finished loading.
  AddButtonToFaceBookTitleBar();
  ShowGiftSender();
  InstallRemoveButtonEvent();
  DailyUpdateCheck();
  CheckParameters();
});   

function ShowGiftSender(){
  PrepareGiftSender(); // Build the Gift Sender GUI
  DisplayGiftKey(); // Read the GiftKey from a cookie and show it in the form if we have one
};


//**********************************************************************************************
//  SUPPORTING FUNCTIONS
//**********************************************************************************************

//==============================================================================================
//  Titlebar FaceBook: Show MafiaWars Button
//==============================================================================================

function AddButtonToFaceBookTitleBar(){
	        $('#fb_menu_inbox').parent().append("<li id='GSBarButton' class='fb_menu'>"+
	        "<a id='GSLink' class='fb_menu_link'>MafiaWars</a>"+
					"<div class='fb_menu_dropdown clearfix' id='fb_menu_mw_dropdown'>"+
						"<div class='fb_menu_item'><p class='fb_menu_separator'><b>Interface</b></p></div>"+
						"<div id='GSToggle' class='fb_menu_item'>"+
							"<a class='fb_menu_item_link' href='#'>Toggle GiftSender</a>"+
						"</div>"+
						"<div class='fb_menu_separator'></div>"+
						"<div class='fb_menu_item'><p class='fb_menu_separator'><b>Gifting page</b></p></div>"+
						"<div id='GSGiftkey' class='fb_menu_item'>"+
							"<a class='fb_menu_item_link' href='#'>Get & Store Giftkey</a>"+
						"</div>"+
						"<div class='fb_menu_separator'></div>"+
						"<div class='fb_menu_item'><p class='fb_menu_separator'><b>Profile page</b></p></div>"+
						"<div id='GSGiftProfilekey' class='fb_menu_item'>"+
							"<a class='fb_menu_item_link' href='#'>Get & Store Giftkey</a>"+
						"</div>"+
						"<div id='GSGiftRecipient' class='fb_menu_item'>"+
							"<a class='fb_menu_item_link' href='#'>Get & Store UserID</a>"+
						"</div>"+
						"<div id='GSGiftKeyAndRecient' class='fb_menu_item'>"+
							"<a class='fb_menu_item_link' href='#'>Get & Store Giftkey + UserID</a>"+
						"</div>"+
						"<div class='fb_menu_separator'></div>"+
						"<div class='fb_menu_item'><p class='fb_menu_separator'><b>Parameters</b></p></div>"+
						"<div id='GSMaxLog' class='fb_menu_item'>"+
							"<a class='fb_menu_item_link'>Maximum log items</a>"+
						"</div>"+
						"<div id='GSDelay' class='fb_menu_item'>"+
							"<a class='fb_menu_item_link'>Delay between gifts</a>"+
						"</div>"+
						"<div id='GSQorS' class='fb_menu_item'>"+
							"<a class='fb_menu_item_link'>Quality vs. Speed</a>"+
						"</div>"+
						//***********************************************************
						// CONTROLE FUNCTION
						"<div id='GSTest' class='fb_menu_item'>"+
							"<a class='fb_menu_item_link'>Check Collection ID's</a>"+
						"</div>"+
						//***********************************************************
						"<div class='fb_menu_separator'></div>"+
						"<div class='fb_menu_item'><p class='fb_menu_separator'><b>Updates</b></p></div>"+
						"<div id='GSUpdate' class='fb_menu_item'>"+
							"<a class='fb_menu_item_link'>Script Version Check</a>"+
						"</div>"+
					"</div>");

        
					$('#GSToggle').click(function() {
						ToggleGiftSender();
					});
					$('#GSGiftkey').click(function() {
						getGiftKey();
					});
					$('#GSGiftProfilekey').click(function() {
						getGiftKeyFromProfile();
					});
					$('#GSGiftRecipient').click(function() {
						getRecipientFromProfile();
					});

					$('#GSGiftKeyAndRecient').click(function() {
            getBothFromProfile();
					});
					
					$('#GSMaxLog').click(function() {
						setMaximumLog();
					});
					
					$('#GSDelay').click(function() {
						setDelay();
					});
					
					$('#GSQorS').click(function() {
						setQorS();
					});

					$('#GSUpdate').click(function() {
						updateScript('man');
					});

					$('#GSTest').click(function() {
						Test();
					});
				};

function ToggleGiftSender(){
        if(!$("#gs").length > 0 ){
          ShowGiftSender();
        }else{
          $('#gsbutton').remove();           
          $('#gs').remove();           
          $('#gs_reportframe').remove();           
        }
};

//===================================================
//  Function mainly used during development of script
//===================================================

function Test(){
					
					var almsg="";
					var checkcol=0;

					var reply = prompt("Choose a collection to check (number from 0-25):", checkcol);

          LootText = CollectionSet[reply][3] ;
          FirstGiftID=parseInt(CollectionSet[reply][ColArrayFirstGift]);
          var ColArrayLastGift=CollectionSet[reply].length;
          LastGiftID=parseInt(CollectionSet[reply][ColArrayLastGift]);

					for (i=ColArrayFirstGift;i<ColArrayLastGift;i++){
						almsg += "Collection Item "+ (i-3) +": giftID = "+CollectionSet[reply][i]+" \n";
					}

      alert ("Number of items in collection "+LootText+" = "+ (ColArrayLastGift-ColArrayFirstGift) + "\n\n" + almsg);
};


//==============================================================================================
//  Remove GiftSender Toggle Button from Titlebar FaceBook when we leave MafiaWars
//==============================================================================================

function InstallRemoveButtonEvent(){
    window.addEventListener("unload", function(e) {
       $('#GSBarButton').remove();
    }, false);
};


//==============================================================================================
//  Preparing the GiftSender GUI
//==============================================================================================

function PrepareGiftSender(){
    var myfavlist ="";
    
    var buttonframecontent =
        '<div id="gsbutton" style="padding: 5px; vertical-align: middle;>'+
          '<div id="gsbframe">'+
            '<table width="100%">'+
              '<tr>'+  
              // OPTIONS
                '<td width="125px">'+
                  '<input id="viewtool" class="sexy_button" type="button" value="Show Options" style="width: 120px;"/>'+
                '</td>'+
              // FILLER
                '<td id="versionnote"><center>MafiaWars Gift Sender - Version: <B>'+ SCRIPT.version +'</B> - Build: <B>'+ SCRIPT.build + '</B>' +
                '</center></td>'+
              // UPDATE
                '<td width="125px">'+
                  '<input id="updatetool" class="sexy_button" type="button" value="Update" style="width: 120px;"/>'+
                '</td>'+
              '</tr>'+
            '</table>'+
          '</div>'+
        '</div>'
    ;
 
////////////////////////////////////////////////////////////////////
    
    var gifthtml = ""; var curVault = ""; var curSubVault = "";

    for (i=0;i<giftSet.length;i++){
      if (giftSet[i][2] != "" && giftSet[i][2] != curVault){
        curVault = giftSet[i][2];
        gifthtml += '<optgroup class="vault" label="' + curVault + '"></optgroup>';
      }
      if (giftSet[i][3] != "" && giftSet[i][3] != curSubVault){
        curSubVault = giftSet[i][3];
        gifthtml += '<optgroup class="subvault" label="' + curSubVault + '"></optgroup>';
      }
      gifthtml += '<option value="' + giftSet[i][0] + '">' + giftSet[i][4] + '</option>';
    }

////////////////////////////////////////////////////////////////////
    
    var collectionhtml = ""; var curcolVault="";

    for (i=0;i<CollectionSet.length;i++){
    
      if (CollectionSet[i][2] != curcolVault){
        curcolVault = CollectionSet[i][2];
        collectionhtml += '<optgroup class="vault" label="' + curcolVault + '"></optgroup>';
      }
    
      collectionhtml += '<option value="' + CollectionSet[i][0] + '">' + CollectionSet[i][3] + '</option>';
    }

////////////////////////////////////////////////////////////////////

    var myconfigcontent = 
      '<style type="text/css">'+
          '.vault {background-color: #F90;font-style: normal;font-weight: bold;font-size: 13px;line-height: normal;}'+
          '.subvault {background-color: #CCC;font-style: normal;font-weight: bold;}'+  
      '</style>'+
      
      '<div id="gs" class="tab_box_content" style="padding: 5px; margin-bottom: 5px; vertical-align: middle; display:none;">'+
          '<div id="gs_configframe">'+
            '<form id="gsform" name="gsform" method="post" action="">'+
              '<table width="100%" cellpadding=2>'+
                '<tr><td colspan="5" bgcolor="black"><strong style="font-size: 16px; color: #FFD927;">Multi-gift sender:</strong>'+
                '</td></tr><tr valign="middle">'+
                  '<td height="35" style="font-size: 11px;">FaceBookID (or link):'+
                '<input id="City" name="iCity" type="hidden" value="1" /></td>'+
                '<td height="35" style="font-size: 11px;">'+
                '<input id="UID" name="iUID" type="text" /></td>'+
                '<td height="35" style="font-size: 11px;">Gift key:</td>'+
                '<td height="35" style="font-size: 11px;">'+
                '<input id="GiftKey" name="iGiftKey" type="text" size=30 /></td>'+
                '<td height="35" style="font-size: 11px;">'+
                '<input id="scookie" class="sexy_button" type="button" value="Store" style="width: 60px;"/>'+
                '<input id="ecookie" class="sexy_button" type="button" value="Erase" style="width: 60px;"/>'+
                '</td></tr><tr>'+
                '<td width="130" height="35" style="font-size: 11px;">Loot Quantity:</td>'+
                '<td height="35"> '+
                  '<input id="QTY" name="sQTY"  type="text" value="1" ></td>'+
                '<td height="35" style="font-size: 11px;"> Loot item:</td>'+
                '<td height="35">'+
                '<select id="Loot" name="sLoot">'+gifthtml +'</select></td>'+
                '<td height="35">'+
                '<input id="sendbutton" class="sexy_button" type="button" value="Send Gift(s)" style="width: 120px;"/></td>'+
                '</tr>'+
                '<tr><td colspan="2"></td>'+
                '<td height="35" style="font-size: 11px;"> Collection:</td>'+
                '<td height="35">'+
                '<select id="Coll" name="sColl">'+collectionhtml +'</select></td>'+
                '<td height="35">'+
                '<input id="sendcolbutton" class="sexy_button" type="button" value="Send Package" style="width: 120px;"/></td>'+
                '</tr>'+
              '</table>'+
            '</form>'+
            '<p>Enter the FaceBook ID or Profilelink for your gift-recipient and add your GiftKey'+
            ' (if not done yet) to the respective fields.<br>'+
            'By using the STORE-button, your GiftID will be stored, and read next time from a cookie.<br><br>'+
            '<b>2009 - Converted from existing Gift Bookmarklets for MafiaWars by Don Papy with contribution '+
            'of Canis Lupis.</b><br>(Credit to Spockholm, Vern and Bobbie Heartrate for their excellent work).</p>'+
          '</div>'+
      '</div>' 
    ;  


    var mytoolcontent = '<div id="gs_sendframe"></div>';
    var myresultscontent = '<div id="gs_reportframe" class="tab_box_content"></div>';
  
   $("#app10979261223_mw_masthead").parent().append(buttonframecontent);
   $("#app10979261223_mw_masthead").parent().append(myconfigcontent);
   $("#app10979261223_mw_masthead").parent().append(myresultscontent);
   $("#gs").append(mytoolcontent);
   

        //=======================================================
        // Add actions to form buttons
        //=======================================================

        $('#viewtool').bind('click', function() {
          ToggleTool();
        });

        $('#updatetool').bind('click', function() {
          updateScript('man');
        });

        $('#scookie').bind('click', function() {
          SetTheCookie();
        });

        $('#ecookie').bind('click', function() {
          DeleteCookie();
        });        

        $('#sendbutton').bind('click', function() {
          
          //=======================================================
          // Read parameters from form to determine gift action
          //=======================================================
          sent=0;
          chosentype="singleitems";
          Quantity = $('#QTY').val();
          currentColItem=0;
          LastGiftID=Quantity;      
          LootText = $('#Loot option:selected').text() ;
          Loot = giftSet[$('#Loot').attr('value')][6];
          LootCat = giftSet[$('#Loot').attr('value')][5];

          InitiateTransfer("singleitems");

        });       
        
        $('#sendcolbutton').bind('click', function() {
          
          //=======================================================
          // Read parameters from form to determine gift action
          //=======================================================
          sent=0;
          chosentype="collection";
          LootText = $('#Coll option:selected').text() ;
          var tFirstGiftID=CollectionSet[$('#Coll').attr('value')][ColArrayFirstGift];
          FirstGiftID=parseInt(tFirstGiftID);
          var ColArrayLastGift=CollectionSet[$('#Coll').attr('value')].length;
          var tLastGiftID= CollectionSet[$('#Coll').attr('value')][ColArrayLastGift];
          LastGiftID=parseInt(tLastGiftID);
          Quantity=ColArrayLastGift-ColArrayFirstGift;
          InitiateTransfer("collection");

        });              
               
}


function InitiateTransfer(chosentype){

          $("#gs_configframe").hide();

          //=======================================================
          // Convert the input in the recipient field to a valid ID
          //=======================================================

          var URL = $("#UID").val(); 
        
          URLinput = removeSpaces(URL); ;

            if (IsNumeric(URLinput)){
              Recipient = URLinput; 
            }else{
              //Get UserID from URL using regular expression
              var rex1 = new RegExp('[\&|\?][id|user|of|viewas|from|u]+\=[0-9]+');
              //var rex1 = new RegExp('[\&|\?][a-z]+\=[0-9]+');
              var rex2 = new RegExp('[0-9]+');
              var StringMatch = rex1.exec(URLinput);
              Recipient = rex2.exec(StringMatch); 
            }

          //=======================================================
          // Read parameters from form to determine gift action
          //=======================================================

          GiftKey = $('#GiftKey').val();

          
          //=======================================================
          // Write the chosen action to the gs_reportframe DIV 
          //=======================================================
          var myError;
          
          if(!Recipient.length > 0 ){
               myAction = ("<p style= 'color: #FF0000; padding-left: 5px'><b>Invalid recipient!</b></p>");
               myError=1;
          }else{
               myError=0;
            if(chosentype=="singleitems"){
               myAction = ("<p style= 'color: #FFD927; padding-left: 5px'> Executing transfer of "+ Quantity + " <b>" + LootText + 
               "(s)</b> - (LootID="+ Loot +") to recipient with ID <b>"+ Recipient + "</b></p>");
            }else if(chosentype=="collection"){
               myAction = ("<p style= 'color: #FFD927; padding-left: 5px'> Executing transfer of <b>" + LootText + 
               "-collection</b> to recipient with ID <b>"+ Recipient + "</b></p>");
            }
          }
          
          $("#gs_reportframe").html(myAction);
          
          //======================================================================
          // Start sending and write the responses action to the gs_sendframe DIV 
          //======================================================================
          if(myError==1){
              //ERROR DETECTED - HALT!
              $("#gs_sendframe").html("<p style= 'color: #FFD927;'>Error detected, script halted.</p>"); 
              $("#gs_reportframe").html("<p style= 'color: #FF0000; padding-left:5px'><b>Execution stopped due to error.</b></p>");        
              return;
          }else{
              //START SENDING
              $("#gs_sendframe").html("<p style= 'color: #FFD927;'>Responses will be written here...</p>");
              
                //Send single loot, collection or boost items
                //*******************************************
                if(chosentype=="singleitems"){
                    gift_url="http://apps.facebook.com/inthemafia/remote/html_server.php?xw_controller=gift&recipients[0]="+
                    Recipient+"&gift_category="+LootCat+"&gift_id="+Loot+"&gift_key="+GiftKey+"&xw_action=send"; 
                }else{
                //Send complete collections
                //*******************************************
                currentColItem=ColArrayFirstGift;
                qualityfactor="0";
                }
              StartSending();
          }
}

//==============================================================================================
// Function to Show/Hide the Giftsender Tool
//==============================================================================================

function ToggleTool()
{
  $("#gs").toggle(); 
  if ($("#viewtool").attr("value")=="Show Options"){
    $("#viewtool").attr("value","Hide Options");
  }else{
    $("#viewtool").attr("value","Show Options");
  }
  $("#gs_reportframe").html("");
}


//==============================================================================================
// Functions to initiate sending the chosen gifts to the defined recipient
//
// Credit to Spockholm for his Bookmarklet that used this code for an almost similar purpose
// Some of the code has been changed so it could work with the JQuery library
//==============================================================================================

function StartSending()
{ 
  sent=0;
		if(GM_getValue("Delaytime")){wait=GM_getValue("Delaytime");
}else{wait=0; GM_setValue("Delaytime", "0");};
	run=1;

  $("#gs_sendframe").html(gs_running);
  $("#gs_sendframe").show();        
	$("#delay").html(wait);

  msg('Preparing to send...');

  $("#play").hide();
  $("#pause").show();BindPause();
  $("#close").show();BindClose();
  BindIncrease();
  BindDecrease();
  
  if(chosentype=="singleitems"){
    request(gift_url);
  }else if(chosentype=="collection"){

		LootCat = CollectionSet[$('#Coll').attr('value')][1];
		NextGiftID=parseInt(CollectionSet[$('#Coll').attr('value')][currentColItem]);
    
    gift_url="http://apps.facebook.com/inthemafia/remote/html_server.php?xw_controller=gift&recipients[0]="+
    Recipient+"&gift_category="+LootCat+"&gift_id="+NextGiftID+"&gift_key="+GiftKey+"&xw_action=send";    
    request(gift_url);
  }

}

//==============================================================================================
// Gift Sending Loop and AJAX functions
//==============================================================================================

function request(url) {
  if (sent >= Quantity || currentColItem > LastGiftID) { 
    qualityfactor=GM_getValue("QFactor");
    msg('Finished.');
    log('Transfer complete.'); 
        $("#gs_reportframe").html("<p style= 'color: #FFD927; padding-left: 5px'> Transfer of <b>" + LootText + "(s)</b> - to recipient with ID <b>"+ Recipient + "</b> completed!</p>");        
    $("#pause").hide();
    $("#start").hide();
    $("#gs_configframe").show();

  }
  else if (run == 1) {
    xmlHTTP.onreadystatechange=state_change;
    xmlHTTP.open('GET',url,true);
    xmlHTTP.send(null);
  } else {
    msg('Paused...');
  }
  
  if(chosentype=="singleitems"){
    last_url=url;
  }else if(chosentype=="collection"){
    currentColItem++;
		NextGiftID=parseInt(CollectionSet[$('#Coll').attr('value')][currentColItem]);
    last_url=gift_url="http://apps.facebook.com/inthemafia/remote/html_server.php?xw_controller=gift&recipients[0]="+
    Recipient+"&gift_category="+LootCat+"&gift_id="+NextGiftID+"&gift_key="+GiftKey+"&xw_action=send";     
  }
}
//************************************************************************************************
function repeat_gift() {
    function f () {
    msg('Sending gift again... (<a href="'+last_url+'">url</a>)');
    request(gift_url);
    }
    msg('Waiting for ' + wait + ' seconds...');
    setTimeout(f, wait * 1000);
}
//************************************************************************************************
function msg(s) {
  $("#status").html(s);
}
//************************************************************************************************
function log(s) {
reportlog.unshift(s);
if (reportlog.length > maximumlog){
  reportlog.pop();
}
var writelog =reportlog.join("<br />");

if(chosentype=="singleitems"){
  $("#gifts").html('Transferred '+sent+' of '+Quantity);
}else{
  $("#gifts").html('Transferred '+sent+' of '+LootText+' collection');
}

  $("#log").html(writelog);
}
//************************************************************************************************
function state_change(){

if(qualityfactor=="1"){
		//SEND ITEMS USING QUALITY over SPEED
		if(xmlHTTP.readyState==4){
			if(xmlHTTP.status==200){
				s='';
				s=xmlHTTP.responseText;

				if(/You gave the/.test(s)) {
					i=/You gave the (.+) to (.+)<\/td>/.exec(s);

					sent++;
					log('(Gift '+sent+'): Sent '+i[1]+' to '+i[2]);
					repeat_gift();
				}
				else if (/Error while loading page from/.test(s)) {
					msg('Mafia Wars overloaded, waiting 30 seconds...');
					log('Mafia Wars overloaded, waiting 30 seconds...');
					setTimeout(function(){ request(last_url); },30000);
					return; 
				}
				else if (/have enough of that/.test(s) && chosentype=="singleitems") {
					run = 0;
					msg('Stopped...');
					log('<span class="bad">Error!</span> You do not have enough of that item to give');
					$("#gs_reportframe").html("<p style= 'color: #FF0000; padding-left:5px'><b>Transaction halted - Not enough items available.</b></p>");       
					$("#pause").hide();
					$("#start").hide();
				}
				else if(/Some recipient(s) were invalid users./.test(s)) {
					run = 0;
					msg('Stopped...');
					log('<span class="bad">Error!</span> Some recipient(s) were invalid users');
					$("#gs_reportframe").html("<p style= 'color: #FF0000; padding-left:5px'><b>Transaction halted - Invalid recipient detected.</b></p>");       
					$("#pause").hide();
					$("#start").hide();
				}
			}
			else{
				retry("Problem retrieving XML data");
				return;
			}
		}
		retries=0;
	}else{
		//SEND ITEMS USING SPEED over QUALITY
		if(xmlHTTP.readyState==3){  
				xmlHTTP.abort();  
				sent++;  

        if(chosentype=="singleitems"){
                  log('(Gift '+sent+'): Sent to recipient with ID: '+Recipient);
        }else{
                  log('(Item '+sent+' of '+LootText+' Collection): transfer to userID: '+Recipient);
        }

				repeat_gift();  
}  
retries=0;  	}
}
//************************************************************************************************
function retry(s){
  if(retries>5){
    msg(s+'; not retrying any more.');
  }
  else{
    retries++;
    msg(s+'; retry #'+retries+'...');
    request(last_url);
  }
}
//************************************************************************************************
function get_xmlHTTP(){
  if(window.XMLHttpRequest)
    return new XMLHttpRequest();
  if(window.ActiveXObject)
    return new ActiveXObject('Microsoft.XMLHTTP');
  return null;
}


//==============================================================================================
// Bind actions to buttons in gs_sendframe DIV
//==============================================================================================

function BindIncrease()
{
    $('#increase').bind('click', function() {
      wait++;
      $("#delay").html(wait);
      return false;
    });
}

function BindDecrease()
{
    $('#decrease').bind('click', function() {
      if(wait <= 0) {
        wait = 0; 
      }
      else {
        wait--;
      }
      $("#delay").html(wait);
      return false;
    });
}

function BindPause()
{
      $('#pause').bind('click', function() {
        run = 0;
        msg('Paused...');
        $("#pause").hide();
        $("#play").show();BindPlay();
        $("#close").show();BindClose();
        $("#gs_reportframe").html("<p style= 'color: #FF0000; padding-left:5px'><b>Execution paused upon your request.</b></p>");        
        return false;
      });
}

function BindPlay()
{
        $('#play').bind('click', function() {
        run = 1;
        $("#gs_sendframe").html(gs_running);
        $("#pause").show();BindPause();
        $("#play").hide();
        $("#close").show();BindClose();
        msg('Resume gifting... (<a href="'+last_url+'">url</a>)');
        $("#gs_reportframe").html("<p style= 'color: #FFD927; padding-left: 5px'> Resuming transfer of remaining <b>" + LootText + 
               "(s)</b> - (LootID="+ Loot +") to recipient with ID <b>"+ Recipient + "</b></p>");       
        request(gift_url);
        return false;
      });
}

function BindClose()
{
      $('#close').bind('click', function() {
        run = 0; Quantity=0; Loot=""; Recipient="";
        $("#gs_sendframe").hide();//CLOSE THE WINDOW HERE
        $("#gs_configframe").show();
        $("#gs_reportframe").html("<p style= 'color: #FF0000; padding-left: 5px'><b>Gift sending stopped upon your request. Initiate new transaction by clicking SEND button.</b></p>");       
        delete xmlHTTP['onreadystatechange'];
        return false;
      });
      
      $('#increase').bind('click', function() {
        wait++;
        $("#delay").html(wait);
        return false;
      });
}


//==============================================================================================
// Cookie and parameter functions
//==============================================================================================

function CheckParameters(){

	if(GM_getValue("QFactor")){
		qualityfactor=GM_getValue("QFactor");	
	}else{
		qualityfactor="1";
		GM_setValue("QFactor", "1");		
	}
	
	if(GM_getValue("Maximumlog")){
		maximumlog=GM_getValue("Maximumlog");	
	}else{
		maximumlog="5";
		GM_setValue("Maximumlog", "5");		
	}
	
	if(GM_getValue("Delaytime")){
		wait=GM_getValue("Delaytime");	
	}else{
		wait="0";
		GM_setValue("Delaytime", "5");		
	}
	
	ReportParameters();
}

function ReportParameters(){
	if(qualityfactor=="1"){
				$("#gs_reportframe").html("<p style= 'color: #FFFF00; padding-left:5px'>Script running in <b>QUALITY</b> mode - Delay is set to <b>"+wait+" seconds</b> - Maximum Logsize set to <b>"+maximumlog+" items.</b></p>");  
	}else{
				$("#gs_reportframe").html("<p style= 'color: #FFFF00; padding-left:5px'>Script running in <b>SPEED</b> mode - Delay is set to <b>"+wait+" seconds</b> - Maximum Logsize set to <b>"+maximumlog+" items.</b></p>");  
	}
}

// Set maximum length of Log (How many reported items are shown in the log frame)

    function setMaximumLog(){
      var reply = prompt("Please enter the number of maximum number of items you wish to see in the log window:", maximumlog);
      GM_setValue("Maximumlog", reply);
      maximumlog=GM_getValue("Maximumlog");
			ReportParameters();
    }

    function setDelay(){
      var reply = prompt("Please enter the amount of seconds you wish as default delay between gifts:", wait);
      GM_setValue("Delaytime", reply);
      wait=GM_getValue("Delaytime");
			$("#delay").html(wait);
			ReportParameters();
    }


		function setQorS(){
      var reply = prompt("Select Quality(1) or Speed(0) as parameter for sending gifts:", qualityfactor);
      GM_setValue("QFactor", reply);
      qualityfactor=GM_getValue("QFactor");
			ReportParameters();
		}

// Cookie read and write functions

    function getCookieVal (offset) 
       {
       var endstr = document.cookie.indexOf (";", offset);
       if (endstr == -1)
          endstr = document.cookie.length;
       return unescape(document.cookie.substring(offset, endstr));
       }

    function GetCookie (CookieKey) 
       {
       var arg = CookieKey + "=";
       var alen = arg.length;
       var clen = document.cookie.length;
       var i = 0;
       while (i < clen) 
          {
          var j = i + alen;
          if (document.cookie.substring(i, j) == arg)
             return getCookieVal (j);
          i = document.cookie.indexOf(" ", i) + 1;
          if (i == 0) break; 
          }
       return null;
       }

    function SetCookie (value) 
       {
       var argv = SetCookie.arguments;
       var argc = SetCookie.arguments.length;
       var expires = (argc > 2) ? argv[2] : null;
       var path = (argc > 3) ? argv[3] : null;
       var domain = (argc > 4) ? argv[4] : null;
       var secure = (argc > 5) ? argv[5] : false;
       document.cookie = argv[0] + "=" + argv[1] +
            ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
            ((path == null) ? "" : ("; path=" + path)) +
            ((domain == null) ? "" : ("; domain=" + domain)) +
            ((secure == true) ? "; secure" : "");
       }

    function DeleteCookie () 
       {
       var exp = new Date();
       exp.setTime (exp.getTime() - 1000000000);  // This cookie is history (changed -1 to make it previous time)
       var cval = GetCookie ('GiftCode');
        document.cookie = "GiftCode=" + cval + "; expires=" + exp.toGMTString();
        alert("GiftCode=" + cval + "; expires=" + exp.toGMTString());
        $("#GiftKey").val("");
        var cval = GetCookie ('GiftRecipient');
        document.cookie = "GiftRecipient=" + cval + "; expires=" + exp.toGMTString();
        $("#UID").val("");
      alert("Your GiftKey cookies has been deleted.");
      alert(GetCookie('GiftCode'));
       }

    function DisplayGiftKey()
       {
         if(GetCookie('GiftCode') != null){
            $("#GiftKey").val(GetCookie('GiftCode')); 
         }else{
            $("#GiftKey").val("No GiftKey Cookie found!!!"); 
         }
         if(GetCookie('GiftRecipient') != null){
            $("#UID").val(GetCookie('GiftRecipient'));
          }

       }

    function SetTheCookie()
       {
       if($("#GiftKey").val().length != 0)  
          {
          var expdate = new Date (); 
          expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * 365)); 
          SetCookie('GiftCode', $("#GiftKey").val(), expdate);  
          alert('GiftID cookie set to: ' + $("#GiftKey").val() + '.');
          } 
       else 
          {
          alert('You must enter your GiftKey first. You can retrieve it from the Gifting page,'+
          ' or a Profile page using the commands in the MafiaWars menu in the Title Bar, or enter it manually.');
          }
       if($("#UID").val().length != 0)  
          {
          var expdate = new Date (); 
          expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * 365)); 
          SetCookie('GiftRecipient', $("#UID").val(), expdate);  
          } 

          return false;
       }


//==============================================================================================
// Convert and extract the FaceBook ID from a profile link (if needed)
//==============================================================================================

  function removeSpaces(string) {
   return string.split(' ').join('');
  }
  
  function IsNumeric(sText)
  
  {
     var ValidChars = "0123456789";
     var IsNumber=true;
     var Char;
   
     for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
       {
       IsNumber = false;
       }
      }
     return IsNumber;
     
  } 

//==============================================================================================
// Get Giftkey from Gift-page and/or recipient ID + store in cookie for retrieval
//==============================================================================================

function getGiftKey()
{
  var expdate = new Date (); 
  expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * 365)); 
  
  var giftKey = "";
	giftKey = $("#app10979261223_gift_key").attr("value");
	
	if (giftKey==undefined){
		alert("Please open your Gifting page and run this command again");
	}else{
		alert("Detected Giftkey:"  + giftKey + ". Now storing value in cookie.");
		SetCookie('GiftCode', giftKey, expdate);  
		DisplayGiftKey();
	}
}

function getGiftKeyFromProfile(){
  var expdate = new Date (); 
  expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * 365)); 
  
  var giftKey = "";

try{
  
	var match=/gift_key=([0-9a-f]+)/.exec(document.body.innerHTML).toString();
	var comma = match.indexOf(",");
	comma++;
	var giftKey = match.substring(comma);

  }

catch(err){
		alert("Can't find giftkey on this page.");
    return false;

  }
    SetCookie('GiftCode', giftKey, expdate);  
    DisplayGiftKey();
}

function getRecipientFromProfile(){
  var expdate = new Date (); 
  expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * 365)); 

  var giftRecipient = "";

    var content=document.getElementById('app10979261223_content_row');
    var as=content.getElementsByTagName('a');
    for(i=0;i<as.length;i++)
    {
      if(as[i].innerHTML=='Profile')
      {
        var match=/[;&]user=(\d+)/.exec(as[i].href).toString();
        var comma = match.indexOf(",");
        comma++;
        var giftRecipient = match.substring(comma);
      }
    }

  if(giftRecipient!==""){   
      SetCookie('GiftRecipient', giftRecipient, expdate);  
      DisplayGiftKey();
        if($("#gs").css("display") == "none") {
					ToggleTool();
				}
		$("#gs_reportframe").html("<p style= 'color: #FFFF00; padding-left:5px'>Recipient Cookie set to: <b>"+giftRecipient+"</b></p>");  

  }else{
      alert("No valid Recipient ID found. Please make sure you are on a profile page of a mafiafriend to run this command.");
      return false;
  }

}

function getBothFromProfile(){
	getGiftKeyFromProfile();	
	getRecipientFromProfile();
}

//======================================================================
//	Update the script (Credits to Richard Gibson; ms99 and blannie)
//======================================================================

function updateScript(utype) {
var today = new Date();
GM_setValue('GiftSenderUpdaterLastCheck', String(today)); 

	GM_log("Preparing version check for script on "+SCRIPT.url); //DEBUG

    GM_xmlhttpRequest({
      method: 'GET',
      url: SCRIPT.url + '?source', // don't increase the 'installed' count; just for checking
      onload: function(result) {
        if (result.status != 200) {
          return;
        }
        if (!result.responseText.match(/build:\s+'(\d+)/)) return;
        var theOtherBuild = parseInt(RegExp.$1);
        var runningBuild = parseInt(SCRIPT.build);
				GM_log("Current build installed is: "+runningBuild); //DEBUG
				
        var theOtherVersion = result.responseText.match(/@version\s+([\d.]+)/)? RegExp.$1 : '';
				//BETA VERSION DETECTED
        if (theOtherBuild < runningBuild) {
          if(utype=='man'){        
						if (window.confirm('It seems that you have a beta version of the GiftSender script (build ' + runningBuild + ') installed.\n\nClick OK to DOWNGRADE to the most recent official release (version: ' + theOtherVersion + ' - build: '+theOtherBuild+ ').\n\nAn automated update-check will be done again in 24 hours.\n\n')) {window.location.href = SCRIPT.url;}return;
					}else{
							$("#versionnote").append("</p><center><font style='color: #FF9900;'><B>Daily check:</B> BETA version detected. Click update to install current release.</font></center>");
					}					
				//NEW RELEASE DETECTED
        } else if (theOtherBuild > runningBuild || theOtherVersion != SCRIPT.version) {
          if(utype=='man'){        
						if (window.confirm('Version ' + theOtherVersion + ' - build: '+theOtherBuild+ ' is available!\n' +SCRIPT.news+ '\nDo you want to upgrade?' + '\n')) {
							window.location.href = SCRIPT.url;}
					}else{
							$("#versionnote").append("</p><center><font style='color: #FF9900;'><B>Daily check:</B> Version " + theOtherVersion + " - build: "+theOtherBuild+ " is available! Click update to install.</font>"+SCRIPT.news+"</center>");
					}					
        //VERSION IS CURRENT
        } else {
          if(utype=='man'){
            alert('You already have the latest version.');
          return;
          }else{
            $("#versionnote").append("</p><center><font style='color: #FF9900;'><B>Daily check:</B> Your installed version is current.</font></center>");
          }
        }
      }
    });
}


function DailyUpdateCheck(){
var lastupdatecheck = GM_getValue("GiftSenderUpdaterLastCheck", "never");
    var today = new Date();
    var one_day = 24 * 60 * 60 * 1000;
    if(lastupdatecheck != 'never'){
      today = today.getTime();
      var lastupdatecheck = new Date(lastupdatecheck).getTime();
      var interval = (today - lastupdatecheck) / one_day; 
      if(interval >= 1){
        updateScript('auto');
      }else{
        }
    }else{
      updateScript('auto');
    }
}