// DECLARE GLOBALS
var gCutPaste = '';
var gbTraffic = false;
var gbHasUpdated = false;

jQuery.sweetmodal = function(options,callback){
	var $ = jQuery;
	$('#sweetmodal').remove();
	$('BODY').prepend('<div id="sweetmodal" />');
	var oModal = $('#sweetmodal')
		.append(options.html)
		.append('<div style="clear:both"><br /><br /><br /><br /></div><table width="100%" style="position:absolute;bottom:5px;"><tr><td style="text-align:center" id="sweetmodal-buttons"></td></tr></table>')
		.css({
			'font-family':'sans-serif',
			'font-weight':'normal',
			'color':'#000',
			'display':'none',
			'background-color':'#FFF',
			'overflow':'hidden',
			'border':'15px solid rgba(0,0,0,0.2)',
			'-moz-background-clip':'padding',
			'-webkit-background-clip':'padding',
			'background-clip':'padding-box',
			'padding':'15px',
			'position':'absolute',
			'padding-bottom':'10px',
			'-webkit-border-radius':'20px',
			'-moz-border-radius':'20px',
			'border-radius':'20px',
			'z-index':'9999',
			'width':'300px !important',
			'width':'auto',
			'min-width':'300px',
			'height':'150px !important',
			'height':'auto',
			'min-height':'15px',
			'font-size':'13px'
		});
	if ($.browser.msie) {
		oModal.css({
			'border':'5px ridge #FFF'
		});
	}
	setTimeout("jQuery('#sweetmodal .hasfocus').click().focus();clearTimeout();",400);
	var oWin = $(window);
	var nTop = Math.abs(((oWin.height() - oModal.outerHeight()) / 2) + oWin.scrollTop());
	var nLeft = Math.abs(((oWin.width() - oModal.outerWidth()) / 2) + oWin.scrollLeft());
	oModal.css({
		'position':'absolute',
		'top':nTop,
		'left':nLeft
	});
	if (options.css) {
		oModal.css(options.css);
	}
	if (options.fixed === false) {
		// do nothing
	} else {
		oModal.css({
			'position':'fixed',
			'top':Math.abs(nTop - oWin.scrollTop()),
			'left':nLeft
		});
	}
	if (options.buttons) {
		for (var i = 0; i < options.buttons.length; i++) {
			$('#sweetmodal-buttons').append('<a href="">' + options.buttons[i] + '</a>');
		}
	} else {
		$('#sweetmodal-buttons').append('<a href="">OK</a>');
	}
	$('#sweetmodal P').css('margin-top',0);
	var sStyle = '';
	sStyle += 'font-weight:bold;';
	sStyle += 'text-align:center;';
	sStyle += 'font-family:sans-serif;';
	sStyle += 'display:inline-block;';
	sStyle += 'height:30px;';
	sStyle += 'line-height:30px;';
	sStyle += 'margin:2px;';
	sStyle += 'padding-left:15px;';
	sStyle += 'padding-right:15px;';
	sStyle += 'font-size:13px;';
	sStyle += '-webkit-border-radius:4px;';
	sStyle += '-moz-border-radius:4px;';
	sStyle += '-o-border-radius:4px;';
	sStyle += '-ms-border-radius:4px;';
	sStyle += 'border-radius:4px;';
	sStyle += '-webkit-box-shadow:1px 1px 2px rgba(160, 160, 160, 0.3);';
	sStyle += '-moz-box-shadow:1px 1px 2px rgba(160, 160, 160, 0.3);';
	sStyle += 'box-shadow:1px 1px 2px rgba(160, 160, 160, 0.3);';
	sStyle += 'border:1px solid #BBB;';
	sStyle += 'cursor:pointer;';
	sStyle += 'text-decoration:none;';
	sStyle += 'min-height:1%;';
	sStyle += 'background:#eaeaea;';
	sStyle += 'color:#111;';
	sStyle += 'text-shadow:1px 1px 1px rgba(255, 255, 255, 0.75);';
	sStyle += 'filter:"progid:DXImageTransform.Microsoft.gradient(startColorstr=\'#ffffffff\',endColorstr=\'#ffdddddd\')";';
	sStyle += '-ms-filter:"progid:DXImageTransform.Microsoft.gradient(startColorstr=\'#ffffffff\',endColorstr=\'#ffdddddd\')";';
	sStyle += 'background-image:-moz-linear-gradient(top, #ffffff, #dddddd);';
	sStyle += 'background-image:-webkit-gradient(linear, 0% 0%, 0% 100%, from(#ffffff), to(#dddddd));';
	sStyle += 'background-image:-webkit-linear-gradient(#ffffff, #dddddd);';
	sStyle += 'background-image:-o-linear-gradient(#ffffff, #dddddd);';
	sStyle += 'background-image:linear-gradient(top, #ffffff 0%, #dddddd 100%);';
	sStyle += 'opacity:.95;';
	sStyle += '-ms-filter:"alpha(opacity=95)";';
	sStyle += 'filter:alpha(opacity=95);';
	sStyle += '-khtml-opacity:.95;';
	sStyle += '-moz-opacity:.95;';
	sStyle += 'min-width:60px;';
	$('#sweetmodal-buttons A')
	.attr('style',sStyle)
	.click(function(e){
		e.preventDefault();
		$(this).css('color','#111');
		if (callback){
			callback($(this).text());
		}
		oModal.remove();
		return false;
	}).hover(function(){
		$(this).css({
			'border':'1px solid #999',
			'opacity':'1',
			'-ms-filter':'"alpha(opacity=100)"',
			'filter':'alpha(opacity=100)',
			'-khtml-opacity':'1',
			'-moz-opacity':'1'
		});
	},function(){
		$(this).css({
			'border':'1px solid #BBB',
			'opacity':'0.95',
			'-ms-filter':'"alpha(opacity=95)"',
			'filter':'alpha(opacity=95)',
			'-khtml-opacity':'0.95',
			'-moz-opacity':'0.95'
		});
	});
	oModal.fadeIn('fast',function(){
		return $(this);
	});
	return oModal;
}

function spyders_selectItem(sID){
	var $ = jQuery;
	var sFld = '#' + $('#' + sID).attr('rel');
	var sVal = $('#' + sID).val();
	$(sFld + ' option[selected]').removeAttr('selected');
	$(sFld + " option[value='" + sVal + "']").attr('selected','selected');
}

function spyders_updateCutPaste(o){
	var $ = jQuery;
	gCutPaste = $('#fldCutPaste').val();
}

function spyders_adjustList(sName,s) {
	var $ = jQuery;
	// MAKE LINE-DELIMINIATED NO MATTER WHAT FORMAT RECEIVED
	s = s.split('"').join("'");
	s = s.split(';').join(',');
	s = s.split('  ').join(' ');
	s = s.split(',   ').join(', ');
	s = s.split(',  ').join(', ');
	s = s.split(', ').join(',');
	s = s.split("\r\n").join("\n");
	s = s.split("\r").join("\n");
	s = s.split(',').join("\n");
	s = s.split("\n\n").join("\n");
	s = s.split("\n\n").join("\n");
	s = s + "\n";
	// LOOP THROUGH THE LIST TO CREATE NEW DIVS
	var asItems = s.split("\n");
	var nCount = asItems.length;
	var sItem = '';
	var s = '';
	$('.multiselect[rel="' + sName + '"]').html('');
	for(var i = 0; i < nCount; i++) {
		try {sItem = asItems[i];}catch(e){}
		sItem = $.trim(sItem);
		if (!sItem) {
			continue;
		}
		s += '<div> <input type="checkbox" id="' + sName + '_' + (i+1) + '" name="' + sName + '[]" value="' + sItem + '">';
		s += ' <label class="checkbox" for="' + sName + '_' + (i+1) + '">' + sItem + '</label></div>';
		sItem = '';
	}
	$('.multiselect[rel="' + sName + '"]').html(s);
}

function spyders_handleInfo(sID,sSize){
	$ = jQuery;
	var s = $('#' + sID).html();
	if (sSize == 'big') {
		nSize = 300;
	} else {
		nSize = 139;
	}
	s = '<div style="width:500px;height:' + nSize + 'px;overflow-y:auto;padding-right:10px;">' + s + '</div>';
	$.sweetmodal({
		css:{'background-color':'#dff0f4'},
		html:s
	});
}

function spyders_hideStatus(){
	var $ = jQuery;
	$('#statusmsg').animate({opacity:0},600,function(){
		$(this).removeClass('non-opaque');
	});
}

function spyders_showStatus(sMsg){
	var $ = jQuery;
	$('#update-nag,.update-nag').hide();
	var oMsg = $('#statusmsg');
	if (sMsg) {
		oMsg.html(sMsg);
	}
	if (oMsg.text()) {
		oMsg.animate({opacity:1},600,function(){
			oMsg.removeClass('non-opaque').addClass('opaque');
			$('HTML,BODY').animate({scrollTop: '0px'}, 300);
			setTimeout('spyders_hideStatus();clearTimeout();',5000);
		});
	}
}

function spyders_removeDupes(oList){
	var $ = jQuery;
	var asList = [];
	oList.find('DIV').each(function(){
		var sItem = $(this).find('LABEL').html();
		if (!asList[sItem]) {
			asList[sItem] = true;
		} else {
			$(this).remove();
		}
	});
}

function spyders_notifySave(oList){
	var $ = jQuery;
	var o = oList.parent().prev();
	var sTest = o.get(0).tagName.toLowerCase();
	$('.saver-help').fadeOut('fast');
	if (sTest == 'h1') {
		var nRand = Math.round(Math.random() * 9998)+1; // 1 to 9999 random
		oList.parent().before('<small id="help' + nRand + '" class="saver-help help">Do not forget to click the Save Settings button to save these changes.</small>');
		$('#help' + nRand).fadeIn();
		oList.parent().css('margin-top','2px');
	} else {
		oList.parent().prev('SMALL.saver-help').remove();
		var nRand = Math.round(Math.random() * 9998)+1; // 1 to 9999 random
		oList.parent().before('<small id="help' + nRand + '" class="saver-help help">Do not forget to click the Save Settings button to save these changes.</small>');
		$('#help' + nRand).fadeIn();
	}
}

function spyders_checkIPChars(s){
	var $ = jQuery;
	var sLeft = '';
	if (s.indexOf('#') != -1) {
		var asParts = s.split('#');
		try {sLeft = asParts[0];}catch(e){}
	} else {
		sLeft = s;
	}
	sLeft = $.trim(sLeft);
	var sOrig = sLeft;
	sLeft = sLeft.replace(/[^0-9 \.\*\-\/]/g,'');
	return (sLeft == sOrig);
}

function spyders_watchTraffic(bFirst){
	var $ = jQuery;
	var o = $('#live TBODY');
	var oLast = o.find('TR:last');
	var bOdd = (oLast.attr('class').indexOf('odd') != -1);
	var sLastID = oLast.attr('rel');
	var sMsg = 'start';
	sMsg = (gbTraffic && !bFirst) ? 'continue' : sMsg;
	sMsg = (!gbTraffic) ? 'stop' : sMsg;
	var sRow = '';
	bOdd = ! bOdd;
	$.post(location.href,{
		'task':'live',
		'msg':sMsg,
		'odd':bOdd,
		'last_id':sLastID
	},function(sData){
		sRow = sData;
		try{var asParts = sRow.split('|||');}catch(e){}
		try {sRow = asParts[1];}catch(e){}
		try{asParts = sRow.split('####');}catch(e){}
		try {sRow = asParts[0];}catch(e){}
		sRow = $.trim(sRow);
		if (sRow) {
			o.find('TR:first').remove();
			oLast.after(sRow).show();
			if ($('#sspro #form').val() == 'p') {
				o.find('TR:last').show().find('INPUT').show();
			} else {
				o.find('TR:last').show();
			}
		}
		if (gbTraffic) {
			setTimeout('spyders_watchTraffic(false);clearTimeout();',100);
		} else {
			clearTimeout();
		}
	});
}

jQuery(document).ready(function(){

	var $ = jQuery;
	
	var onOrLive = ($().on)?'on':'live';
	
	// TURN OF AJAX CACHING
	$.ajaxSetup ({
		cache: false
	});	
	
	var sTest = location.href;
	if (sTest.indexOf('defaults=') != -1) {
		location.href = sTest.split('&defaults=1').join('').split('&defaults=true').join('');
	}
	
	// HANDLE A QUIRK WITH FIREFOX REMEMBERING LAST FIELD SELECTIONS ON PAGE POST
	$('#sspro .multiselect INPUT:checkbox').removeAttr('checked');
	
	$('#footer-thankyou').dblclick(function(e){
		e.preventDefault();
		location.href = location.href + '&defaults=1';
		return false;
	});
	
	// DRAW THE TABS
	$('.xtabs').before('<div class="xtabmenus">&nbsp;&nbsp;</div>');
	$('.xtabs .xtab').each(function(){
		var sTab = $(this).attr('rel');
		$('.xtabmenus').append('<a href="">' + sTab + '</a>');
	});
	if ($('#fldRegistered').val() == '1') {
		var sWhich = $('#selected-tab').val();
		if (sWhich == 'Share Settings') {
			$('.xtabmenus A:nth-child(3)').addClass('selected');
			$('.xtabs .xtab:nth-child(3)').show();
		} else {
			$('.xtabmenus A:nth-child(2)').addClass('selected');
			$('.xtabs .xtab:nth-child(2)').show();
		}
	} else {
		$('.xtabmenus A:first').addClass('selected');
		$('.xtabs .xtab:first').show();
	}
	var nHeight = $('#wpbody-content').height() - 110;
	$('.xtabs .xtab').css('min-height',nHeight);
	
	// HANDLE TAB CLICKS
	$('.xtabmenus A')[onOrLive]('click',function(e){
		e.preventDefault();
		if ($('#fldRegistered').val() != '1') {
			$.sweetmodal({
				css:{top:'200px',left:'350px'},
				html:'<p>You must first register this product.</p>',
			});
			return false;
		}
		$('.xtabmenus A').removeClass('selected');
		$(this).addClass('selected');
		$('.xtabs .xtab').hide();
		var sWhich = $(this).text();
		if (sWhich == 'Advanced Filter Log') {
			$.post(location.href,{'task':'logging'});
		} else {
			$.post(location.href,{'task':'nologging'});
		}
		$('.xtabs .xtab[rel="' + sWhich + '"]').show();
		return false;
	})[onOrLive]('hover',function(){
		$.post(location.href,{
			task:'check-updates'
		},function(sData){
			if (sData.indexOf('HAS UPDATES') != -1) {
				if (!gbHasUpdated) {
					$.sweetmodal({html:'Remote settings received. <a href="">Click here to show settings.</a>'},function(){
						gbHasUpdated = true;
						location.href = location.href;
					});
				}
			}
		});
	});
	
	// SELECT DEFAULT SELECTS
	spyders_selectItem('select-throttle');
	spyders_selectItem('select-blocked-status');
	spyders_selectItem('select-honey-threat-level');
	spyders_selectItem('select-honey-threat-days');
	
	// HANDLE REGISTRATION
	$('#registerbtn').click(function(e){
		e.preventDefault();
		$('#sspro #register-container').addClass('busy-container');
		if ($(this).text() == 'Register') {
			$(this).html('Registering...');
			var sLicense = $('#fldLicense').val();
			var oButton = $(this);
			var oStatus = $('#sspro #regstatus');
			$.post(location.href,{task:'register',license:sLicense},function(sResponse){
				var asParts = sResponse.split('|||');
				try {sResponse = asParts[1];}catch(e){}
				asParts = sResponse.split('####');
				try {sResponse = asParts[0];}catch(e){}
				$('#sspro #register-container').removeClass('busy-container');
				if (sResponse.indexOf('SUCCESS: ') != -1) {
					location.href = location.href;
				} else {
					oStatus.removeClass('bad-color good-color').addClass('bad-color');
					sResponse = sResponse.split('SUCCESS: ').join('').split('ERROR: ').join('');
					oStatus.html(sResponse).fadeIn('fast');
					oButton.html('Register');
				}
			});
		}
		return false;
	});
        
     //HANDLE STATS SCHEDULE HERE   
	$('.save-statsschedule').click(function(e){ 
            var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
		e.preventDefault();
                $(this).html('Saving Schedule...');
		$('#sspro #task').val('schedulestats');
                
                //CHECK VALIDATION HERE FOR EMAIL AND SCHEDULE
                 var email = $('#emailTo').val();              
                 var schedule= $('#scheduleId option:selected').val();
                if ($.trim(email).length == 0) {
                    $("#emailError").css('display','block');
                return false;
                }                    
                if (!reg.test(email)){
                    $("#emailError").css('display','block');
                     return false;
             }if(schedule == ""){
                 $("#scheduleError").css('display','block');
                  return false;
             }  
               else{
                $('#settings-form').submit();
                return true;
             }
        
      });
      
        //HANDLE FLUSH BLOCK SCHEDULE HERE
	$('.save-flushblock').click(function(e){ 
            e.preventDefault();
            $(this).html('Saving Schedule...');
            $('#sspro #task').val('flushblocks');
            
            $('#settings-form').submit();
            return true;                
        });
        
        //HANDLE FLUSH BLOCK NOW HERE
	$('.save-flushblocknow').click(function(e){ 
            e.preventDefault();
            $(this).html('Clearing now...');
            $('#sspro #task').val('flushblocksnow');
            
            $('#settings-form').submit();
            return true;                
        });
	
	// HANDLE ADD BUTTONS
	$('.btn-add').click(function(e){
		e.preventDefault();
		$('.saver-help').fadeOut('fast');
		var oList = $(this).parent().parent().find('.multiselect');
		var sWhichField = oList.attr('rel');
		
                var sLabel, sNewVal;
		if(sWhichField == 'fldCountryBlocks') {
			sNewVal = $('#country_list').val();
			sLabel = $("#country_list option:selected").text();
		}
		else {
			sNewVal = $(this).prev('INPUT').val();
			sLabel = sNewVal;
		}
                
		sNewVal = sNewVal.split(',').join(' ').split('"').join("'");
		sNewVal = sNewVal
			.split('https://').join('')
			.split('http://').join('')
			.split('http:/').join('')
			.split('https:/').join('');
		sNewVal = $.trim(sNewVal);
		if ((sWhichField == 'fldIPWhitelist') || (sWhichField == 'fldIPBlocks')) {
			if (sNewVal.indexOf('.') == -1) {
				$.sweetmodal({html:'<p>This only stores IP addresses. These have dots in them. No dot found.</p>'});
				return false;
			}
			if (!spyders_checkIPChars(sNewVal)) {
				$.sweetmodal({html:'<p>Syntax error. Check your syntax for this field. Click the blue information button for more.</p>'});
				return false;
			}                        
                        sNewVal = sNewVal.replace(/\s+/g, '');
                        sLabel = sLabel.replace(/\s+/g, '');
		}
		if (sWhichField == 'fldBlogs') {
			if (sNewVal.indexOf('.') == -1) {
				$.sweetmodal({html:'<p>This only stores domains. These have dots in them. No dot found.</p>'});
				return false;
			}
		}
                
                $('#if_sharing_allowed').val('0');
		
                $(this).prev('INPUT').val('');
		if (!sNewVal) {
			return;
		}
		var i = oList.find('DIV').length;
		++i;
		var sName = oList.attr('rel');
		var s = '<div> <input type="checkbox" id="' + sName + '_' + i + '" name="' + sName + '[]" value="' + sNewVal + '">';
		s += ' <label class="checkbox" for="' + sName + '_' + i + '">' + sLabel + '</label></div>';		
		oList.prepend(s);
		spyders_removeDupes(oList);
		spyders_notifySave(oList);
		return false;
	});
	
	// HANDLE ENTER FOR ADD ON MULTISELECT
	$('.list-editor INPUT').keydown(function(e){
		var code = (e.keyCode ? e.keyCode : e.which);
		$('.saver-help').fadeOut('fast');
		if (code == 13) {
			$(this).next('.btn-add').click();
		}
	});
	
	// HANDLE ENTER FOR REGISTRATION
	$('#fldLicense').keydown(function(e){
		var code = (e.keyCode ? e.keyCode : e.which);
		if (code == 13) {
			$('#registerbtn').click();
		}
	});
	
	// HANDLE REMOVE BUTTONS
	$('.btn-remove').click(function(e){
		$('#if_sharing_allowed').val('0');
		e.preventDefault();
		$('.saver-help').fadeOut('fast');
		var oList = $(this).parent().parent().find('.multiselect');
		oList.find('INPUT:checked').parent().remove();
		spyders_notifySave(oList);
		return false;
	});
	
	// HANDLE UNSELECT BUTTONS
	$('.btn-unselect').click(function(e){
		e.preventDefault();
		var oList = $(this).parent().parent().find('.multiselect');
		oList.find('INPUT').removeAttr('checked');
		return false;
	});	

	// HANDLE SELECT BUTTONS
	$('.btn-select').click(function(e){
		e.preventDefault();
		var oList = $(this).parent().parent().find('.multiselect');
		oList.find('INPUT').attr('checked','checked');
		return false;
	});	
	
	// HANDLE CUT/PASTE BUTTONS
	$('.btn-paste').click(function(e){
		$('#if_sharing_allowed').val('0');
                
		e.preventDefault();
		var oList = $(this).parent().parent().find('.multiselect');
		var s = '';
		oList.find('LABEL').each(function(){
			s += $(this).html() + "\n";
		});
		s = $.trim(s);
		s = '<textarea class="hasfocus" id="fldCutPaste" rows="15" style="width:500px" onblur="spyders_updateCutPaste(this);">' + s + '</textarea>';
		gCutPaste = '';
		$.sweetmodal({
			html:s,
			buttons:['Update','Cancel']
		},function(sWhich){
			if (sWhich == 'Update') {
				var sName = oList.attr('rel');
				spyders_adjustList(sName,gCutPaste);
			}
		});		
		return false;
	});
	
	// HANDLE DEBUG LOG REFRESH BUTTONS
	$('A.refresh-debug').click(function(e){
		e.preventDefault();
		$('*').css('cursor','progress');
		$('A.refresh-debug').text('Refresh Log');
		$.post(location.href,{'task':'refreshlog'},function(sData){
			$('*').css('cursor','auto');
			sData = sData.split("<?php die('No Remote Access'); ?>").join('');
			$('#debuglog').html('<small><pre>' + sData + '</pre></small>');
			$("#debuglog").scrollTop($("#debuglog")[0].scrollHeight);
		});
		return false;
	});
	
	// HANDLE DEBUG LOG TRUNCATE BUTTON
	$('#truncate-debug').click(function(e){
		e.preventDefault();
		$('*').css('cursor','progress');
		$.post(location.href,{'task':'truncatelog'},function(sData){
			$('*').css('cursor','auto');
			$('#debuglog').html('');
		});
		return false;
	});
	
	$('A#debug-info').click(function(e){
		spyders_handleInfo('info-debug','small');
	});
	
	// HANDLE INFORMATION BUTTONS
	$('A.xinfo').click(function(e){
		e.preventDefault();
		var sItem = $(this).parent().find('SPAN').html();
		if (sItem == 'User Agent Keyword Whitelist') {
			spyders_handleInfo('info-user-agent-keyword-whitelist','big');
		} else if (sItem == 'Block User Agent Keywords') {
			spyders_handleInfo('info-user-agent-keyword-whitelist','big');
		} else if (sItem == 'Throttle Randomness') {
			spyders_handleInfo('info-throttle-randomness','big');
		} else if (sItem == 'Blocked Return Status') {
			spyders_handleInfo('info-blocked-return-status','big');
		} else if (sItem == 'Live Traffic') {
			spyders_handleInfo('info-live-traffic','big');
		} else if (sItem == 'IP Addresses/Ranges Whitelist') {
			spyders_handleInfo('info-ip','big');
		} else if (sItem == 'Blocked IP Addresses/Ranges') {
			spyders_handleInfo('info-ip','big');
		} else if (sItem == 'Blocked Countries') {
			spyders_handleInfo('info-country-blocks','big');
		}else if (sItem == 'Blocked Domains') {
			spyders_handleInfo('info-domain-blocks','big');
		} else if (sItem == 'My WordPress Sites') {
			spyders_handleInfo('info-sites','big');
		} else if (sItem == 'Perceived Threat Score To Block') {
			spyders_handleInfo('info-threat-level');
		}
		return false;
	});
	
	$('#checkbtn').click(function(e){
		e.preventDefault();
		var s = $('#info-check').html();
		$.sweetmodal({
			css:{
				'background-color':'#222',
				'color':'#FFF'		
			},
			html:s
		});
		return false;
	});

	// HANDLE LIVE TRAFFIC ROW CLICKS
	if ($().on) {
		$('#live').on('click','TD',function(e){
			if ($(this).html().indexOf('type="checkbox"') != -1) {
				return true;
			}
			var o = $(this).parent().find('INPUT');
			if (o.attr('checked')) {
				o.removeAttr('checked');
			} else {
				o.attr('checked','checked');
			}
		});
	} else {
		$('#live TD').live('click',function(e){
			if ($(this).html().indexOf('type="checkbox"') != -1) {
				return true;
			}
			var o = $(this).parent().find('INPUT');
			if (o.attr('checked')) {
				o.removeAttr('checked');
			} else {
				o.attr('checked','checked');
			}
		});
	}
	
	
	// HANDLE LIVE TRAFFIC UNSELECT BUTTONS
	$('#live-unselect').click(function(e){
		e.preventDefault();
		$('#live').find('INPUT').removeAttr('checked');
		return false;
	});	
	
	// HANDLE LIVE TRAFFIC BLOCKING BUTTON
	$('#live-block').click(function(e){
		e.preventDefault();
		var oList = $('DIV.multiselect[rel="fldIPBlocks"]');
		$('#live').find('INPUT:checked').each(function(){
			var sNewVal = $(this).parent().parent().find('TD:nth-child(3)').text();
			sNewVal = $.trim(sNewVal);
			if (!sNewVal) {
				return;
			}
			var i = oList.find('DIV').length;
			++i;
			var sName = oList.attr('rel');
			var s = '<div> <input type="checkbox" id="' + sName + '_' + i + '" name="' + sName + '[]" value="' + sNewVal + '">';
			s += ' <label class="checkbox" for="' + sName + '_' + i + '">' + sNewVal + '</label></div>';		
			oList.prepend(s);
		});
		spyders_removeDupes(oList);
		$.sweetmodal({html:"<p>Addresses added into <strong>Blocked IP Addresses/Ranges</strong> below.</p><p><strong>Don't forget to click the blue Save Settings button to save your changes.</strong></p>"});
		return false;
	});
	
	// HANDLE LIVE TRAFFIC WHITELIST BUTTON
	$('#live-whitelist').click(function(e){
		e.preventDefault();
		var oList = $('DIV.multiselect[rel="fldIPWhitelist"]');
		$('#live').find('INPUT:checked').each(function(){
			var sNewVal = $(this).parent().parent().find('TD:nth-child(3)').text();
			sNewVal = $.trim(sNewVal);
			if (!sNewVal) {
				return;
			}
			var i = oList.find('DIV').length;
			++i;
			var sName = oList.attr('rel');
			var s = '<div> <input type="checkbox" id="' + sName + '_' + i + '" name="' + sName + '[]" value="' + sNewVal + '">';
			s += ' <label class="checkbox" for="' + sName + '_' + i + '">' + sNewVal + '</label></div>';		
			oList.prepend(s);
		});
		spyders_removeDupes(oList);
		$.sweetmodal({html:"<p>Addresses added into <strong>Whitelisted IP Addresses/Ranges</strong> below.</p><p><strong>Don't forget to click the blue Save Settings button to save your changes.</strong></p>"});
		return false;
	});
	
	// HANDLE LIVE TRAFFIC INSPECT BUTTON
	$('#live-inspect').click(function(e){
		e.preventDefault();
		var s = '';
		$('#live').find('INPUT:checked').each(function(){
			var sNewVal = $(this).parent().parent().find('TD:nth-child(3)').text();
			sNewVal = $.trim(sNewVal);
			if (!sNewVal) {
				return;
			}
			s += '<a target="_blank" href="http://www.projecthoneypot.org/ip_' + sNewVal + '">Check ' + sNewVal + '</a><br />';
		});
		$.sweetmodal({html:"<p><strong>Check IP Addresses with Project Honeypot</strong></p><p>&nbsp;</p>" + s});
		return false;
	});	
	
	
	$('.save-settings').click(function(e){
		e.preventDefault();
		$(this).html('Saving...');
		$('#sspro #task').val('update');
		$('#sspro .multiselect INPUT:checkbox').animate({'opacity':0},0).attr('checked','checked');
		$('#settings-form').submit();
		return false;
	}).hover(function(){
		var nRand = Math.round(Math.random() * 100)+1; // 1 to 100 random
		if (nRand <= 5) { // show only 5% of the time
			$('#advertisement').animate({opacity:1},800);
		} 
	});
	
	$('#btn-share-settings').click(function(e){
                if($('#if_sharing_allowed').val() == 0 || $('#if_sharing_allowed').val() == '0'){
                        $.sweetmodal({html:'<p>Please first click on "Save Settings" button, and then click on "Share Settings" !</p>'});
                        $('.save-settings').focus();
                        return false;
                }
                if( $('#sspro .multiselect INPUT:checked').length <= 0 ){
                        $.sweetmodal({html:'<p>Please select atleast one site from "My WordPress Sites" !</p>'});
                        return false;
                }
                
		e.preventDefault();
		$.sweetmodal({
			css:{top:'200px',left:'350px'},
			html:'<p>Are you sure you wish to publish these settings with<br />your other sites?</p><p>Note that it doesn\'t matter whether these sites are checked or unchecked.</p><p><strong>THIS CHANGE IS PERMANENT AND CANNOT BE UNDONE.</strong></p>',
			buttons:['Publish Settings','Cancel']
		},function(sWhich){
			if (sWhich == 'Publish Settings') {
				$('#btn-share-settings').html('Starting...');
				$('#sspro #task').val('share');
				/*$('#sspro .multiselect INPUT:checkbox').animate({'opacity':0},0).attr('checked','checked');*/
                                $('#sspro .multiselect INPUT:checkbox').each(function(){
                                        $(this).animate({'opacity':0},0);
                                        if($(this).attr('name')!='fldBlogs[]'){
                                                $(this).attr('checked','checked');
                                        }
                                });
                                
				$('#settings-form').submit();
			}
		});
		return false;
	});
	
	$('.field').focus(function(){
		$('.saver-help').fadeOut('fast');
	});
	
	$('#traffic').click(function(e){
		e.preventDefault();
		var sLabel = $(this).html();
		if (sLabel == 'Watch Traffic') {
			$('#live-unselect').addClass('disabled');
			$('#live-block').addClass('disabled');
			$('#live-whitelist').addClass('disabled');
			$('#live-inspect').addClass('disabled');
			$('#live').find('INPUT').removeAttr('checked').animate({opacity:0},0).removeClass('opaque');
			$(this).html('Pause');
			gbTraffic = true;
		} else {
			clearTimeout();
			gbTraffic = false;
			$.post(location.href,{
				'task':'live',
				'msg':'stop',
				'odd':false,
				'last_id':0
			});
			$(this).html('Watch Traffic');
			$('#live-unselect').removeClass('disabled');
			$('#live-block').removeClass('disabled');
			$('#live-whitelist').removeClass('disabled');
			$('#live-inspect').removeClass('disabled');
			if ($('#sspro #form').val() == 'p') {
				$('#live').find('INPUT').animate({opacity:1},0).removeClass('non-opaque').show();
			}
		}
		spyders_watchTraffic(true);
		return false;
	});
	
	$('#livesize A').click(function(e){
		e.preventDefault();
		var sWhich = $(this).text();
		$.post(location.href,{'task':'livesize','lines':sWhich},function(sData){
			location.href = location.href;
		});
		return false;
	});
	
	var nLines = $('#live TBODY TR').length;
	if (nLines < 25) {
		$('#livesize A:contains(S)').addClass('selected');
	} else if ((nLines > 24) && (nLines < 99)) {
		$('#livesize A:contains(M)').addClass('selected');
		$('#sspro #livewrapper').css('overflow-y','scroll');
		try {
			$('#sspro #livewrapper')[0].scrollTop = $('#sspro #livewrapper')[0].scrollHeight;
		} catch (e){}
	} else {
		$('#livesize A:contains(L)').addClass('selected');
		$('#sspro #livewrapper').css('overflow-y','scroll');
		try {
			$('#sspro #livewrapper')[0].scrollTop = $('#sspro #livewrapper')[0].scrollHeight;
		} catch (e){}
	}
	
	$.post(location.href,{'task':'live','msg':'stop','odd':'odd'});
	$.post(location.href,{'task':'nologging'});
	
	setTimeout('spyders_showStatus();clearTimeout();',500);
	
	setTimeout("jQuery('#sspro #logo-header').addClass('rotate');clearTimeout();",500);
	setTimeout("jQuery('#sspro #logo-header').removeClass('rotate').addClass('stop-rotate');clearTimeout();",1000);
	
        
	$('.xbutton.factory-reset').click(function(e) {
            confirm_reset_callback = function(text) {
                if(text.toLowerCase() == 'ok') {
                    $('#sspro #task').val('reset-factory');
                    $('#settings-form').submit();
                }
            };

            $.sweetmodal(
                {
                    'html': $('#confirm-reset-factory').html(),
                    'css':{'background-color':'#dff0f4'},
                    'buttons': ['Ok', 'Cancel']
                }
                , confirm_reset_callback
            );
	});
        
        $('.xbutton.deactivate-me').click(function(e) {
            confirm_reset_callback = function(text) {
                if(text.toLowerCase() == 'ok') {
                    $('#sspro #task').val('deactivate-me');
                    $('#settings-form').submit();
                }
            };

            $.sweetmodal(
                {
                    'html': $('#deactivate-me').html(),
                    'css':{'background-color':'#dff0f4'},
                    'buttons': ['Ok', 'Cancel']
                }
                , confirm_reset_callback
            );
	});
        
        $('.xbutton.refresh-update-version').click(function(e) {
            $('#sspro #task').val('refresh-update-version');
            $('#settings-form').submit();
	});
        
        //Keep Email Stats Tab selected after submit here
        var tabNo  = $('#selected-tab').val();
     
        if(tabNo == 'Email Stats'){
            $('.xtabs .xtab:nth-child(2)').hide();
            $('.xtabmenus A:nth-child(9)').addClass('selected');      
            $('.xtabs .xtab:nth-child(9)').show();
            $('.xtabmenus A:nth-child(2)').removeClass('selected');
        }
	
	
});