// 2010(c)Meat Digital AS //
// All site spesific javascripts here

$.fx.prototype.cur = function(){ // we are overwriting this function to remove limiting of the size of the
    if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
      return this.elem[ this.prop ];
    }
    var r = parseFloat( jQuery.css( this.elem, this.prop ) );
    return typeof r == 'undefined' ? 0 : r; 
}


var org_width;
var org_height;
var timeoutID;

function fallback_bgfade() {

	org_width = $('img#bg_img').width();
	org_height = $('img#bg_img').height();
	doresizebg();
	$('#bg_wrapper').animate({opacity: 1},800);
	
}
	
$(document).ready(function() {

	//console.log( images.attr('src') );
	img = $('img#bg_img');
	
	$(img).load(function() {
		// Remove attributes in case img-element has set width and height
		//$(this).removeAttr("width")
		//       .removeAttr("height")
		//       .css({ width: "", height: "" }); // Remove css dimensions as well
		org_width = $('img#bg_img').width();
		org_height = $('img#bg_img').height();
	
		org_width = this.width;
		org_height = this.height;
		
		
		// skallering her
		doresizebg();
		
		// $(this).fadeIn();
		//clearTimeout(t);
		$('#bg_wrapper').animate({opacity: 1},800);
		
	});
	
	var src = img.attr('src');
	img.attr('src',"");
	img.attr('src', src);
	
	var t=setTimeout(fallback_bgfade, 4000);
	
	//img.src = src;	
	/*
	var src = img.attr('src');
	console.log(src);
	img.src = "";
	console.log(img.src);
	img.attr('src', src); // Triggers onload if image is cached (see comments)	
	console.log(img.src);
	*/
	/*
	var pic_real_width;
	var pic_real_height;
	
	$(img).load(function() {
	    // Remove attributes in case img-element has set width and height
	    $(this).removeAttr("width")
	           .removeAttr("height")
	           .css({ width: "", height: "" }); // Remove css dimensions as well
	
	    pic_real_width = this.width;
	    pic_real_height = this.height;
	});
	
	var src = img.src;
	img.src = "";
	img.src = src; // Triggers onload if image is cached (see comments)
	*/

});

var enableFade = '';

$(document).ready(function() {
	enableFade = checkBrowser ();
	
	doresizebg ();
	initializeBoatMenu ();
	initializeMainMenuNav ();
	initializeNewsItems ();
	initializeAvailableBoats ();
	initializeNewsScroll ();
	initializeNewsGalleryScroll ();
	if(enableFade){
		initializeTotalFadein ();
	} else {
		classFade();
	}
	
	/* CHECK FOR SCROLL */
	checkCompanyScroll ();
	checkBoatScroll ();
});

/**  BROWSER COMPATILBILITY  ***/
function getInternetExplorerVersion() {
	var rv = -1; // Return value assumes failure.
	if (navigator.appName == 'Microsoft Internet Explorer') {
		var ua = navigator.userAgent;
		var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
			rv = parseFloat(RegExp.$1);
	}
	return rv;
}

function checkBrowser() {
	var rv = true;
	var ver = getInternetExplorerVersion();
	if (ver > -1) {
		if (ver >= 9.0)
			rv = true;
		else
			rv = false;
	}
	return rv;
}

/***  BACKGROUND REZISING  ***/

function doresizebg() {

	viewportwidth = $(window).width();
	viewportheight = $(window).height();
	
	var contentwidth = $("body").width();
	var contentheight = $("body").height();
	
	if(viewportheight <= contentheight) {
		$("#bg_wrapper").height(contentheight);
	} else {
		$("#bg_wrapper").height(viewportheight);
	}
	
	if(viewportwidth <= contentwidth) {
		$("#bg_wrapper").width(contentwidth);
	} else {
		$("#bg_wrapper").width(viewportwidth);
	}
	
	if(get_aspect( $("#bg_wrapper").width(), $("#bg_wrapper").height() ) >= get_aspect(org_width, org_height) ){
	
		// height is biggest
		$("#bg_img").width( $("#bg_wrapper").width() );
		$("#bg_img").height( $("#bg_wrapper").width() * get_aspect(org_height, org_width) );
		
		var cur_height = $("#bg_img").height();
		$("#bg_img").offset( function(index, coords) {
			return{ left: 0, top: -( ( cur_height - $("#bg_wrapper").height() )/2) };
		});
		
	} else {
	
		// width is biggest
		$("#bg_img").width( $("#bg_wrapper").height() * get_aspect(org_width, org_height) );
		$("#bg_img").height( $("#bg_wrapper").height()  );
		
		var cur_width = $("#bg_img").width();
		$("#bg_img").offset( function(index, coords) {
			return{ left: -( (cur_width- $("#bg_wrapper").width() )/2 ), top: 0 };
		});
	
	}
}

$(window).resize(function() {
	doresizebg();
});


function get_aspect(width, height) {
	return width/height;
}
/***  END  ***/


/***  MAIN NAVIGATION  ***/
/***  ROLLOVER EFFECT  ***/
function initializeMainMenuNav() {
	var numItems = $('#mainnav li').size();
	var i = 0;
	for (i=0; i<numItems; i++){
		addRolloverEffect($('#_mainnav li:eq('+i+')'),$('#mainnav li:eq('+i+') a'));
	}
}

function addRolloverEffect (item,label) {
	if ($(item).hasClass('active') == false){
		$(item).mouseover(function() {
			$(item).stop().animate({
				backgroundPosition: "0px 0px"
				},'slow');
			$(label).css("color" , "#bcbdbe");
		});

		$(item).mouseout(function() {
			$(item).stop().animate({
				backgroundPosition: "0px -120px"
				},'slow');
			$(label).css("color" , "#bcbdbe");
		});
	}
}


/***  END  ***/


/***  BOAT NAVIGATION  ***/
var _lastItem = "";
var _fadeSpeed = 100; // milliseconds
var _lastClicked = "";

function initializeBoatMenu() {	
	checkForDeepLink();
	addClick ("#overviewMenuItem","#overviewWrapper");
	addClick ("#techDataMenuItem","#techDataWrapper");
	addClick ("#galleryMenuItem","#galleryWrapper");
	addClick ("#graphicsMenuItem","#graphicsWrapper");
	addClick ("#engineMenuItem","#engineWrapper");
	addClick ("#equipPriceMenuItem","#equipPriceWrapper");
	addClick ("#equipmentMenuItem","#equipmentWrapper");
	addClick ("#fuelPerfMenuItem","#fuelPerfWrapper");
	addClick ("#serviceMenuItem","#serviceWrapper");
	addClick ("#reviewsMenuItem","#reviewsWrapper");
	addClick ("#brochureMenuItem","#brochureWrapper");
	addClick ("#contactMenuItem","#contactWrapper");
}

function checkForDeepLink(){
	if (location.href.split("#")[1] != undefined) {
		fadeChange ("#" + location.href.split("#")[1] + "Wrapper");
		$("#" + location.href.split("#")[1] + "MenuItem").parent().addClass('active');
		_lastClicked = "#" + location.href.split("#")[1] + "MenuItem";
		$('#boatmenu').stop().animate({
				opacity: 0.90
		},150);
		checkBoatScroll ();
	}
}

function addClick(click,fade) {
	$(click).click(function() {
		fadeChange(fade,this);
	});
}

function fadeChange (item,clicked){
	if (item != _lastItem) {
		$('.contentbox.contentBoxFrame').removeClass('setScrollBar');
		$(_lastItem).removeClass('activeBoatContent');
		if (_lastItem != ""){
			$(_lastClicked).parent().removeClass('active');
			$(_lastItem).removeClass('activeBoatContent');
			_lastClicked = clicked;
			$(_lastItem).fadeOut(_fadeSpeed, function() {
				crossfadeContent(item);
			});
		} else {
			crossfadeContent(item);
		}
		if(item == "#galleryWrapper"){
			$('.contentbox.contentBoxFrame').removeClass('transparentbox');
		} else{
			$('.contentbox.contentBoxFrame').addClass('transparentbox');
		}
		$(clicked).parent().addClass('active');
		_lastClicked = clicked;
	}

	$('#boatmenu,#bottom_menu,#newsmask,#footer').unbind('mouseover mouseout');
	clearTimeout(timeoutID);
}

var priceJscroll = "";
function crossfadeContent(item){
	$(item).fadeIn(_fadeSpeed, function() {
		// Animation complete
		if (_lastItem != ".contentWrapper") {
			//$(_lastItem).css("display","none");
			$(_lastItem).css("display" , "none");
		}
		_lastItem = item;
	});
	location.href = "#" + item.split("#")[1].split("Wrapper")[0];
	$(".contentbox").fadeIn(_fadeSpeed, function() {
		if(item == '#fuelPerfWrapper'){
			$('#fuelPerfContent').jScrollPane({showArrows:false});
			$(item).addClass('activeBoatContent');
			checkBoatScroll();
		}
		if(item == '#techDataWrapper'){
			$('#techDataContent').jScrollPane({showArrows:false});
			$(item).addClass('activeBoatContent');
			checkBoatScroll();
		}
		if(item == '#overviewWrapper'){
			$('#overviewContent').jScrollPane({showArrows:false});
			$(item).addClass('activeBoatContent');
			checkBoatScroll();
		}	
		if(item == '#equipPriceWrapper'){
			priceJscroll = $('#equipPriceContent').jScrollPane({animateScroll: true, animateInterval:60, animateStep:3, showArrows:false});
			$(item).addClass('activeBoatContent');
			checkBoatScroll();
			var api = priceJscroll.data('jsp');
			$('#priceQuickJump').bind(
			'click',
				function(){
					api.scrollToY(parseInt($('#engPrice').height()));
					return false;
				}
			);
		}
		if(item == '#equipmentWrapper'){
			$('#equipmentContent').jScrollPane({showArrows:false});
			$(item).addClass('activeBoatContent');
			checkBoatScroll();
		}if(item == '#contactWrapper'){
			$('#contactContent').jScrollPane({showArrows:false});
			$(item).addClass('activeBoatContent');
			checkBoatScroll();
		}
	});
}

/***  END  ***/


/***  NEWS ITEMS  ***/

function initializeNewsItems() {
	var numItems = $('div.niv4').size();
	var i = 0;
	for (i=0; i<numItems; i++){
		addRolloverEffect2($('.borderEffect').eq(i),$('.glitchPreventer').eq(i),$('.newsitemheader:eq('+i+')'));
	}
}

function addRolloverEffect2 (item,glitch,headingBG) {
	if ($(item).hasClass('active') == false){
		$(item).mouseover(function() {
			$(item).stop().animate({
				borderWidth: "7px",
				width: "278px",
				height: "138px"
			},120);
			$(glitch).stop().animate({
				opacity: 0.99
			},120);
			$(headingBG).css("background-color" , "#666666");
		});

		$(item).mouseout(function() {
			$(item).stop().animate({
				borderWidth: "0px",
				width: "292px",
				height: "152px"
			},120);
			$(glitch).stop().animate({
				opacity: 0.90
			},120);
			$(headingBG).css("background-color" , "#333333");
		});
	}
}

/***  END  ***/


/***  NEWS SCROLL  ***/

var _numNewsItems = 0;
var _currentNewsItem = 0;
function initializeNewsScroll() {
	_numNewsItems = ($('.niv4').size()-2);
	$('#newsRightArrow').click(function() {
		scrollNextNews();
	});
	$('#newsLeftArrow').click(function() {
		scrollPrevNews();
	});
	$('#newsRightArrow').mouseover(function() {
		overArrow(this);
	});
	$('#newsLeftArrow').mouseover(function() {
		overArrow(this);
	});
	$('#newsLeftArrow').mouseout(function() {
		outArrow(this);
	});
	$('#newsRightArrow').mouseout(function() {
		outArrow(this);
	});
}

function scrollNextNews () {
	if(_currentNewsItem<_numNewsItems-1){
		_currentNewsItem++;
		$('.niv3').stop().animate({
			"margin-left" : "-"+_currentNewsItem*320+"px"
		},500);
	}
}

function scrollPrevNews () {
	if(_currentNewsItem>0){
		_currentNewsItem--;
		$('.niv3').stop().animate({
			"margin-left" : "-"+_currentNewsItem*320+"px"
		},500);
	}
}

/***  END  ***/

/***  NEWS GALLERY SCROLL  ***/
var _numNewsGalleryItems = 0;
var _currentNewsGalleryItem = 0;
function initializeNewsGalleryScroll() {
	_numNewsGalleryItems = ($('.newsGall4').size());
	$('#newsGalleryRightArrow').live("click", function() {
		scrollNextNewsGallery();
	});
	$('#newsGalleryLeftArrow').live("click", function() {
		scrollPrevNewsGallery();
	});
	$('#newsGalleryRightArrow').mouseover(function() {
		overArrow(this);
	});
	$('#newsGalleryLeftArrow').mouseover(function() {
		overArrow(this);
	});
	$('#newsGalleryLeftArrow').mouseout(function() {
		outArrow(this);
	});
	$('#newsGalleryRightArrow').mouseout(function() {
		outArrow(this);
	});
}

function scrollNextNewsGallery () {
	if(_currentNewsGalleryItem<_numNewsGalleryItems-1){
		_currentNewsGalleryItem++;
		$('.newsGall3').stop().animate({
			"margin-left" : "-"+_currentNewsGalleryItem*442+"px"
		},500);
	}
}

function scrollPrevNewsGallery () {
	if(_currentNewsGalleryItem>0){
		_currentNewsGalleryItem--;
		$('.newsGall3').stop().animate({
			"margin-left" : "-"+_currentNewsGalleryItem*442+"px"
		},500);
	}
}

/***  END  ***/


/***  AVAILABLE BOATS  ***/
var _avalBoatPageNum = 0;
var _currentPage = 0;
function initializeAvailableBoats() {
	var i = 0;
	_avalBoatPageNum = $('.availableBoatPage').size();
	$('#quickPage').css('width',10*_avalBoatPageNum);
	for (i=0; i<_avalBoatPageNum; i++){
		$('.quickPageNumber').eq(i).click(function() {
			scrollToPage (($(this).html()-1));
		});
	}
	$('.quickPageNumber').eq(0).css('color','#EEE');
	
	$('#rightArrow').click(function() {
		scrollPageNext();
	});
	$('#leftArrow').click(function() {
		scrollPagePrev();
	});
	$('#rightArrow').mouseover(function() {
		overArrow(this);
	});
	$('#leftArrow').mouseover(function() {
		overArrow(this);
	});
	$('#leftArrow').mouseout(function() {
		outArrow(this);
	});
	$('#rightArrow').mouseout(function() {
		outArrow(this);
	});

}

function overArrow(btn) {
	if(enableFade){
		$(btn).stop().animate({
			opacity: 0.99
		},50);
	}
}

function outArrow(btn) {
	if(enableFade){
		$(btn).stop().animate({
			opacity: 0.90
		},50);
	}
}


function scrollPageNext () {
	if(_currentPage<_avalBoatPageNum-1){
		_currentPage++;
		scrollToPage (_currentPage);
	}
}

function scrollPagePrev () {
	if(_currentPage>0){
		_currentPage--;
		scrollToPage (_currentPage);
	}
}

function scrollToPage (toPage) {
	$('#availibleBoatScroll').stop().animate({
		"margin-left" : "-"+toPage*620+"px"
	},500);
	for (var i = 0; i< _avalBoatPageNum; i++){
		$('.quickPageNumber').eq(i).css('color','#676767')
	}
	$('.quickPageNumber').eq(toPage).css('color','#EEE')
	_currentPage = toPage;
}

//

$('#submitrequest').live('click',function() {
	var postdata = $('#requestformdata').serialize();
$.ajax({ 
	url: '/api/get?type=requestinfo',
	type: 'post',
	data: postdata,
	beforeSend: function(){
	},
	success: function(data){
		$('#requestForm').html(data);
  	}
});

});
/***  END  ***/


var delaytime = 3500;
var autofadetime = 250;
var fadetime = 650;

function initializeAutoFade (hooverItem) {
	var $fadeItems = $('#boatmenu.menufade,#bottom_menu,#newsScroll,#footer');

	/* BOAT MENU */
	if(_lastClicked == ""){
		autoFade($fadeItems);
	}
	
	$(hooverItem).mouseover(function() {
		if(_lastClicked == ""){
			addOver($fadeItems);
		}
	});
	
	$(hooverItem).mouseout(function() {
		if(_lastClicked == ""){
			addOut($fadeItems);
		}
	});
}

function autoFade ($items){
	/*$items.delay(delaytime).stop().animate({
		opacity: 0.0
	},autofadetime);*/
	
	clearTimeout(timeoutID);
	
	if (location.href.split("#")[1] == undefined) {
		timeoutID = setTimeout( function(){
			$items.stop().animate({
				opacity: 0.0
			},fadetime);
		}, delaytime);
	}
	
}

function addOver ($items){
	var url = "" + window.location;
	if (url.search(/#/i)< 0) {
		$items.stop().animate({
			opacity: 0.90
		},fadetime);
	}
}

function addOut ($items){
	var url = "" + window.location;
	if (url.search(/#/i)< 0) {
		$items.stop().animate({
			opacity: 0.0
		},fadetime);
	}
}


/* CHECKING IF COMPANY SCROLL EXISTS */
function checkCompanyScroll(){
	if ($('#companyContentHolder').height() < 410) {
		//$('.contentBoxFrame').css('border-right','4px solid #e4e3e4');
		$('.contentBoxFrame').css('border-right','4px solid #838484');
		$('#companyContent').css('width','592px');
		$('#companyContentHolder').css('width','592px');
		$('.contentbox').css('width','612px');
	}
}

/* CHECKING IF BOAT SCROLL EXISTS */
function checkBoatScroll(){
	if ($('.activeBoatContent .boatContentHolder').height() > 390) {
		$('.contentbox.contentBoxFrame').addClass('setScrollBar');
	}
}


var fade1 = 700;
var fade2 = 800;
var delay1 = 100;
var delay2 = delay1+fade1;
var delay3 = delay2+fade1;
var delay4 = delay3+fade1;
var delay5 = delay4+fade1;

/* FADING IN THE ENTIRE SITE AFTER X MILLISECONDS */
function initializeTotalFadein (){
		$('#top_menu_fadeholder').delay(delay1).animate ({opacity: 1},fade1);
		$('#maincontent').delay(delay2).animate ({opacity: 1},fade1);
		$('#bottom_menu').delay(delay3).animate ({opacity: 1},fade1);
		$('#newsScroll').delay(delay4).animate ({opacity: 1},fade1);
		$('#footer').delay(delay5).animate ({opacity: 1},fade1, function() {
			initializeAutoFade ('#boatmenu.menufade');
			initializeAutoFade ('#bottom_menu');
			initializeAutoFade ('#newsScroll');
			initializeAutoFade ('#footer');
		});
}
function classFade(){
	//$('#newsScroll').css('z-index', '9999');
}
