$(document).ready(function(){

$("body").removeClass("unscripted");

//COMMON VARIABLES
var bgImageWidth = 1500;
var bgImageHeight = 1000;
dimensionsInt();
$("#content").fadeIn("fast");
$.ajaxSetup({cache: false});
$("#content").ajaxError(function(event, request, settings){
$(this).append("<div style='width:90%;padding:4px;border:2px solid red;background:#FFF;color:red;margin:10px;'>Unfortunately there was an error displaying the page you were looking for. Please try again.</div>");
});

// DIMENSION SETTINGS, DETERMINE BACKGROUND IMAGE SIZE AND THE CONTAINER HEIGHT.	
$(window).resize(function(){dimensionsInt();});

function dimensionsInt(pageSwitch){
	var widthToSet = $(window).width();
	var heightToSet = $(window).height();
	var ratioToSet = widthToSet / heightToSet;
	var imageRatio = bgImageWidth / bgImageHeight;
	if (ratioToSet > imageRatio) {
		var imgHeight = (widthToSet / bgImageWidth) * bgImageHeight;
		var imgWidth = widthToSet;
	} else {
		var imgHeight = heightToSet;
		var imgWidth = (heightToSet / bgImageHeight) * bgImageWidth;
	}	
	var imgTop = 0 - ((imgHeight - heightToSet) / 2);
	var imgLeft =  0 - ((imgWidth - widthToSet) / 2);
	$("#mainBg").css({"height": heightToSet, "width": widthToSet});
	$("#insidecontainer").css("height", heightToSet);
	$("#loader").css("height", heightToSet - 134);
	$('#mainBg img').css({"height": imgHeight, "width": imgWidth, "top": imgTop, "left": imgLeft});
	var botOffset = ((heightToSet - 170) / 2) - (parseInt($("#content").css("height")) / 2);
	if(botOffset < 95){ botOffset = 95; }
	$("#content").css("top", botOffset);
	
}

// MAIN NAV LINKS

$("#navigation a").bind({					
  click: function() {
    pagePrep($(this).parent("li").attr("id"));
	return false;
  },
  mouseenter: function() {
    $(this).children("span").fadeIn(150);
  },
  mouseleave: function(){
	$(this).children("span").fadeOut(5);
  }
});		

// START LOADER AND GRAB URL OF PAGE TO BE LOADED

function pagePrep(contentID, contentUrl){
	
	$("#loader").fadeIn("fast");
	var contentUrl;
	$("body").attr('id', 'page-' + contentID + '');
		switch (contentID) {
		case 'home':
		contentUrl = "/index.php";
		break;
		case 'news':
		contentUrl = "/page/news/index.php";
		break;
		case 'individual': case 'finance': case 'share': case 'location': case 'contact':
		contentUrl = "/page/" + contentID + ".php";
		break;
		case 'gallery':
		contentUrl = "/page/gallery/index.php"; break;
		case 'stock':
		contentUrl = "/page/stock/index.php"; break;
		default: ;
		}
	var leftCalc = (parseInt($("#insidecontainer").css("width")) - parseInt($("#content").width())) / 2;
	$("#content")
	.fadeOut("fast")
	.attr("style", "")
	.css("left", leftCalc);
	$("#mainBg").fadeOut("fast", function(){
		$(this).html("<img src='/images/backgrounds/"+ contentID + "-xl.jpg' />");
			$("#content").load('' + contentUrl + ' #c', function(){
				if ($.browser.msie  && parseInt($.browser.version) == 9) {
				
					pageLoad();
				
				}else{
				
				$("#mainBg").onImagesLoad({ 
             	selectorCallback: pageLoad
				});
				
				}
		});

	});
	
}

function pageLoad($selector){
		dimensionsInt();
		$("#mainBg, #content").fadeIn("fast");
		$("#loader").fadeOut();
		firePageFunctions($("body").attr('id').replace('page-', ''));		
}

// SPECIFIC PAGE FUNCTIONS THAT NEED TO BE FIRED WHEN A SPECIFIC PAGE IS LOADED
function firePageFunctions(page){	
		switch(page){
		case 'news':
		$('#newsScroll').jScrollPane({showArrows:true});
		break;
		case 'news-view':
		$('#newsContent').jScrollPane({showArrows:true});
		break;
		case 'contact':
		manageContactForm();
		break;
		case 'gallery':
		galleryInt();
		break;
		case 'gallery-view':
		subGalleryInt();
		break;
		case 'stock':
		stockInt();
		break;
		case 'stock-view':
		loopStockGallery(true);
		break;
		case 'individual':
		$('#indscroll').jScrollPane({showArrows:true});
		break;
		case 'location':
		loadMap();
		break;
		default: ;
		}		
}

// GALLERY PAGES SETUP
function galleryInt(){
	var InTrans = false;
	$("#content ul li img").fadeTo("fast", "0.5");
	$("#content ul li:nth-child(3)").animate({ 'width': 439}, 500, function(){ $(this).addClass('active');$(this).children('div').fadeIn("fast");$(this).children('img').fadeTo("fast", "1"); });
	$("#content ul li").hover(function(){
		if($(this).width() < 100 && InTrans == false){
			InTrans = true;
			$("#content ul li").children("div").fadeOut("fast");$("#content ul li").children("img").fadeTo("fast", "0.5");
			var toAnimate = $(this);
			toAnimate.animate({ 'width': 439}, 400, function(){ $(this).addClass("active");$(this).children('div').fadeIn("fast");$(this).children('img').fadeTo("fast", "1");InTrans = false; });
			$("#content ul li.active").removeClass("active").animate({ 'width': 83 }, 400);
			}
	});
}

function subGalleryInt(){

	$("#galleryhold > div").hide("fast");
	$("#galleryhold div:first").show("fast");
	if($("#galleryhold > div").length < 2){
		$(".next.subGallery, .prev.subGallery,").hide("fast");	
	}

}

function galleryJump(goTo){

	var pageShowing = $("#galleryhold > div:visible");
	if(goTo == "next"){
	if($("#galleryhold div:last").is(":visible")){
	pageShowing.hide("fast", function(){ $("#galleryhold div:first").show("fast"); }); 
	}else{
	pageShowing.hide("fast", function(){ $(this).next("div").show("fast"); }); 
	}
	}
	
	if(goTo == "prev"){
	if($("#galleryhold div:first").is(":visible")){
	pageShowing.hide("fast", function(){ $("#galleryhold div:last").show("fast"); }); 
	}else{
	pageShowing.hide("fast", function(){ $(this).prev("div").show("fast"); }); 
	}
	}
	
}

function showGalleryImage(clicked){
	
clicked.addClass("active");
var leftCalcIV = $(window).width() / 2 - ($("#imageViewer").outerWidth() / 2);
$("#imageViewer #img").html("<img src='" + clicked.attr("href") + "' />");
$("#imageViewer")
.css("left", leftCalcIV)
.show("fast", function(){ 
$("#mainBg").fadeTo("fast", 0.3);
$("#content").fadeTo("fast", 0);
$("#navigation").hide("fast");
});

}

function closeGalleryImage(){
	
	$("#imageViewer").css("display", "none");
	$("#mainBg").fadeTo("fast", 1, function(){  $("#content").fadeTo("fast", 1); });
	$("#content .imageView.active").removeClass("active");
	$("#navigation").show("fast");
	
}

function imageJump(goTo){
	
	var showing = $("#galleryhold").find('a.active');
	if(goTo == "prev"){
		if($("#galleryhold > div a:first-child").hasClass("active")){
			toShow = $("#galleryhold > div a:last-child");
		}else{
		var toShow = showing.prev('a');
		}
	}else{
		if($("#galleryhold > div a:last-child").hasClass("active")){
			toShow = $("#galleryhold > div a:first-child");
		}else{
		var toShow = showing.next('a');
		}
		
	}
	showing.removeClass("active");
	toShow.addClass("active");
	$("#imageViewer #img").html("<img src='" + toShow.attr('href') + "' />");
	
}

// FUNCTIONS FOR MAIN STOCK LISTING
function stockInt(){		$("#stockPages").css("margin-left", (parseInt($("#insidecontainer").css("width")) / 2) - (parseInt($("#stockPages").css("width")) / 2) - 35);}

function stockJump(nextPage){
		
		var nextPage;
		var numofpages = $("#stockPages li").length - 3;
		var productHoldWidth = 900;
		var prevPage = $("#stockPages a.active");
		var movingDirection = "forward";
		var shiftLeft;
		var pageJump = Number(prevPage.html()) - Number(nextPage.html());
		pageJump = Math.abs(pageJump);
		if(nextPage.parent().hasClass("last")){
			if(Number(prevPage.attr("href")) < Number(numofpages)){
			nextPage = $("#stockPages a.active").parent("li").next("li").children("a");
			pageJump = 1;
			}else{
				$("#stockPages a").removeClass("disabled");
				return false;
			}
		}
		if(nextPage.parent().hasClass("first")){
			if(Number(prevPage.attr("href")) > 1){
			nextPage = $("#stockPages a.active").parent("li").prev("li").children("a");
			pageJump = 1;
			}else{
				$("#stockPages a").removeClass("disabled");
				return false;
			}
		}
		
			if(Number(prevPage.html()) > Number(nextPage.html())){ movingDirection = "backward"; }
			if(movingDirection == "forward"){	
				shiftLeft = parseInt($("#stockScroll ul").css("margin-left")) - (Number(pageJump) * Number(productHoldWidth));
							
			}else{	
				shiftLeft = parseInt($("#stockScroll ul").css("margin-left")) + (Number(pageJump) * Number(productHoldWidth));	
			}
			
			
		$("#stockScroll ul").animate({"margin-left": shiftLeft}, 1000, function(){ $("#stockPages a").removeClass("disabled"); });
		prevPage.removeClass("active");
		nextPage.addClass("active");

						
}
$("#stockPages a").live("click", function(){ if(!$(this).hasClass("disabled")){ $("#stockPages a").addClass("disabled");stockJump($(this));}return false;});

// CAR VIEW IMAGE GALLERY FUNCTIONS
function loopStockGallery(isFirst){

	if($("#images ul").length > 0){
	if($("#images ul li a:last").hasClass("active") || isFirst){
	$("#images > img").stop(true, false);
	var nextToShow = $("#images ul li a:first");
	}else{
	var nextToShow = $("#images ul li a.active").next("a");
	}
	$("#images ul li a").removeClass("active");
	nextToShow.addClass("active");
	$("#images > img")
	.attr("src", nextToShow.attr("href"))
	.delay(2000)
	.animate({"opacity": 1}, 2000, function(){loopStockGallery(false);}
	);
	}
	
}

$("#images ul").live('mouseover', function(){$("#images > img").stop(true, false);});

function switchCarViewImage(clicked){
var toShow = clicked;
$("#images li a").removeClass("active");
toShow.addClass("active");
$("#images > img").attr("src", toShow.attr("href"));
	
}

// CONTACT FORM
function manageContactForm(){
		
	$("#contactform input[type!=submit], #contactform textarea").focus(function(){
	$(this).val("");
	});
	
	$("#contactform").submit(function(){
	var name = $("#name").val();
	var phone = $("#phone").val();
	var email = $("#email").val();
	var message = $("#message").val();
	if(name == "" || phone == "" || email == "" || message == ""){
	
		alert("Please ensure you have entered all fields on the form and try again");
		return false;
	
	}
	var dataString = 'name='+ name + '&phone=' + phone + '&email=' + email + '&message=' + message + '&submit=send';	
	$.ajax({
      type: "POST",
      url: "/page/contact-send.php",
      data: dataString,
      success: function() {
        $('.contactInfo + div').html("<h3><strong>Your message has been successfully sent. We will be in touch as soon as possible.</strong></h3>");
      }
     });
    return false;						  
	});
	
}
// LOAD GOOGLE MAPS FOR LOCATION PAGE
function loadMap(){
	
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        var point = new GLatLng(53.5785, -2.3088);
        map.setCenter(new GLatLng(53.5785, -2.3088), 16);
		map.addOverlay(new GMarker(point));
		map.setMapType(G_HYBRID_MAP);
        map.setUIToDefault();
      }
	  
}

// LINKS AND LIVE LINKS
// main page links
$("a.button, a#galleryView, a#stock-view, a#news-view").live("click", function(){
if(!$(this).hasClass("External")){
pagePrep($(this).attr("id"), $(this).attr("href"));	
return false;
}
});
// make the whole list item for stock clickable
$("#stockScroll li").live("click", function(){pagePrep("stock-view", $(this).find("a").attr("href"));return false;});
// show and hide images in the gallery section
$(".imageView").live("click", function(){showGalleryImage($(this));return false;});
$("#closeImage").live("click", function(){closeGalleryImage();return false;});
// cycle through images in any given gallery
$(".next.imageJump").live("click", function(){ imageJump("next"); return false;});
$(".prev.imageJump").live("click", function(){ imageJump("prev"); return false;});
// jump between gallery pages
$(".next.subGallery").live("click", function(){ galleryJump("next"); return false;});
$(".prev.subGallery").live("click", function(){ galleryJump("prev"); return false;});
// image switch for car view pages
$("#images li a").live("click", function(){	switchCarViewImage($(this)); return false;});
// make the whole list for gallery list clickable
$("#page-gallery #c li").live("click", function(){pagePrep("gallery-view", $(this).find("a").attr("href"));return false;});

});


