// set no conflict
var $j = jQuery.noConflict();

var $shoppingCartId = 'my-trip-content';
var $ajaxUrl = 'http://varmlandofscandinavia.com/vos.php';

// relative locations to background images, from the template directory
var $bgLocation = 'images/bg/fishing';

// default bg width / height
var $fullBgWidth = 1280;
var $fullBgHeight = 960;

// save point for loaded trip data
var $tripData = null;


/**
 * Submit form
 */
function checkout()
{
	//alert($j("#commentForm").serialize());
	//return false;
	$j('.the-form .content-inner-super-wide:first').hide();
	$j('.the-form').append('<div class="content-inner-super-wide">Sending request... Please wait...</div>');
	//content-inner-super-wide

	$j.ajax({
		type : "POST",
		url : $ajaxUrl,
		data : $j("#commentForm").serialize(),
		success : function(msg) {
			if(msg) {
				if ( msg == "ok" ) {
					$j('.the-form').empty();
					$j('.the-form').append('<div class="content-inner-super-wide">Thank you</div>');
				}
				else {
				}
			}

		}
	});
}


/**
 * Add post to trip
 *
 * @var int post_id
 */
function addToTrip(post_id)
{
	$j.ajax({
		type : "POST",
		url : $ajaxUrl,
		data : "func=add_to_trip&post_id="+post_id,
		success : function(msg) {
			if(msg=="true") {
				/* if($j('#post_'+post_id)[0]) {
					$copy = $j('#post_'+post_id).clone(false);
					$copy.insertBefore($j('#post_'+post_id)[0]);

					$copy.css("position","absolute").css("z-index","100").css("background","#fff").css("border","none").css("padding","11px").css("top",($j('#post_'+post_id).offset().top)+'px');
					
					$copy.animate({
						width: '0px',
						height: '0px',
						opacity: '0.0',
						left: ($j('.slide-out-div:first').offset().left)+'px',
						top: ($j(window).scrollTop()-370)+'px'
					},750);
					
					$copy.queue(function(){
						$j('.slide-out-div-highlight:first').css("display","block").css("opacity","1.0");
						$j('.slide-out-div-highlight:first').fadeOut(1750);
						$copy.remove();
					});
				}
				else { */
					$j('.slide-out-div-highlight:first').css("display","block").css("opacity","1.0");
					$j('.slide-out-div-highlight:first').fadeOut(1750);
				// }
				
				// update item's left counter
				/*
				$j('.slide-inner #more-link .number-of-more')[0].innerHTML = parseInt($j('.slide-inner #more-link .number-of-more')[0].innerHTML)+1;
				
				if(parseInt($j('.slide-inner #more-link .number-of-more')[0].innerHTML)>0) {
					$j('.slide-inner #more-link .number-of-more').removeClass('inactive').addClass('active');
				}
				*/
				// reset trip data
				resetTripData();
				updateCount();
				
				$j('#post_'+post_id+' .add-trip').removeClass('active').addClass('inactive');
				$j('#post_'+post_id+' .remove-trip').removeClass('inactive').addClass('active');
			}
			else {
				displayError("An error occurred and the selected item could not be added to your trip.");
			}
		}
	});
}

function displayError(msg)
{
	$j('#error-msg #error-msg-content .subtext').empty().append(msg);
	$j('#error-msg').css("display","none");
	$j('#error-msg').fadeIn(3000);
	
	$j(document).click(function(){
		hideError();
	});
}

function hideError() {
	$j('#error-msg').fadeOut(1000);
}


/**
 * Remove a post from the option data
 *
 * @var int post_id
 */
function removeFromTrip(post_id)
{
	$j.ajax({
		type : "POST",
		url : $ajaxUrl,
		data : "func=remove_from_trip&post_id="+post_id,
		success : function($msg) {
			if($msg == 'true') {
				$j('#cart-item-'+post_id).fadeOut();
				$j('#cart-item-'+post_id).queue(function(){
					$j('#cart-item-'+post_id).remove();
				});
				
				if($post = $j('#checkout_post_'+post_id)) {
					$post.fadeOut();
					$post.queue(function(){
						$post.remove();
						
						if (jQuery.trim($j('.mos').html()) == "") {
							//alert("tomt");
							$j('.qur').fadeOut('slow');
						}
					});
				}
				
				$j('#post_'+post_id+' .add-trip').removeClass('inactive').addClass('active');
				$j('#post_'+post_id+' .remove-trip').removeClass('active').addClass('inactive');
				
				// update item's left counter
				/*
				$j('.slide-inner #more-link .number-of-more')[0].innerHTML = parseInt($j('.slide-inner #more-link .number-of-more')[0].innerHTML)-1;
				
				if(parseInt($j('.slide-inner #more-link .number-of-more')[0].innerHTML)<1) {
					$j('.slide-inner #more-link .number-of-more').removeClass('active').addClass('inactive');
				}
				*/
				
				// reset trip data
				resetTripData();
				updatePrice();
				updateCount();

			}
			else {
				displayError("An error occurred and the selected item could not be removed from your trip.");
			}
		}
	});
}


function updatePrice()
{
	$j.ajax({
		type : "POST",
		url : $ajaxUrl,
		data : "func=update_price",
		success : function($msg) {
			$j('.myPrice-inner').empty();
			$j('.myPrice-inner').append('£');
			if ( $msg == 0 ) {
				$j('.myPrice-inner').empty();
				$j('.myPrice-inner').append('£0');
				$j('.no-packages').empty();
				$j('.no-packages').append('<p>Experience <a href="/fishing/">fishing</a>, <a href="/wilderness/">wilderness</a> and <a href="/culture/">culture</a>. Share it with friends and family.</p><p>Use the "Add to my trip" buttons to customize your adventure.</p>');
				$j('#'+$shoppingCartId).empty();
				$j('#'+$shoppingCartId).append('<span id="my-trip-content-default">No items yet.</span>');
			}
			$j('.myPrice-inner').append($msg);
		}
	});
}

function updateCount()
{
	$j.ajax({
		type : "POST",
		url : $ajaxUrl,
		data : "func=count_items",
		success : function($msg) {
			$j('.number-of-more').empty();
			if ( parseInt($msg)-5 > 0 ) {
				var plask = parseInt($msg)-5;
				//alert(plask);
				$j('.number-of-more').append('<p>Click Book my trip to show ' + Number(plask) + ' more item(s).</p>');
			}
		}
	});
}

function displayTripData()
{
	var result = '<table id="sidebar-cart">';
	$j.ajax({
		type : "POST",
		url : $ajaxUrl,
		data : "func=get_trip_data",
		success : function(msg) {
			eval("var data = "+msg);

			if(data != '') {
				for(var key in data) {
					result+= '<tr class="cart-item" id="cart-item-'+key.replace('post_','')+'">' +
					'<td class="post-img"><img src="'+data[key].post_thumbnail_url+'" /></td>' +
					'<td class="post-title"><span>'+data[key].post_title+'</span></td>' +
					'<td class="post-delete"><a href="javascript:removeFromTrip(\''+key.replace('post_','')+'\');"><div class="link-box"><!-- DELETE LINK BOX --></div></a></td>' +
					'</tr>';
				}
				$j('#'+$shoppingCartId).empty();
				$j('#'+$shoppingCartId).append(result+'</table>');
			}
			else {
				$j('#'+$shoppingCartId).empty();
				$j('#'+$shoppingCartId).append('<span id="my-trip-content-default">No items yet.</span>');
			}
		}
	});
}

function resetTripData()
{
	$j('#'+$shoppingCartId).empty();
	displayTripData();
}

function stretchBgImg()
{
	$obj = $j('#full-bg');
	
	$obj.css("top","0px").css("left","0px");
	
	$clientHeight = $j(window).height();
	$clientWidth = $j(window).width();
	
	if($clientHeight > $clientWidth) {
		$heightRatio = $clientHeight > $fullBgHeight ? $clientHeight/$fullBgHeight : $fullBgHeight/$clientHeight;
		
		$newWidth = $fullBgWidth*$heightRatio;
		$leftPosMinus = ($newWidth-$fullBgWidth)/2;
		
		$obj.css("width",($newWidth)+'px').css("height",($clientHeight)+'px').css("left","-"+$leftPosMinus+"px");
	}
	else if($clientWidth > $clientHeight) {
		$widthRatio = $clientWidth > $fullBgWidth ? $clientWidth/$fullBgWidth : $fullBgWidth/$clientWidth;
		
		$newHeight = $fullBgHeight*$widthRatio;
		$topPosMinus = ($newHeight-$fullBgHeight)/2;
		
		if($clientWidth < $fullBgWidth) {
			$leftPostMinus = ($fullBgWidth-$clientWidth)/2;
			$obj.css("left",'-'+$leftPostMinus+'px');
			$clientWidth = $fullBgWidth;
			$newHeight = $fullBgHeight;
			$topPosMinus = ($fullBgHeight-$clientHeight)/2;
		}
		
		$obj.css("width",$clientWidth+'px').css("height",($newHeight)+'px').css("top","-"+$topPosMinus+"px");
	}
}

function changePost(offset)
{
	// $j('#story-post-ajax-loading').show();
	$newPost = $j('.story .content-inner-wide').clone(false).insertAfter($j('.story .content-inner-wide')[0]).hide();
	$j('.story .content-inner-wide')[0].className += " old";
	
	// make sure that a user can't double click the prev / next buttons multiple times
	$j('.story .navigation .nav-brick:first').css('display','block');
	
	$j.ajax({
		type : "POST",
		url : $ajaxUrl,
		data : "func=get_story_post_by_offset&post_offset="+offset,
		complete : function() {
			// $j('#story-post-ajax-loading').hide();
		},
		success : function(msg) {
			if(msg!="false") {
				eval("$data = "+msg+";");

				$prevLink = $j('.story .navigation .prev-link');
				$nextLink = $j('.story .navigation .next-link');
				
				if($newPost[0]) {
					$newPost.empty();
					$newPostData = '<div id="post_'+$data.postId+'">' + $data.data;
					
					if($data.isInCart=='1') {
						$newPostData += '<a href="javascript:addToTrip('+$data.postId+');" class="add-trip inactive">Add to my trip</a><a href="javascript:removeFromTrip('+$data.postId+');" class="remove-trip active">Remove from my trip</a>';
					}
					else {
						$newPostData += '<a href="javascript:addToTrip('+$data.postId+');" class="add-trip active">Add to my trip</a><a href="javascript:removeFromTrip('+$data.postId+');" class="remove-trip inactive">Remove from my trip</a>';
					}
					
					$newPostData+= '</div>';
					$newPost.append($newPostData);
				}
				
				if(offset > 0) { 
					$prevLink[0].href = 'javascript:changePost('+(offset-1)+');'; 
					$prevLink.css('visibility','visible');
				}
				else {
					$prevLink.css('visibility','hidden');
				}
				
				if(offset < $numberOfStoryPosts) {
					$nextLink[0].href = 'javascript:changePost('+(offset+1)+');';
					$nextLink.css('visibility','visible');
				}
				else {
					$nextLink.css('visibility','hidden');
				}
				
				$newPostWidth = $newPost.width();
				
				//$j('.story .content-inner-wide.old').hide("slide", {direction : "left"}, 1000);
				$j('.story .content-inner-wide.old').fadeOut();

				// $newPost.show("slide", {direction : "right"}, 1000);
				
				$j('.story .content-inner-wide.old').queue(function(){
					$j('.story .content-inner-wide.old').remove();
					$newPost.css('display','block').css('opacity','0.0');
					$newPost.animate({ 
				        opacity: 1.0
				      }, 900);

					$j('.story .story-post-number #current-story-post-text').text((offset+1)+"/");
					
					// hide the navigation brick, allowing users to once again click on the next / prev buttons
					$j('.story .navigation .nav-brick:first').css('display','none');
				});
			}
			else {
				displayError("An error occurred, please try again.");
			}
		}
	});
	
}

$j(document).ready(function(){
	// display the current trip data
	displayTripData();

	// setup animations for the slide-out-div-fix element
	/*$j("#slide-out-div-fix").click(function(){
		if($j('.slide-out-div').hasClass('open')) {
			$j("#slide-out-div-fix").animate({right:'0px'}, 300);
		}
		else {
			$j("#slide-out-div-fix").animate({right:'288px'}, 300);
		}
		$j('.slide-out-div .handle').click();
	});*/
	
	$w = $j(window).width();
	
	if($w < 1180) {
		$fullBgWidth = 1024;
		$fullBgHeight = 768;
	}
	else if($w < 1500) {
		$fullBgWidth = 1280;
		$fullBgHeight = 960;
	}
	else if($w < 1820) {
		$fullBgWidth = 1600;
		$fullBgHeight = 1200;
	}
	else {
		$fullBgWidth = 1920;
		$fullBgHeight = 1440;
	}
	
	$j('#full-bg')[0].src += $bgLocation + '/' + $fullBgWidth + 'x' + $fullBgHeight + '.jpg';

	// stretch image background
	stretchBgImg();
});

$j(window).resize(function(){
	// stretch image background
	stretchBgImg();
});;

