/**
 * Pimps At War JavaScript Functions and Event Handlers
 * 
 * Most page load functions should go into PAW_init so they are processed before image loading.
 * Legacy onload functions should go into PAW_onload only if there are issues using PAW_init, most likely with Firefox.
 * Both functions provide automatic running of any function with _extra name suffix to load dynamic stuff automatically.
 */
$(document).ready(function(){
	PAW_init();
	if(typeof PAW_init_extra == 'function') {
		PAW_init_extra();
	}
});
window.onload = function(){
	PAW_onload();
	if(typeof PAW_onload_extra == 'function') {
		PAW_onload_extra();
	}
};

function PAW_init()
{
	// Change events
	$('#changepimpid').change(function() {
		$('#changepimp').submit();
	});
	$('#changethemeid').change(function() {
		$('#changetheme').submit();
	});
	// Click events
	$('#accountlink').click(function() { 
    	$('#account').slideToggle(300);
    });
	$('#pimplink').click(function() { 
    	$('#pimp').slideToggle(300);
    });
	$('#actionslink').click(function() { 
    	$('#actions').slideToggle(300);
    });
	$('#attacklink').click(function() { 
    	$('#attack').slideToggle(300);
    });
	$('#ganglink').click(function() { 
    	$('#gang').slideToggle(300);
    });
	$('#commslink').click(function() { 
    	$('#comms').slideToggle(300);
    });
	$('#rankslink').click(function() { 
    	$('#ranks').slideToggle(300);
    });
	$('#upgradeslink').click(function() { 
    	$('#upgrades').slideToggle(300);
    });
	var General = {
		setHandlers : function() {
			if ($('#statusMessage')) {
				$('#statusMessage').animate({'opacity':0.5}, 300);  
				$('#statusMessage').animate({'opacity':1}, 300);
				$('#statusMessage').animate({'opacity':0.5}, 100);  
				$('#statusMessage').animate({'opacity':1}, 100); 
				$('#statusMessage').animate({'opacity':0.5}, 100);  
				$('#statusMessage').animate({'opacity':1}, 100);
				setTimeout("hide('#statusMessage')", 10000);
			}
			if ($('#adminAlert')) {
				$('#adminAlert').animate({'opacity':0.5}, 300);  
				$('#adminAlert').animate({'opacity':1}, 300);
				$('#adminAlert').animate({'opacity':0.5}, 100);  
				$('#adminAlert').animate({'opacity':1}, 100); 
				$('#adminAlert').animate({'opacity':0.5}, 100);  
				$('#adminAlert').animate({'opacity':1}, 100);
				setTimeout("hide('#adminAlert')", 15000);
			}
			if ($('.hpAlert')) {
				$('.hpAlert').animate({'opacity':0.5}, 300);  
				$('.hpAlert').animate({'opacity':1}, 300);
				$('.hpAlert').animate({'opacity':0.5}, 100);  
				$('.hpAlert').animate({'opacity':1}, 100); 
				$('.hpAlert').animate({'opacity':0.5}, 100);  
				$('.hpAlert').animate({'opacity':1}, 100);
			}
			if ($('#loginfail')) {
				$('#loginfail').animate({'opacity':0.5}, 300);  
				$('#loginfail').animate({'opacity':1}, 300);
				$('#loginfail').animate({'opacity':0.5}, 100);  
				$('#loginfail').animate({'opacity':1}, 100); 
				$('#loginfail').animate({'opacity':0.5}, 100);  
				$('#loginfail').animate({'opacity':1}, 100);
				setTimeout("hide('#loginfail')", 6000);
			}
		}
	}
	General.setHandlers();
	new bsn.AutoSuggest('findplayersearch', {
		script: "/ajax/autosuggest/?",
		varname: "pimpname",
		minchars: 2,
		delay: 100,
		timeout: 10000,
		cache: true,
		json: true,
		maxresults: 10,
		maxentries: 10
	});
	new bsn.AutoSuggest('addtoreport', {
		script: "/ajax/autosuggest/?noinfo=1&",
		varname: "pimpname",
		minchars: 2,
		delay: 100,
		timeout: 10000,
		cache: true,
		json: true,
		maxresults: 10,
		maxentries: 10
	});
	new bsn.AutoSuggest('assignreportto', {
		script: "/ajax/autosuggest/?noinfo=1&",
		varname: "pimpname",
		minchars: 2,
		delay: 100,
		timeout: 10000,
		cache: true,
		json: true,
		maxresults: 10,
		maxentries: 10
	});
	$('#tabs').tabs();
	$('#tutorial').draggable({
		stop: function() {
			var pos = $('#tutorial').position();
			var visible = $('#tutorial .tcontent').is(':visible');
			$.cookie('PAWTUTORIAL', '{top:' + pos.top + ',left:' + pos.left + ',visible:' + visible + '}' , { expires: 1, path: '/' });
		}
	});
	$('img#tresize').click(function() { 
    	$('#tutorial .tcontent').slideToggle(300, function() {
			if($('#tutorial .tcontent').is(':visible')) {
				$('img#tresize').attr('src', '/images/magnifier_zoom_out.png');
			} else {
				$('img#tresize').attr('src', '/images/magnifier_zoom_in.png');
			}
			var pos = $('#tutorial').position();
			var visible = $('#tutorial .tcontent').is(':visible');
			$.cookie('PAWTUTORIAL', '{top:' + pos.top + ',left:' + pos.left + ',visible:' + visible + '}' , { expires: 1, path: '/' });
		});
    });
	$('a#tclose').click(function() {
		$.cookie('PAWTUTORIAL', null, { path: '/' });
	});
	if($('#tutorial').length > 0) {
		var params = $.cookie('PAWTUTORIAL');
		if(params != null) {
			var pos = eval('(' + params + ')');
			$('#tutorial').css({
				'top'  : pos.top + 'px',
				'left' : pos.left + 'px'
			});
			if(pos.visible == false) {
				$('#tutorial .tcontent').slideToggle(0);
			}
		}
	}
	$('a[rel=delete]').click(function() {
		return confirm('Are you sure you want to delete this?');
	});
	$('a[rel=closereport]').click(function() {
		return confirm('Are you sure you want to close this report?');
	});
	$('a[rel=showreport]').click(function() {
		var id = $(this).attr('id').replace('showdetails_', '');
		showhide('#details_' + id);
	});
	$('a[rel=showreport]').one("click", function() {
		var id = $(this).attr('id').replace('showdetails_', '');
		ajaxreplace('/ajax/reportothers/' + id, '#others_' + id);
		ajaxreplace('/ajax/reportlogs/' + id, '#logs_' + id);
		return false;
	});
	$('a[rel=blockplayer]').click(function() {
		return confirm('WARNING: This option will restrict or ban the selected player, are you sure?');
	});
	$('form#forumpost').submit(function() {
		if($('input#attachment').val() != '') {
			// HTML to insert
			var overlay = '<div id="pg_overlay"></div>';
			var uploadbox = '<div id="uploadbox"><img id="loadingimg" border="0" /><br /><p>Uploading...</p></div>';
			// Insert the HTML
			$('body').append(overlay);
			$('body').append(uploadbox);
			// Work around for iframed pages
			if(top === self) {
				// Center the loading box
				centerObject($('#uploadbox'));
				// Setup event handlers so box stays centered
				$(window).scroll(function() {
					centerObject($('#uploadbox'));
				});
				$(window).resize(function() {
					centerObject($('#uploadbox'));
				});
			} else {
				// Center the box so that it's in the middle horizontally
				centerObject($('#uploadbox'));
				// Then fix the box near the attachment element
				var pos = $('input#attachment').position();
				$('#uploadbox').css({'top': pos.top - 200});
			}
			// Add the reloaded image
			$('img#loadingimg').attr('src', '/images/loader_big.gif');
			// Finally set background height and add the background fade effect
			$('#pg_overlay').css({'opacity': 0, 'height': $(document).height()});
			$('#pg_overlay').fadeTo(300, 0.33);
		}
	});
	$('form.acceptbounty').submit(function() {
		// Grab bounty ID
		var id = $(this).attr('id').replace('acceptfrm_', '');
		var page = $(this).attr('action').replace('/actions/acceptbounty/', '');
		// HTML to insert
		var overlay = '<div id="pg_overlay"></div>';
		var checkbox = '<div id="bountycheck"><img id="loadingimg" border="0" /><br /><p>Checking attack paramaters...</p></div>';
		// Insert the HTML
		$('body').append(overlay);
		$('body').append(checkbox);
		// Work around for iframed pages
		if(top === self) {
			// Center the loading box
			centerObject($('#bountycheck'));
			// Setup event handlers so box stays centered
			$(window).scroll(function() {
				centerObject($('#bountycheck'));
			});
			$(window).resize(function() {
				centerObject($('#bountycheck'));
			});
		} else {
			// Center the box so that it's in the middle horizontally
			centerObject($('#bountycheck'));
			// Then fix the box to the top of the table
			var pos = $('#bountylist').position();
			$('#bountycheck').css({'top': pos.top + 50});
		}
		// Add the reloaded image
		$('img#loadingimg').attr('src', '/images/loader_big.gif');
		// Finally set background height and add the background fade effect
		$('#pg_overlay').css({'opacity': 0, 'height': $(document).height()});
		$('#pg_overlay').fadeTo(300, 0.33);
		// AJAX call
		$.get('/ajax/checkattack/' + id + '/page/' + page, function(data){
			// Move/resize the div
			$('#bountycheck').animate({
				'left':   '-=125px',
				'top':    '-=50px',
				'width':  '+=250px',
				'height': '+=170px'
			}, 500);
			// Insert the html
			$('#bountycheck').html(data);
			// Add click function to cancel button
			$('input#cancelconf').click(function() {
				$('#bountycheck').fadeTo(500, 0, function() {
					$('#bountycheck').remove();
				});
				$('#pg_overlay').fadeTo(500, 0, function() {
					$('#pg_overlay').remove();
				});
				return false;
			});
		});
		return false;
	});
	$('a[rel=flowplayer]').each(function() {
		var id = $(this).attr('id');
		flowplayer(id, '/swf/flowplayer-3.1.1.swf',	{
			clip:  { 
				autoPlay: false, 
				autoBuffering: false
			}
		});
	});
	$('div.preview').each(function() {
		var url = $(this).html();
		var loader = '<img class="loadingimg" border="0" /><br /><p>Loading preview...</p>';
		$(this).html(loader);
		$('img.loadingimg').attr('src', '/images/loader_big.gif');
		var target = $(this);
		$.get('/ajax/urlpreview?url=' + url, function(data) {
			target.html(data);
		});
	});
	$('span.countdown').each(function() {
		var endtime = $(this).html();
		$(this).countdown({
			until:  endtime,
			format: 'dhmS',
			layout: '{d<}{dn} days {d>}{h<}{hn} hours {h>}{m<}{mn} mins {m>}{sn} secs',
			expiryUrl: self.location.href
		});
	});
}

function PAW_onload()
{
	// Preload the loading image
	loader = new Image();
	loader.src = '/images/loader_big.gif';
}

function show(obj)
{
	$(obj).animate({ height: 'show', opacity: 1 }, 'slow');
}
function hide(obj)
{
	$(obj).animate({ height: 'hide', opacity: 0 }, 'slow');
}
function quickshow(obj)
{
	$(obj).animate({ height: 'show' }, 'fast');
}
function quickhide(obj)
{
	$(obj).hide();
}
function vslidein(obj)
{
	$(obj).show();
}
function vslideout(obj)
{
	$(obj).animate({ height: 'hide' }, 'slow');
}
function imgreload(obj, file)
{
	document.getElementById(obj).src = file + '?' + microtime();
}
function microtime()
{
	var now = new Date().getTime() / 1000;
    var s = parseInt(now);
    return (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}
function showhide(obj)
{
	$(obj).slideToggle(300);
}
function setVal(obj, data)
{
	document.getElementById(obj).value = data;
}
function setBg(obj, data)
{
	document.getElementById(obj).style.background = '#' + data;
}
function setCol(obj, data)
{
	document.getElementById(obj).style.color = '#' + data;
}
function enableSort(obj)
{
	$(obj).sortable({
		items: '.sortableitem',
		opacity: 0.75,
		placeholder: 'placeholder',
		tolerance: 'pointer'
	});
	$(obj).disableSelection();
	$(obj).sortable('enable');
}
function disableSort(obj)
{
	$(obj).sortable('disable');
}
function saveSort(obj, url, hideobj, showobj)
{
	var order = $(obj).sortable('serialize');
	$.post(url, order, function(){
		// Hide save animation after 1 second and reveal the button
		setTimeout("quickhide('" + hideobj + "')", 1000);
		setTimeout("quickshow('" + showobj + "')", 1000);
	});
}
function ajaxreplace(url, obj)
{
	$.get(url, function(data){
		$(obj).html(data);
	});
}
function centerObject(obj)
{
	winheight = $(window).height();
	winwidth = $(window).width();
	objheight = obj.height();
	objwidth = obj.width();
	if (self.pageYOffset) {
		scrollTop = self.pageYOffset;
		scrollLeft = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {
		scrollTop = document.documentElement.scrollTop;
		scrollLeft = document.documentElement.scrollLeft;
	} else if (document.body) {
		scrollTop = document.body.scrollTop;
		scrollLeft = document.body.scrollLeft;	
	}
	obj.css({
			 'top': ((winheight - objheight) / 2) + scrollTop,
			 'left': ((winwidth - objwidth) / 2) + scrollLeft
			});
}
function playVideo(file)
{
	var path = '/attachments/' + file;
	var code = '<a id="vplink" href="' + path + '" style="display: block; width: 640px; height: 480px;"></a>';
	$('#videoplayer').html(code);
	flowplayer('vplink', '/swf/flowplayer-3.1.1.swf', {
		clip:  { 
			autoPlay: true, 
			autoBuffering: true
		}
	});
	// Hack for iframed versions
	if(top !== self) {
		if(typeof resizeIframe == 'function') {
			var pos = $('#footer').position();
			resizeIframe(950, pos.top + 80);
		}
	}
}
function fb_resize()
{
	FB_RequireFeatures(["CanvasUtil"], function() {
		FB.XdComm.Server.init('/xd_receiver.htm');
		FB.CanvasClient.startTimerToSizeToContent();
		FB.CanvasClient.scrollTo(0,0);
	});
}
function fb_feedpost(api_key, feed_id, app_name, app_url, action_txt, body_txt)
{
	if(body_txt == undefined) {
		body_txt = '';
	}
	FB_RequireFeatures(["XFBML"], function() {
		FB.Facebook.init(api_key, '/xd_receiver.htm');
        FB.Connect.showFeedDialog(feed_id,
                                  {appname: app_name,
                                   appurl:  app_url,
                                   action:  action_txt,
                                   images:[{src:  'http://www.pimpsatwar.com/images/fb_feed_1.png',
                                            href: app_url},
                                           {src:  'http://www.pimpsatwar.com/images/fb_feed_2.png',
                                            href: app_url},
                                           {src:  'http://www.pimpsatwar.com/images/fb_feed_3.png',
                                            href: app_url}]},
                                  [],
                                  body_txt,
                                  null,
                                  FB.RequireConnect.require,
                                  null);
	});	
}