$(document).ready(function() {
	
	// mobile site?
	var $m = $("#mobileLogo").length > 0;
	
	// slideup - open day
	if ($("#overlay").length > 0) {
		int2 = setInterval( "popup()", 1000);
	}
	
	
	
	// News Ticker
	if (!$m) {
		$(".marqueeContent").marquee("marqueeContent").hover( function() {
			$(this).trigger('stop');
		}, function() {
			$(this).trigger('start');
		}).mousemove(function (event) {
			if ($(this).data('drag') == true) {
				this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
			}
		}).mousedown(function (event) {
			$(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
		}).mouseup(function () {
			$(this).data('drag', false);
		});
	}

	// Ticker Speaker
	int = setInterval( "animateTickerSpeaker()", randomFromTo(50, 250) );
	
	// Ticker Content Width
	var $tickerWidth = 0;
	$(".marqueeContent ul li").each( function() {
		$tickerWidth += $(this).width();
	});
		$(".marqueeContent ul").width($tickerWidth + 100);
	
	// Init Positions
	resizeFunctions();
	
	// On resize
    $(window).resize(function() {
	    resizeFunctions();
	});
	
	// Random Background Elements
	$("#backgroundElements div, #buffer").not("#skyline").each( function() {
		var $rand = randomFromTo(1, 5);
		if ($rand == 1) {
			$(this).remove();
		}
	});
	
	// Clouds
	$(".animLeft").each( function() {
		animateCloud("left", $(this));
	});
	
	$(".animRight").each( function() {
		animateCloud("right", $(this), 0);
	});
	
	// Planes
	animatePlane("left", $("#plane1"));
	animatePlane("right", $("#plane2"));
	
	// Buffer
	if ($("#buffer").length > 0 && $("#homeMainPanel").length == 0 && $("#pointer").length == 0) {
		placeBuffer();
		$("#buffer").animate({
			opacity: 1
		}, randomFromTo(1000, 10000), function() {
			$(this).animate({
				top: -75
			}, 1000, "easeOutBounce");
		});
	}
	
	// Pointer
	
	if ($("#pointer").length > 0) {
		$("#pointer .close").hide().click( function() {
			$(this).parent().fadeOut();
		});
		$("#pointer").show().animate({
			top : '0px',
			left : '50%'
		}, 1500, 'easeInCirc', function() {
			$("#pointer .signup").animate({
				top : '225px',
				left : '0px'
			}, 500, 'easeOutBounce', function() {
				$("#pointer .close").fadeIn();
			});
		});
	}
		
	
	
	
	// Input Default text
	$("#search input[type=text], #search textarea").each( function() {		
		if ($(this).val() != "") {
		    $(this).parent().find("label").hide();
		}
	});
    
   	$("#search input[type=text], #search textarea").keypress(function() {
		$(this).parent().find("label").fadeOut(150);
    });

    $("#search input[type=text], #search textarea").blur(function() {
        if ($(this).val() == "") {
            $(this).parent().find("label").fadeIn(150);
        }
    });
    
    $("#contactForm input[type=text], #contactForm textarea").focus( function() {
	    $(this).parent().addClass("focused");
    });
    
    $("#contactForm input[type=text], #contactForm textarea").blur( function() {
	    $(this).parent().removeClass("focused");
    });
    
    // Select Box
    if (!$m) {
		$("#careerPanel select").selectBox();
	}
	
	// Equal Heights
   equalHeight($("#bottomPanels .panel .wrapper"));
   
   // Body Minimum Height
   if (!$m) {
	   $("#mainContainer").css("min-height", ($(window).height() - 243) + "px");
	}
   
   // Main Menu Dropdowns
   $("#mainmenu > li").hover( function() {
	   $(this).find("ul").fadeIn();
	   if ($(this).find("ul li ul").length > 0) {
		   equalHeight($("#mainmenu li ul li ul"));
	   }
   }, function() {
	   $(this).find("ul").hide();
   });
   
   
   // Career Results
   $("#mainContent .noJScourseResult").addClass("courseResult").removeClass("noJScourseResult");
   
	$("#careerfinder").submit( function(e) {
		e.preventDefault();
		
		var $l = $("#careerLocation").val();
		var $j = $("#careerCareer").val();
		var $c = $("#careerCourse").val();
		
		if (!$m) {
			$("#careerResultsWrapper").addClass("showingCareers").hide().css({
				'text-align' : 'center',
				'background' : 'url("images/loader.gif") no-repeat center center'
			});
		} else {
			$("#careerResultsWrapper").addClass("showingCareers").hide().css({
				'text-align' : 'center',
				'background' : 'url("images/m/loader.gif") no-repeat center center'
			});
		}
		
		if (!$m) {
			$("#careerPanel .wrapper").animate({
				width: 907
			}, 500, function() {
				$(this).addClass("expanded");
				$(this).find(".closeBtn").show().click( function(e) {
					e.preventDefault();
					$(this).fadeOut();
					$("#careerResultsWrapper").hide(0, function() {
						$("#careerResultsWrapper .scrollingContent").html("");
						$("#bottomPanels .panel").not("#careerPanel").fadeIn();
					});
					$("#careerPanel .wrapper").animate({
						width: 248
					});
				});
			});
			$("#bottomPanels .panel").not("#careerPanel").fadeOut();
			$("#careerResultsWrapper .scrollControls").hide();
			$("#careerResultsWrapper .scrollingContent").html("");
		}
		$("#careerResultsWrapper").show();
		
		$.getJSON('/careerfinder.php', {e:'json', l:$l, j:$j, c:$c}, function(data) {
		    var $results = '';
			if ($m) {
				$results += "<h1>Results</h1>";
			    if (data.length < 1) {
				    $results += '<p>No results were found for this search, please try again.</p>';
			    } else {
				    if ($m) {
					    $results += '<p>Showing ' + data.length + ' results</p>';
				    } else {
					    $results += '<p>We found ' + data.length + ' course(s) based on your search.</p>';
				    }
			    }
			}
			
			$.each(data, function(i, item) {
				if ($m) {
					$results += '<div class="courseResult">';
					$results += '<h2><a href="' + item['url'] + '">' + item['title'] + '</a></h2>';
					$results += '<p>' + item['type'] + ' - ' + item['location'] + '</p>';
					$results += '</div>';
				} else {
					$results += '<div class="courseResult">';
					$results += '<h3><a href="' + item['url'] + '">' + item['title'] + '</a></h3><p>' + item['location'] + '<br />' + item['type'] + '</p><a href="' + item['url'] + '" class="readmore">Read more</a>';
					$results += '</div>';
				}
			});
			
			if ($m) {
				$("#careerResultsWrapper").html($results).removeAttr("style");
				var offset = $("#careerResultsWrapper").offset();
				$("body").animate({
					scrollTop : (offset.top)
				}, 300);
			} else {
				
				$("#careerResultsWrapper .scrollingContent").show();
				$("#careerResultsWrapper").fadeIn(500, function() {
					$("#careerResultsWrapper .scrollingContent").html($results);
					 equalHeight($(".courseResult"));
					 $("#careerResultsWrapper").removeAttr("style");
					
					// Scrolling Courses
					var $w = 612; // results pane width
					var $n = 4; // number of results per pane
					var $f = $("#careerResultsWrapper .courseResult").length * ($w / $n); // width of all courses
					
					if ($("#careerResultsWrapper .courseResult").length > $n) {
					   	$("#careerResultsWrapper .scrollControls").show();
						$("#careerResultsWrapper .scrollControls li.next").removeClass("disabled");
					}
					
					$("#careerResultsWrapper .scrollControls a").click( function(e) {
					   e.preventDefault();
					   if (!$(this).parent().hasClass("disabled")) {
						   var $left = parseFloat($("#careerResultsWrapper .scrollingContent").css("left").replace("px", ""));
						   var $dist = ($(this).parent().hasClass("next")) ? $left - $w : $left + $w;
						   $("#careerResultsWrapper .scrollingContent").animate({
							   left: $dist
						   });
						   
						   if ($dist < 0) {
							   $("#careerResultsWrapper .scrollControls li.prev").removeClass("disabled");
						   } else {
							   $("#careerResultsWrapper .scrollControls li.prev").addClass("disabled");
						   }
						   
						   if ($dist - $w < -($f)) {
							   $("#careerResultsWrapper .scrollControls li.next").addClass("disabled");   
						   } else if ($("#careerResultsWrapper .courseResult").length > $n) {
							   $("#careerResultsWrapper .scrollControls li.next").removeClass("disabled");
						   }
					   }
					   
					});
				});
			}
		});
	});
	
	// FIND US COURSES
	$(".locLinkCourses").hide();
	
	if ($("#nearestLocation").length > 0) {	
		// MOBILE GEOLOCATION
   		equalHeight($("#locationMainContent .panel .content"));
		initLocation($m);
	}
	

});

function initLocation($m) {
	var $uloc;
	
	// Try W3C Geolocation (Preferred)
	if(navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(position) {
			findNearest(position.coords.latitude, position.coords.longitude, $m);
	}, function() {
		// show not found message
		$("#nearestLocation .locLinkView, #nearestLocation .links").hide();
		$("#nearestLocation .content p:first").text("Sorry, we couldn't find your current location.");
		return null;
	});
	// Try Google Gears Geolocation
	} else if (google.gears) {
		var geo = google.gears.factory.create('beta.geolocation');
		geo.getCurrentPosition(function(position) {
			findNearest(position.latitude, position.longitude, $m);
		}, function() {
			// show not found message
			$("#nearestLocation .locLinkView, #nearestLocation .links").hide();
			$("#nearestLocation .content p:first").text("Sorry, we couldn't find your current location.");
			return null;
		});
	// Browser doesn't support Geolocation
	} else {
		// show not found message
		$("#nearestLocation .locLinkView, #nearestLocation .links").hide();
		$("#nearestLocation .content p:first").text("Sorry, we couldn't find your current location.");
	}
}

function findNearest(lat, long, $m) {
	
	var userLoc = new google.maps.LatLng(lat, long);
	
	var locations = new Array();
	locations['headoffice'] = new google.maps.LatLng(51.5355877, -0.1063233);
	locations['basildon'] = new google.maps.LatLng(51.5717709, 0.4582278);
	locations['bethnalgreen'] = new google.maps.LatLng(51.5333689, -0.0575223);
	locations['grays'] = new google.maps.LatLng(51.4766137, 0.324616);
	locations['lowestoft'] = new google.maps.LatLng(52.477611, 1.7519817);
	locations['peckham'] = new google.maps.LatLng(51.4667906, -0.0675067);
	locations['rotherham'] = new google.maps.LatLng(53.4329318, -1.3598824);
	locations['sheffield'] = new google.maps.LatLng(53.4116501, -1.5021879);
	locations['braintree'] = new google.maps.LatLng(51.8699797, 0.5709657);
	locations['leeds'] = new google.maps.LatLng(53.7991268, -1.5400171);
	
	var closest = 999999999;
	var closestKey;
	
	for (loc in locations) {
		distance = calcDistance(userLoc, locations[loc]);
		if (parseFloat(distance) < parseFloat(closest)) {
			closestKey = loc;
			closest = distance;
		}
	}
	// show "nearest" content based on key
	if ($m) {	
		$("#nearestLocation").show().find(".mobLocation").html($("#" + closestKey).html());
	} else {
		$.getJSON('/getLocation.php', {l:closestKey}, function(data) {		
			var $address = "";
			for ($i=1;$i<=5;$i++) {
				if (data['address_' + $i] !== null) {
					if ($i == 2 || $i == 3) {
						$address += "<br />";
					} else if ($i > 1) {
						$address += ", ";
					}
					$address += data['address_' + $i];
				}
			}
			
			var $mapaddress = data['map_search_string'].replace(/ /g, "+");
			
				
			$("#nearestLocation img.map").attr({
				"src": "/images/map_home_" + data['slug'] + ".jpg",
				"alt": data['courselocationname'],
				"title": data['courselocationname']
			});
			$("#nearestLocation .character img").attr({
				"src": "/images/map_character_" + data['slug'] + ".png",
				"alt": data['courselocationname'],
				"title": data['courselocationname']
			});
			$("#nearestLocation .locName").text(data['courselocationname']);
			$("#nearestLocation .locAddress").html("<strong>" + $address + "</strong>");
			$("#nearestLocation .tel").text(data['telephone_1']);
			$("#nearestLocation a.locLinkView, #nearestLocation li.locLinkView a").attr({
				"href": "http://maps.google.co.uk/maps?q=" + $mapaddress + "&hl=en&t=m&z=16",
				//"href": "http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&geocode=&q=" + $mapaddress + "&ie=UTF8&hq=&hnear=" + $mapaddress + "&z=16",
				"target": "_blank"
			});
			
			$("#nearestLocation").show();
   			equalHeight($("#locationMainContent .panel .content"));
		});
	}
	
	// hide "other" content based on key
	$("#" + closestKey).hide();	
}

function calcDistance(p1, p2){
  return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}



function animateTickerSpeaker() {
	if (!$("#speaker").hasClass("pumped")) {
		$("#speaker").css({
			top: "-8px",
			right: "98px",
			backgroundPosition : "0px -75px"
		}).addClass("pumped");
	} else {
		$("#speaker").css({
			top: "-6px",
			right: "100px",
			backgroundPosition : "0px 0px"
		}).removeClass("pumped");
	}
	
	// reset timer
	clearInterval(int);
	int = setInterval( "animateTickerSpeaker()", randomFromTo(50, 250) );
}

function randomFromTo(from, to){
   return Math.floor(Math.random() * (to - from + 1) + from);
}

function resizeFunctions() {
	
	// Logo Cloud
	$lcX = (($(window).width() - 960) / 2) - 220;
	$("body").css({
		backgroundPositionX : $lcX + "px"
	});
	
	placeBuffer();
	placePlane("left", $("#plane1"));
	placePlane("right", $("#plane2"));
	
}

function animateCloud($direction, $cloud, $step) {
	
	var $ww = $(window).width();
	var $w = $cloud.width();
	
	// css
	if ($step > 0) {
		var $args = {};
		$args[$direction] = "-" + $w + "px";
		$cloud.css($args);
	}
	
	// animate
	var $args = {top: randomFromTo($cloud.offset().top - 50, $cloud.offset().top + 50)};
  	$args[$direction] = $ww + $w;
	$cloud.animate($args, randomFromTo(30000, 40000), function() {
		animateCloud($direction, $cloud, 1);		
	});
	
}

function animatePlane($direction, $plane) {
	
	var $ww = $(window).width();
	var $wh = $(window).height();
	var $w = $plane.width();
	var $h = $plane.height();
	
	// css
	placePlane($direction, $plane)
	
	// animate
	var $args = {top: randomFromTo(-500, 150)};
  	$args[$direction] = $ww + $w;
	$plane.animate({
		opacity: 1
	}, randomFromTo(2500, 10000), function() {
		$(this).animate($args, randomFromTo(3000, 4000), "easeInCirc");
	});
	
}

function equalHeight(selector) {
	var maxHeight = 0;
	selector.each( function() {
		if ($(this).height() > maxHeight) {
			maxHeight = $(this).height();
		}
	});
	
	$(selector).height(maxHeight);
}

function placeBuffer() {
	$c = (($(window).width() - 960) / 2) - 125;
	$("#buffer").css({
		right: $c		
	});
}

function placePlane($direction, $plane) {
	var $ww = $(window).width();
	var $wh = $(window).height();
	var $w = $plane.width();
	var $h = $plane.height();
	
	var $args = {"top": randomFromTo(($wh + 150), ($wh + 250)) + "px"};
	$args[$direction] = "0px"
	$plane.css($args);
}

function popup() {
	$("#overlay").height($(document).height()).fadeIn(500, function() {
		$("#slideup").show().animate({
			bottom: -5
		}, 2000, "easeInCirc", function() {
			$("#slideupCallout").animate({
				top: -6,
				left: -47
			}, 500, "easeOutBounce");
		});
	});
	
	$("#overlay a, #slideup a").click (function(e) {
		e.preventDefault();
		$("#slideupCallout").fadeOut(function() {
			$("#slideup").fadeOut(function() {
				$("#overlay").fadeOut();
			});
		});
	});
	
	clearInterval(int2);
}
