checkExternalClick = function(event)
{
  if ($(event.target).parents('.activedropdown').length === 0)
  {
    $('.activedropdown').removeClass('activedropdown');
    $('.options').hide();
  }
};

var toggleFBBox;

$(document).ready(function() {
	
	
	$('#subnav, .rforce').hover(
		function(){
		
			$('#subnav').show();
			$('.rforce').addClass('selected');
		
		},
		function(){
		
			$('#subnav').hide();
			$('.rforce').removeClass('selected');
		
		}
	);

	$(document).mousedown(checkExternalClick);
	function positionElements() {
  		var supMarg = Math.ceil(($(window).height()-590)/2);
		
		if ($("#supportterms").length) {
			if (supMarg>0) $("#supportterms").css("margin-top",supMarg);
		}
		
		if ($(".footer").length) {
			var spaceLeft = $(window).height()-$(".main").height()-110-70-95;
			if (spaceLeft>0) {
				$(".footer").css("top",spaceLeft);
			} else {
				$(".footer").css("top",0);
			}
		}
	}
	
	$(window).resize(positionElements);
	positionElements();
	
	if ($("#clubmap").length) {
		initialize();
	}	
	
	var z = 999;
	var minItemsForScroll = 12;
	
	
	if ($("#termsclose").length) {
		
		$("#termsclose").click(function() {
			$("#filter").hide();
			$("#positioner").hide();
			$('head').find("#termsprint").remove();
		});
		
		$("#termsopener").click(function() {
			$("#filter").show();
			$("#positioner").show();
		});
		
		
	}
	
	if ($(".termsselector").length) {
		
		$(".termsselector").each(function() {
			
			$("#roi").click(function() {
				$("#termsroi").show();
				$("#termsni").hide();
				$(this).addClass("selected");
				$("#ni").removeClass("selected");
			});
			
			$("#ni").click(function() {
				$("#termsroi").hide();
				$("#termsni").show();
				$(this).addClass("selected");
				$("#roi").removeClass("selected");
			});
			
			$(this).find(".print").click(function() {
				window.print();
			});
			
			$('head').append('<link type="text/css" rel="stylesheet" media="print" href="css/global/print.css" id="termsprint"/>');
			
		});
		
		$("#register").click(function() {
			if ($("#tcsaccept").is(':checked')) {
				$("#error").hide();
				if (_gaq) {_gaq.push(['_trackEvent', 'Outbound Links', 'rugby.rbs.co.uk/RBS-RugbyForce/Register']); }
				window.open('https://rugby.rbs.co.uk/RBS-RugbyForce/Register.aspx','Register');
			} else {
				$("#error").show();
			}
		});
		
	}
	
	//alert("gat: "+_gat);


	if ($(".clubdrop").length) {
		
		$("#province").empty().append("<option value='0'>- Select province -</option>");
		for (var b=0; b<provinceArray.length; b++) {
			$("#province").append("<option value='"+provinceArray[b]+"'>- "+provinceArray[b]+"</option>");
		}	
		
		function sortClubsByName(a, b) {
		    var x = a[2];
		    var y = b[2];
			return ((x < y) ? -1 : ((x > y) ? 1 : 0));
		}
		
		var allClubsSorted = clubArray;
		allClubsSorted.sort(sortClubsByName);
		
		function findClubs(province) {
			var provClubs = new Array();	
			for (var c=0; c<clubArray.length; c++) {
				if (clubArray[c][1] == province) provClubs.push(clubArray[c]);
			}
			//alert(provClubs);
			return provClubs;
		}
		
		function findClub(id) {
			var selClub = new Array();	
			for (var c=0; c<clubArray.length; c++) {
				if (clubArray[c][0] == id) {
					selClub.push(clubArray[c]);
					break;
				}
			}
			return selClub;
		}
		
		$(".submit").click(function() {
			var clubSelected = 0;
			var provSelected = 0;
			
			$("#province").each(function() {
				provSelected = $(this).parent().find('span.selindex').text();
			});
			
			$("#club").each(function() {
				clubSelected = $(this).parent().find('span.selindex').text();
			});
			
			if (provSelected != "0") {
				if (clubSelected != "0") {
					setMarkers(findClub(clubSelected));
				} else {
					setMarkers(findClubs(provSelected));
				}
			} else {
				if (clubSelected != "0") {
					setMarkers(findClub(clubSelected));
				} else {
					setMarkers(clubArray);
				}
			}
			
		});
		
		function populateClubs(province) {
			//alert("populateClubs('"+province+"');")
			var provinceClubs = findClubs(province);
			provinceClubs.sort(sortClubsByName);
			
			$("#club").empty().append("<option value='0'>- Select club -</option>");
			for (var b=0; b<provinceClubs.length; b++) {
				$("#club").append("<option value='"+provinceClubs[b][0]+"'>- "+provinceClubs[b][2]+"</option>");
			}
			
			rebuildSelects("club");
			//setMarkers(findClubs(province));
		}
		
		function loadAllClubs(){
		
			$("#club").empty().append("<option value='0'>- Select club -</option>");
		
			var allClubsHtml = "";
			for (var b = 0; b < clubArray.length; b++) {
				allClubsHtml += "<option value='" + clubArray[b][0] + "'>- " + clubArray[b][2] + "</option>";
			} 
			
			$("#club").append(allClubsHtml);
			
			
			
			rebuildSelects("club");
			
			
			
			//setMarkers(clubArray);
		}
		
		function pulseButton() {
			$("#showmap").animate({
    			opacity: 0.3
  			}, 200, function() {
    			$("#showmap").animate({
					opacity: 1
	  			}, 200, function() {
					
					$("#showmap").animate({
		    			opacity: 0.3
		  			}, 200, function() {
		    			$("#showmap").animate({
							opacity: 1
			  			}, 200, function() {}
						);
		  			}
					);
					
				}
				);
  			}
			);

		}
		
		toggleFBBox = function(mode) {
			
			//alert("toggleCalled");
			
			if (!mode) {
				$("#loadingbox").hide();
				$("#fblogin").hide();
				
				loadAllClubs();
				if (urlClub != 0) {
					setMarkers(findClub(urlClub));
				} else {
					setMarkers(clubArray);
				}
				//alert("hidden loading, hidden fb overlay");
				
			} else {
				
				$("#fblogin").show();
				$("#loginbox").show();
				$("#loadingbox").hide();
				
				//alert("hidden loading, shown fb overlay");
			}
			$("#clubselection").css("visibility","visible");
		}
		
		var fbuser = false;
		
		FB.init({
			appId  : '177398238966965',
			status : true, // check login status
			cookie : true, // enable cookies to allow the server to access the session
			xfbml  : true  // parse XFBML
		});
		
		FB.getLoginStatus(function(response) {
		
		  if (response.session) {
		
			fbuser = true;
			toggleFBBox(false);
		    
		  } else {
		  	
			fbuser = false;
			toggleFBBox(true);
			
		  }
		  
		});
		
		

		
		
		
	}
	

	if ($(".paging").length) {
	
		
		var currPage = 1;
		var pagesFound = 0;
		
		$(".infopage").each(function(g) {
			pagesFound++;
			$(this).attr("id", "page" + eval(g + 1));
			//alert("page"+eval(g+1));
		});
	
		function updatePages(e) {
			
			//alert("update called");
			
			$(".infopage").each(function(x){
				$(this).hide();
			});				
			//alert("jest");
			//alert("currPage: "+currPage)
			
			$("#page"+currPage).show();
			
			
			if (currPage < pagesFound) {
				$(".next").addClass("active");
				$(".next").unbind();
				$(".next").one('click', function() {
					currPage++;
					//alert("dodaje");
					updatePages();
					return false;
				});
				//alert("currPage: "+currPage+" / "+pagesFound);
				
				if (currPage > 1) {
					$(".prev").addClass("active");
					$(".prev").unbind();
					$(".prev").one('click', function() {
						currPage--;
						//alert("odejmuje");
						updatePages();
						return false;
					});
					//alert("currPage: "+currPage+" / "+pagesFound);
					
	
				} else {
					//alert("ostatnia: "+$(this).find(".next"))
					$(".prev").removeClass("active");
				}
	
				
			} else {
				//alert("ostatnia: "+$(this).find(".next"))
				$(".next").removeClass("active");
			}
			
			
			
						
			
		
			
			//alert(pagesFound);

		};
		updatePages();
	
		
	}
	
	if ($(".gallery").length) {
		
		var initPos = 0;
		var itemWidth = 275;
		var itemNum = 0;
		

		$(".galitem").each(function(a){
			
			$(this).css("left",eval(initPos+(a*itemWidth)));
			itemNum++;
			
		});
		
		var minPos = itemWidth*3-itemWidth*itemNum;
		//alert("minpos: "+minPos);
		var maxPos = 0;
		
		if (initPos <= minPos) $("#slideright").addClass("disabled");
		if (initPos >= maxPos) $("#slideleft").addClass("disabled");
		
		$("#slideleft").click(function(){
			
			//alert("newpos: "+initPos);
			if (initPos+itemWidth <= maxPos) {
				initPos += itemWidth;
				
				if (initPos == maxPos) {
					$(this).addClass("disabled");
					if (initPos >= minPos) {
						$("#slideright").removeClass("disabled");	
					}
				} else {
					$(this).removeClass("disabled");
					if (initPos >= minPos) {
						$("#slideright").removeClass("disabled");	
					}
				}
				
				$(".galitem").each(function(a){
				
					$(this).animate({
    					left: eval(initPos + eval(a * itemWidth))
    				}, 800, function foobar() {
    					// Animation complete.
  					});
			
					
					//$(this).css("left", );
					//alert($(this).css("left"));
				//$(this).css("left",eval(a*itemWidth));
				});
			}
			
		});
		
		$("#slideright").click(function(){
			
			//alert("newpos: "+initPos);
			if (initPos-itemWidth >= minPos) {
				initPos -= itemWidth;
				
				if (initPos == minPos) {
					$(this).addClass("disabled");
					if (initPos <= maxPos) {
						$("#slideleft").removeClass("disabled");	
					}
				} else {
					$(this).removeClass("disabled");
					if (initPos <= maxPos) {
						$("#slideleft").removeClass("disabled");	
					}
				}
				
				$(".galitem").each(function(a){
				
					$(this).animate({
    					left: eval(initPos + eval(a * itemWidth))
    				}, 800, function foobar() {
    					// Animation complete.
  					});
				
					//$(this).css("left", eval(initPos + eval(a * itemWidth)));
					//alert($(this).css("left"));
				//$(this).css("left",eval(a*itemWidth));
				});
			}
			
		});
		
	}
	
	function rebuildSelects(selectid){
	
		
		//alert("selectid: "+selectid);
		
		// start of rebuildSelects
	
		$('select').each(function(){
			var selectclass = $(this).attr("class");
			var selectident = $(this).attr("id");
			
			//alert(selectid)
			if (selectid == "") {
				selectident = "";
			}
			
			if (selectclass != "" && selectident == selectid) {
				
				
				$(this).parent().removeClass('enhanced');
				$(this).parent().find("dl").remove();
				if (!$(this).parent().hasClass('enhanced')) {
					targetselect = $(this);
					targetselect.hide();
					
					// set our target as the parent and mark as such
					var target = targetselect.parent();
					target.addClass('enhanced');
					
					// prep the target for our new markup
					target.append('<dl class="dropdown ' + selectclass + '"><dt><a class="dropdown_toggle" href="#"></a></dt><dd><div class="options ' + selectclass + '"><ul></ul></div></dd></dl>');
					target.find('.dropdown').css('zIndex', z);
					z--;
					
					// we don't want to see it yet
					target.find('.options').hide();
					
					// parse all options within the select and set indices
					var i = 0;
					targetselect.find('option').each(function(){
						// add the option
						target.find('.options ul').append('<li><a href="#"><span class="value">' + $(this).text() + '</span><span class="hidden index">' + $(this).val() + '</span></a></li>');
						
						// check to see if this is what the default should be
						if ($(this).attr('selected') == true) {
							targetselect.parent().find('a.dropdown_toggle').append('<span></span>').find('span').text($(this).text());
							targetselect.parent().find('a.dropdown_toggle').append('<span class="hidden selindex"></span>').find('span.selindex').text($(this).val());
						}
						
						i++;
						
						if (i == minItemsForScroll) 
							target.find('.options').addClass("biggie");
					});
					if (i == 1) 
						target.find('.options').css("top", "25px");
				}
			}
		});
		
		// let's hook our links, ya?
		$('a.dropdown_toggle').die('click');
		$('a.dropdown_toggle').live('click', function(){
			var theseOptions = $(this).parent().parent().find('.options');
			if (theseOptions.css('display') == 'block') {
				$('.activedropdown').removeClass('activedropdown');
				theseOptions.hide();
			}
			else {
				theseOptions.parent().parent().addClass('activedropdown');
				theseOptions.show();
			}
			
			return false;
		});
		
		// bind to clicking a new option value
		$('.options a').die('click');
		$('.options a').live('click', function(e){
			$('.options').hide();
			
			var enhanced = $(this).parent().parent().parent().parent().parent().parent();
			var realselect = enhanced.find('select');
			
			// set the proper index
			realselect[0].selectedIndex = $(this).find('span.index').text();
			
			// update the pseudo selected element
			enhanced.find('.dropdown_toggle').empty().append('<span></span>').find('span').text($(this).find('span.value').text());
			enhanced.find('.dropdown_toggle').append('<span class="hidden selindex"></span>').find('span.selindex').text($(this).find('span.index').text());
			
			//alert("kliknieto: "+$(this).find('span.value').text().substr(2,100));
			
			if (realselect.attr("id") == "province") {
				var clickedItemValue = $(this).find('span.index').text();
				if (clickedItemValue != "0") {
					populateClubs(clickedItemValue);
				} else {
					loadAllClubs();
				}
			}
			
			if (realselect.attr("id") == "province" || realselect.attr("id") == "club") {
				pulseButton();
			}
			
			
			return false;
		});
		
		
		// end of rebuildSelects
	}
	
	if ($(".toolkit").length) {
		
		
		var linksNum = $(".toolkit div a").length;
		var linkW = $(".toolkit div a").width();
		var minLeft = (linkW*(linksNum-3)*-1);
		var maxLeft = 0;
		$(".toolkit div").css("width",(linkW*linksNum));
		
		//alert(minLeft+", "+maxLeft);
		
		function updateToolkit() {
			
			var currLeft = $(".toolkit div").css("left");
			var currLeftNum = parseInt(currLeft.substr(0,currLeft.length-2));
			
			if (currLeftNum >= maxLeft) {
				$("#sleft").addClass("disabled");
			} else {
				$("#sleft").removeClass("disabled");
			} 
			
			if (currLeftNum <= minLeft) {
				$("#sright").addClass("disabled");
			} else {
				$("#sright").removeClass("disabled");
			} 
			
			$("#sleft").removeClass("inactive");
			$("#sright").removeClass("inactive");
		}
		
		$("#sleft").each(function() {
			$(this).click(function() {
				
				if (!$(this).hasClass("disabled") && !$(this).hasClass("inactive")) {
					var currLeft = $(".toolkit div").css("left"); 
					var currLeftNum = parseInt(currLeft.substr(0,currLeft.length-2));
					
					$(this).addClass("inactive");
					if (currLeftNum<maxLeft) $(".toolkit div").animate({
						left:currLeftNum+linkW
					}, 500, function() {
						//alert($(".toolkit div").css("left"));
						
						updateToolkit();
					});
					
					
					
				}
				
			});
		});
		
		$("#sright").each(function() {
			
			$(this).click(function() {
				if (!$(this).hasClass("disabled") && !$(this).hasClass("inactive")) {
					var currLeft = $(".toolkit div").css("left"); 
					var currLeftNum = parseInt(currLeft.substr(0,currLeft.length-2));
					
					$(this).addClass("inactive");
					if (currLeftNum>=minLeft) $(".toolkit div").animate({
						left:currLeftNum-linkW
					}, 500, function() {
						//alert($(".toolkit div").css("left"));
						updateToolkit();
					});
					
					
					
				}
				
			});
		});

				
		
		
		
	}	
	
	rebuildSelects("");
	//rebuildSelects("province");
	
});
