/**
 * Define main object class for Bragbet
 *
*/
if (typeof BN == 'undefined') {
	var BN = {};
}

/**
 * Creates IDŐs for any item
 * @base SCS
 * @class Construct a new BN.Identifier object
 * @constructor
 */
BN.Identifier = function() {	 

	/**
	 * Create 16 character random string to be used as ID
	 * @private
	 * @return 16 character long alpha string
	 * @type {String}
	 */
	var _randomString = function() {
		var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
		var strLength = 16;
		var rndString = '';
		for (var i=0; i< strLength; i++) {
			var rnum = Math.floor(Math.random() * chars.length);
			rndString += chars.substring(rnum, rnum+1);
		}
		return rndString;
	};
	
	/**
	 * Add new ID to an element
	 * @param {String} id ID to add to HTML markup first item
	 * @param {String} html HTML markup
	 * @return HTML with with an ID added to the first element
	 * @type {String}
	 */
	this.addId = function(html, id) {
		if (typeof id == 'undefined' || id == '') {
			var id = _randomString();
		}
		$(html).each(function() {
			$html = $(this).attr('id', id);
		});
		return $html.get(0);
	};
	
	/**
	 * Give out a random ID
	 * @return random ID value
	 * @type {String}
	 */
	this.randomId = function() {
		return _randomString();
	};
};


/**
 * Add tooltips to (?) items
 *
*/
BN.tooltips = function() {
	
	var _positionTips = function(link) {
		var $arrow = $('#tooltip-'+link.id+' .arrow');
		$('#tooltip-'+link.id).css({opacity: 0, top: ($(link).position().top - ($('#tooltip-'+link.id).outerHeight()/2) + ($arrow.outerHeight()/2)), left: ($(link).position().left + $(link).outerWidth() + ($arrow.outerWidth()))});
	};
	
	$('.hasTooltip').each(function() {
		var content = $(this).attr('title');
		this.id = BN.identifier.randomId();
		$('body').prepend('<div class="tooltip" id="tooltip-'+this.id+'"><div class="body">'+content+'</div><img src="/home/images/tooltip-arrow.png" class="arrow"></div>');
		this.title = '';
	});
	$('.hasTooltip').click(function(e) {
		e.preventDefault();
	});
	$('.hasTooltip').hover(function() {
		_positionTips(this);
		$('#tooltip-'+this.id).css({visibility: 'visible'}).animate({opacity: 1}, 100);
	},
	
	function() {
		$('#tooltip-'+this.id).animate({opacity: 0}, 100, function() {
			$(this).attr('style', '');
		});
	});
	
	$(window).resize(function() {
		$('.hasTooltip:visible').each(function() {
			_positionTips(this);
		});
	});
};






/**
 * Add tooltips to (Odds) items
 *
*/
BN.tooltipsOdds = function() {
	
	var _positionTipsOdds = function(link) {
		var $arrow = $('#tooltipOdds-'+link.id+' .arrow');
		$('#tooltipOdds-'+link.id).css({opacity: 0, top: ($(link).position().top - ($('#tooltipOdds-'+link.id).outerHeight()/2) + ($arrow.outerHeight()/2)), left: ($(link).position().left + $(link).outerWidth() + ($arrow.outerWidth()))});
	};
	
	$('.hasTooltipOdds').each(function() {
		var content = $(this).attr('title');
		this.id = BN.identifier.randomId();
		$('.tips').prepend('<div class="tooltip" id="tooltipOdds-'+this.id+'"><div class="body">'+content+'</div><img src="/home/images/tooltip-arrow.png" class="arrow"></div>');
		this.title = '';
	});
	$('.hasTooltipOdds').click(function(e) {
		e.preventDefault();
	});
	$('.hasTooltipOdds').hover(function() {
		_positionTipsOdds(this);
		$('#tooltipOdds-'+this.id).css({visibility: 'visible'}).animate({opacity: 1}, 100);
	},
	
	function() {
		$('#tooltipOdds-'+this.id).animate({opacity: 0}, 100, function() {
			$(this).attr('style', '');
		});
	});
	
	$(window).resize(function() {
		$('.hasTooltipOdds:visible').each(function() {
			_positionTipsOdds(this);
		});
	});
};



/**
 * Large button tabs
 *
*/
BN.tabs = function() {
	$('.tabs a').click(function(e) {
		e.preventDefault();
		$(this).closest('ul').find('li').removeClass('active');
		$(this).closest('li').addClass('active');
		$(this).closest('fieldset').find('.tabContents').addClass('hidden');
		var $t = $(this);
		
		if ($(this).attr('data-target') == 'popup') {
			$.ajax({
				type: 'get',
				url: $(this).attr('data-popupurl'),
				dataType: 'html',
				success: function(data, response) {
					if (data && response == 'success') {
						BN.popup(data, $t.attr('data-popupwidth'));
					}
				},
				error: function(a, b, c) {
				}
			});
		} else {
			$('#'+$(this).attr('data-target')).removeClass('hidden');
		}
	});
};

/**
 * Input field 'hint' values from title attributes
 *
*/
BN.widgets = function($container) {
	$("input[title], textarea", $container).each(function() {
		if ($(this).val() == '') {
			$(this).addClass('hint').val($(this).attr('title'));
		} else {
			$(this).removeClass('hint');
		}
		$(this).focus(function() {
			if ($(this).val() == $(this).attr('title')) {
				$(this).removeClass('hint').val('');
			}
		});
		$(this).blur(function() {
			if ($(this).val() == '') {
				$(this).addClass('hint').val($(this).attr('title'));
			}
		});
	});
	$('.datepicker').datepicker({
		inline: true,
		firstDay: 1,
		showOn: "button",
		buttonImage: "/home/images/calendar-icon.png",
		showOtherMonths: true,
		selectOtherMonths: false
	});
};

/**
 * Scroll list
 *
*/
BN.scroller = function() {
	$('.scrollList .header input[type=checkbox]').live('click', function() {
		if ($(this).attr('checked')) {
			$(this).closest('.scrollList').find('.scroller input[type=checkbox]').attr('checked', 'checked');
		} else {
			$(this).closest('.scrollList').find('.scroller input[type=checkbox]').attr('checked', '');
		}
	});
};

/**
 * Wall actions
 *
*/
BN.wall = function() {
	$('.addComment').live('click', function(e) {
		e.preventDefault();
		var $item = $(this).closest('.item');
		var $comments = $('.itemComments', $item);
		if ($comments.hasClass('hidden')) {
			$comments.removeClass('hidden');
		} else {
			if ($('.comment, .like', $comments).length == 0) {
				$comments.addClass('hidden');
			}
		}
	});
	$('.likePost').live('click', function(e) {
		e.preventDefault();
		var postID = $(this).attr('id').replace('post','');
		var dataString = 'post='+postID;
		$.ajax({
			type: "POST",
			url: "/home/wall/likePost",
			data: dataString,
			success: function(data){
				var html = $(data)
				$('#post'+postID).replaceWith(html);
			},
			error: function() {
				alert("Unable to like post");
			}		
		 });
	});	
	$('.up').live('click', function(e) {
		e.preventDefault();
		var postID = $(this).attr('id').replace('post','');
		var dataString = 'post='+postID;
		$.ajax({
			type: "POST",
			url: "/home/wall/voteUp",					
			data: dataString,
			success: function(data) {
				if ( jQuery.browser.mozilla ) {var html = $(data);$('#post'+postID).replaceWith(html);}
				else {document.getElementById('post'+postID).outerHTML = data;}
				$('textarea').expandingTextArea();
			},
			error: function(data) {
				alert("Unable to vote up post");
			}		
		 });
	});	
	$('.down').live('click', function(e) {
		e.preventDefault();
		var postID = $(this).attr('id').replace('post','');
		var dataString = 'post='+postID;
		$.ajax({
			type: "POST",
			url: "/home/wall/voteDown",			
			data: dataString,
			success: function(data) {
				if ( jQuery.browser.mozilla ) {var html = $(data);$('#post'+postID).replaceWith(html);}
				else {document.getElementById('post'+postID).outerHTML = data;}
				$('textarea').expandingTextArea();
			},
			error: function(data) {
				alert("Unable to vote down post");
			}			
		 });
	});
	

	
	$('a.popup').live('click', function(e) {
		//e.preventDefault();
		var $b = $(this);
		$.ajax({
			type: 'get',
			url: $(this).attr('data-popupurl'),
			dataType: 'html',
			success: function(data, response) {
				if (data && response == 'success') {
					BN.popup(data, $b.attr('data-popupwidth'));
				}
			},
			error: function(a, b, c) {
			}
		});
	});
		
	$('button.popupSuggest').live('click', function(e) {
		e.preventDefault();
		var event = $(this).attr('event');
		var runner = $(this).attr('runner');
		var market_id = $(this).attr('market_id');

		$.ajax({
			type: "POST",
			url: "/home/suggest/popup",
			data: { event: event, runner: runner, market_id: market_id },
			success: function(data){
				var html = $(data)			

				$('#popupSuggest').replaceWith(html);
				
				$.openDOMWindow({ 	
					windowSourceID:'#popupSuggest',
					loader:1, 
					loaderImagePath:'loading.gif', 
					loaderHeight:48, 
					loaderWidth:48,
					borderSize:'1',
					overlayOpacity:40,
				});
			},
			error: function() {
			}		
		});	
	});	
	
	$('button.popupBet').live('click', function(e) {
		e.preventDefault();
		var postId = $(this).attr('postId');

		$.ajax({
			type: "POST",
			url: "/home/wall/bet",
			data: { postId: postId },
			success: function(data){
				var html = $(data)			

				if ( jQuery.browser.mozilla ) {var html = $(data);$('#popupBet').replaceWith(html);}
				else {document.getElementById('popupBet').outerHTML = data;}
				
				$.openDOMWindow({ 	
					windowSourceID:'#popupBet',
					loader:1, 
					loaderImagePath:'loading.gif', 
					loaderHeight:48, 
					loaderWidth:48,
					borderSize:'1',
					overlayOpacity:40,
				});
			},
			error: function() {
			}		
		});	
	});
	
	$('button.popupRemoveUser').live('click', function(e) {
		e.preventDefault();
		var user = $(this).attr('user');
		var team = $(this).attr('team');;

		$.ajax({
			type: "POST",
			url: "/home/team/removePopup",
			data: { user: user, team: team },
			success: function(data){
				var html = $(data)			

				$('#popupRemoveUserForm').replaceWith(html);
								
				$.openDOMWindow({ 
					windowSourceID:'#popupRemoveUserForm',
					loader:1, 
					loaderImagePath:'/home/images/spinner.gif', 
					loaderHeight:48, 
					loaderWidth:48,
					borderSize:'1',
					overlayOpacity:40,
				});
			},
			error: function() {
			}		
		});	
	});	
	
};

BN.tree = function() {	
	
	$('.accordion').each(function() {
		var $acc = $(this);
		var $cont = $(this).closest('section');
		var $bc = $('.breadcrumbs', $cont);
//		if (!$acc.attr('data-url')) {
//			return;
//		}
		var randId = BN.identifier.randomId();
		var sourcedata;
		var source = {};
		
	  	$.ajax({
				type: 'post',
				url: '/home/betx/updateAccordion',
				success: function(data) {
					$('#accord').html(data);
					closeChilds();
				},
				error: function(data) {
					alert("Error With Accord");
				}
			});
		
//		$.ajax({
//			type: 'get',
//			url: $acc.attr('data-url'),
//			dataType: 'json',
//			success: function(data, response) {
//				if (data && response == 'success') {
//					var _parseChildren = function(item, parent) {
//						source[item.id] = item;
//						source[item.id].parent = parent;
//						if (typeof item.children != 'undefined') {
//							for (var i in item.children) {
//								_parseChildren(item.children[i], item);
//							}
//						}
//					};
//					_parseChildren(data, 'treetop');
//					$acc.html('').append(_createItems(data));
//				}
//			},
//			error: function(a, b, c) {
//				// letŐs just fail silently
//			}
//		});
//		
//		var _createItems = function(data) {
//			var all = '';
//			for (var i in data.children) {
//				var param = '';
//				if (data.children[i].url) {
//					param = 'class="child"';
//				} else {
//					param = 'class="folder"';
//				}
//				all += '<li><a '+param+' id="'+randId+'-'+data.children[i].id+'">'+data.children[i].title+'</a></li>';
//			}
//			return all;
//		};
//		var _createBread = function(data) {
//			var all = '';
//			var param = '';
//			if (typeof data.parent != 'undefined') {
//				param = (data.parent == 'treetop') ? data.parent : '';
//			}
//			all = '<li><a href="'+param+'" id="'+randId+'-'+data.id+'">'+data.title+'</a></li>' + all;
//			if (data.parent != 'treetop') {
//				all = _createBread(data.parent) + all;
//			}
//			return all;
//		};

	  	var closeChilds = function(){
			var divs = document.getElementsByTagName("div");
			for(var i = 0; i < divs.length; i++){
			   //do something to each div like
				if (divs[i].className == 'accordSub') {
					var idy = '#' + divs[i].id.split(' ').join('');
					   $(idy).hide();					
				};
			};
	  	};
	  	
		$('a', $acc).live('click', function(e) {
			if ($(this).hasClass('folder')) {
				e.preventDefault();
				
				$('#BetXSplash').hide();
				$('#sportTitle').html('<section class="competitionSelector '+ $(this).text().split(' ').join('')+ '"><h1>'+$(this).text()+'</h1><div><label for="competition">Select a competition</label></div></section>');
			
				closeChilds();
				
				var idx = '#' + $(this).text().split(' ').join('') + '-Child';
				$(idx).show();
			     $('#eventsList').hide()
				
			  	$.ajax({
			  				type: 'post',
			  				url: '/home/betx/updateSport',
			  				data: 'sport='+ $(this).text(),
			  				success: function(data) {
			  					$('#eventsList').html(data);
			  				}
			  			});
			}
			else {
				e.preventDefault();
				$('#BetXSplash').hide();
				
				var i = 'category='+ $(this).attr('subCat') + '&sport=' + $(this).attr('cat');

			  	$.ajax({
			  				type: 'post',
			  				url: '/home/betx/updateCategory',
			  				data: 'category='+ $(this).attr('subCat') + '&sport=' + $(this).attr('cat'),
			  				success: function(data) {
			  					$('#eventsList').html(data);
			  				}
			  			});
			}
		});

//		var _populate = function(id) {
//			var data = source[id];
//			$acc.html('').append(_createItems(data));
//			$bc.html('').append(_createBread(data));
//			if ($('li', $bc).length == 1) {
//				$bc.html('');
//			}
//			$('a', $bc).click(function(e) {
//				e.preventDefault();
//				_populate($(this).attr('id').split('-')[1]);
//			});
//		};
	});
};

BN.popup = function(markup, size, submit, cancel) {
	if (typeof size == 'undefined') {
		size = 520;
	}
	var popupId = BN.identifier.randomId();
	$('body').append('<div class="popup" id="'+popupId+'"><div class="shadowLeft"></div><div class="shadowTopLeft"></div><div class="shadowTop"></div><div class="shadowTopRight"></div><div class="body"><button class="close"></button>'+markup+'</div><div class="shadowRight"></div><div class="shadowBottomLeft"></div><div class="shadowBottom"></div><div class="shadowBottomRight"></div>');
	$('#'+popupId).css({width: size});
	$('#'+popupId).css({marginTop: '-'+($('#'+popupId).outerHeight()/2)+'px', marginLeft: '-'+($('#'+popupId).outerWidth()/2)+'px'});
	$('#'+popupId+' .shadowLeft, #'+popupId+' .shadowRight').css({height: $('#'+popupId+' .body').outerHeight() - 20});
	$('.popup .close').live('click', function() {
		$(this).closest('.popup').remove();
	});
	BN.widgets($('#'+popupId));
};

$(function() {
	BN.identifier = new BN.Identifier();
	BN.tooltips();
	BN.tabs();
	BN.widgets($('body'));
	BN.wall();
	BN.scroller();
	BN.tree();
});




/**
 * PopWindow
 *
*/



$(document).ready(function(){
	$("#profilePic").mouseenter(function(){
		$("#menu").fadeIn("slow");
	}).mouseleave(function(){
		$("#menu").fadeOut("slow");
	});	

	$('#popup').openDOMWindow({ 	
		eventType:'click', 
		windowSourceID:'#sample',
		loader:1, 
		loaderImagePath:'loading.gif', 
		loaderHeight:48, 
		loaderWidth:48,
		borderSize:'1',
		overlayOpacity:40
	});
	$('#close2').closeDOMWindow({eventType:'click'}); 
	$('#edit').openDOMWindow({ 	
		eventType:'click', 
		windowSourceID:'#editThis',
		loader:1, 
		loaderImagePath:'loading.gif', 
		loaderHeight:48, 
		loaderWidth:48,
		borderSize:'1',
		overlayOpacity:40
	});
	$('#close').closeDOMWindow({eventType:'click'}); 
	$('#suggest').openDOMWindow({ 	
		eventType:'click', 
		windowSourceID:'#sample',
		loader:1, 
		loaderImagePath:'loading.gif', 
		loaderHeight:48, 
		loaderWidth:48,
		borderSize:'1',
		overlayOpacity:40,
	
	});
		
});


$('button.popup').openDOMWindow({ 	
	eventType:'click', 
	windowSourceID:'#sample',
	loader:1, 
	loaderImagePath:'loading.gif', 
	loaderHeight:48, 
	loaderWidth:48,
	borderSize:'1',
	overlayOpacity:40,
});
	
//$('button.popupBet').openDOMWindow({ 	
//	eventType:'click', 
//	windowSourceID:'#betPopup',
//	loader:1, 
//	loaderImagePath:'loading.gif', 
//	loaderHeight:48, 
//	loaderWidth:48,
//	borderSize:'1',
//	overlayOpacity:40,
//
//});

function onSuccessPopupBetForm(data){
	if(data.indexOf('p')==1){
		document.getElementById('form-error-popupBet').innerHTML = data;
	}else{
		var html=$(data);
		if ( jQuery.browser.mozilla ) {var html = $(data);$('#popupBetForm').replaceWith(html);}
		else {document.getElementById('popupBetForm').outerHTML = data;}
	}
}












