﻿//	Connections calls

if(typeof logc !== 'function'){
	function logc(inp){
		if (window.console){
			console.log(inp);
		}
		return inp;
	}
}

(function($) {

//	SIDEBAR GAME TABS

	$.fn.gameTabs = function(options){
		if (this.length == 0){
			return $(this);
		}

		var tabs = function(element, options){

			var self = this,
			$root = $(element),

			settings = $.extend({
			}, options || {}),

			$tabkeys = $root.find('ul.tabbar li'),
			$tabs = $root.find('div.tab').hide().eq(0).show().end();

			for(i=0; i<$tabs.length; i++){
				var $i = $tabs.eq(i);
				var ht = $i.outerHeight();
				$i.data('ht', ht);
				if (i==0){
					$root.height(ht);
				}
			}

			var clfn = function(){
				$(this).addClass('act').siblings().removeClass('act');
				var num = $tabkeys.index(this);
				var $par = $tabkeys.parent();
				switch(num){
					case(0):
						$par.addClass('connect').removeClass('play meet');
					break;
					case(1):
						$par.addClass('play').removeClass('connect meet');
					break;
					case(2):
						$par.addClass('meet').removeClass('connect play');
					break;
				}
				var $t = $tabs.hide().eq(num).show();
				$root.height($t.data('ht'));
			}

			$tabkeys.click(clfn);

		}

		return this.each(function(){
			var element = $(this);
			if (element.data('tabs')) return;
			var t = new tabs(this, options);
			element.data('tabs', t);
		});

	}

//	CONNECTION FILTER FUNCTIONALITY

	$.fn.conFilter = function(options){
		if (this.length == 0){
			return $(this);
		}

		var filter = function(element, options){

			var self = this,
			$root = $(element),

			settings = $.extend({
			}, options || {}),

			ajaxurl = '',
			ajaxdata = { ajaxmode: true },
			$tabs = $root.find('a'),

			parseUrl = function(url){
				var parts = url.split('?');
				ajaxurl = parts[0];
				if(parts[1]){
					parts = parts[1].split('&');
					for(i=0; i<parts.length; i++){
						var p = parts[i].split('=');
						p = '{"' + p[0] + '":' + '"' + p[1] + '"}';
						p = $.parseJSON(p);
						ajaxdata = $.extend(ajaxdata, p);
					}
				}
				else {
					ajaxdata = { ajaxmode: true };
				}
			},

			clfn = function(){
				parseUrl(this.href);
				var tagname = $(this).parent().attr('tagName').toLowerCase();
				switch(tagname){
					case('li'):
					$(this).parent().addClass('on').siblings().removeClass('on').parents('div:first').addClass('on');
					break;
					case('p'):
					$(this).parents('div:first').removeClass('on').find('li').removeClass('on');
					break;
				}
				$.ajax({
					type: 'GET',
					cache: false,
					url: ajaxurl,
					data: ajaxdata,
					dataType: 'html',
					success: function(data){
						if(isLoggedOut(data)){ return; }
						$('#connections_main').children().remove().end().append(data);
					},
					complete: function(){
						$.chem.updateConUI();
						$.chem.updateGameUI();
					}
				});
				return false;
			};

			$tabs.click(clfn);

		}

		return this.each(function(){
			var element = $(this);
			if (element.data('ftr')) return;
			var fr = new filter(this, options);
			element.data('ftr', fr);
		});

	}

//	AJAX CALL: REMOVE CONNECTION

	$.fn.removeCon = function(options){
		if (this.length == 0){
			return $(this);
		}

		var remcon = function(element, options){

			var self = this,
			$root = $(element),

			settings = $.extend({
			}, options || {}),

			$par = $root.parents('div.module:first'),
			$cov = $par.find('div.cover'),

			data = {
				ajaxmode: true,
				matchUserId: $par.attr('matchid')
			},

			clfn = function(){
				if ($(this).hasClass('busy')){
					return false;
				}
				$par.addClass('busy');
				$root.addClass('busy');
				$.ajax({
					data: data,
					cache: false,
					url: '/connections/remove',
					success: function(){
						$par.css('overflow', 'hidden').animate({
							height: 0,
							marginBottom: 0
						}, 400, function(){ $(this).remove(); }).find('div.cover').animate({
							height: 0
						}, 400);
					},
					error: function(){
						$root.removeClass('busy');
						var name = $par.removeClass('busy').find('h3 a').text().toLowerCase();
						alert('Could not remove ' + name + ' from connections at this time. Please try again later.')
					}
				});
				return false;
			};

			$cov.css({
				height: $cov.height()
			});
			$root.click(clfn);
		}

		return this.each(function(){
			var element = $(this);
			if (element.data('remcon')) return;
			var rm = new remcon(this, options);
			element.data('remcon', rm);
		});

	}

//	AJAX CALL: SEND NUDGE

	$.fn.sendNudge = function(options){
		if (this.length == 0){
			return $(this);
		}
		var nudge = function(element, options){

			var self = this,
			$root = $(element),
			$par = $root.parents('div.module:first'),

			settings = $.extend({
			}, options || {}),

			data = {
				ajaxmode: true,
				matchUserId: $par.attr('matchid')
			},

			clfn = function(){
				$par.addClass('busy');
				$root.addClass('busy');

				$.ajax({
					data: data,
					url: '/connections/nudge',
					success: function(data){
						if(isLoggedOut(data)){ return; }
						$par.removeClass('busy');
						$root.parent().text('nudge sent');
					},
					error: function(){
						$root.removeClass('busy');
						var name = $par.removeClass('busy').find('h3 a').text().toLowerCase();
						alert('Could not nudge ' + name + ' at this time. Please try again later.')
					}
				});
				return false;
			};

			$root.click(clfn);

		}

		return this.each(function(){
			var element = $(this);
			if (element.data('nudge')) return;
			var ng = new nudge(this, options);
			element.data('nudge', ng);
		});

	}

//	AJAX CALL: GET CONNECTIONS PAGES

	$.fn.getPages = function(options){
		if (this.length == 0){
			return $(this);
		}
		var pages = function(element, options){

			var self = this,
			$root = $(element),
			ajurl = '/connections',
			$trig = $('#cons div.showmore a'),
			$cont = $('#connection_list').eq(0),
			pd = $.parseJSON($root.attr('value')),
			$par = $root.parents('div.module:first'),

			settings = $.extend({
			}, options || {});

			if (pd.filter.length != 0){
				ajurl += '/filtered/' + pd.filter;
			}

			var getData = function(){
				pd.pagenum++;
				if (pd.pagenum > pd.totpgs){
					return false;
				}
				var ajdat = {
					ajaxmode: true,
					addnpages: true,
					sortBy: pd.sortOrder,
					pageNumber: pd.pagenum
				};
				if (pd.progfilter){
					ajdat.progFilter = pd.progfilter;
				}
				$.ajax({
					url: ajurl,
					data: ajdat,
					type: 'GET',
					cache: false,
					success: function(data){
						if(isLoggedOut(data)){ return; }
						$cont.css({
							height: $cont.height()
						}).append(data);

						if(pd.pagenum == pd.totpgs){
							$trig.parents('div:first').remove();
						}
					},
					complete: function(){
						$.chem.updateConUI();
						$.chem.updateGameUI();
						$cont.attr('scrollHeight');
						var t = Math.round(($cont.attr('scrollHeight') - $cont.height())/4);
						if (t<200){ t = 200; }
						$cont.animate({
							height: $cont.attr('scrollHeight')
						}, t, function(){
							$cont.height('auto');
						});
					}
				});
				return false;
			};

			$cont.css({
				overflow: 'hidden'
//				height: $cont.height()
			});

			$trig.click(getData);

		}

		return this.each(function(){
			var element = $(this);
			if (element.data('pages')) return;
			var pg = new pages(this, options);
			element.data('pages', pg);
		});

	}

	$.chem.updateConUI = function(){
		$('#cons a.remcon').removeCon();
		$('#cons p.nudge a').sendNudge();
		$('#cons input[name="pginfo"]').getPages();
	}

})(jQuery);

$(function(){

// Connections list initialization.
	if ($.fn.connection_list){
	    $('#connection_list').connection_list(); // TODO: Migrate filtering and sorting mechanisms into the ConnectionList object.
	}

	try{
		$('#cfilters').conFilter();
		$('div.tabcontainer').gameTabs();
		var $w = $('#cons p.whatis a').psPopup({
		    ajaxdata: {},
		    ajaxmode: 'GET',
		    ajaxrequest: true,
		    showoverlay: true,
		    popupid: '#wm',
		    ajaxurl: '/connections/showwelcomemessage',
		    install: function ($box) {
		        $box.find('a.button').click(function(){
		            $box.find('a.close').trigger('click');
					return false;
		        });
		    }
		});
		if ($w.hasClass('showonload')){
			$w.trigger('click');
			var pop = $w.data('pop');
			pop.showcb = function(){
				$.ajax({
					cache: false,
					dataType: 'html',
					data: { ajaxmode: true },
					url: '/connections/closewelcomemessage'
				});
			};
		}
		$.chem.updateConUI();
	}
	catch(error){
		logc(error)
	}

});

