/**
 * @author	Jonathan Cochran <jono.cochran@gmail.com>
 *			FabricCreative.com, COPYRIGHT 2009
 * --------------------------------------------------------- */

$(document).ready(function() {
/**
 * BROWSER RELATED
 * --------------------------------------------------------- */
	var docLoc = window.location.href;
	var badBrowser = (/MSIE ((5\.5)|6|7|8)/.test(navigator.userAgent) && navigator.platform == "Win32");
	
/**
 * PRELOAD
 * --------------------------------------------------------- */
	if ( !badBrowser )
	{
		$.preload.gap = 5;
		$.preload( '#preload img', {	//the first argument is a selector to the images
			onRequest: request,
			onComplete: complete,
			onFinish: finish,
			placeholder: '../images/blank.gif',	//this is the really important option
			notFound: '../images/blank.gif',	//optional image if an image wasn't found
			threshold: 3 						//'2' is the default, how many at a time, to load.
		});
		
		$("#progress-bar a").click(function() {
			$('#progress-bar').stop().animate({ 'marginLeft' : $(document).width() }, 500, 'easeIn', function() {
				//fade out loader & remove...
				$('#loading-container').fadeTo(300, 0, function() {
					$(this).remove();
			
					//fade in background
					$('#background-image').fadeTo(1000, 1, function() { loadSite() });
				});
			});
		});
	}
	//Bad Browser...
	else
	{
		//Load IE styles
		$('input').css( {
			//'padding' 	: '10px 15px !important',
			'height'	: '30px',
			//'line-height' : '30px',
			'font-size'	: '14px'
		});
		$('#commission, #balance').css('width', '80px');
		$('td').css('color', 'black');
		$('td.th').css('color', '#B8BAB6');
		
		$('#loading-container').remove();
		$('#navigation a').css('padding-left', 0);	
		
		initNavigation();
		loadHomepage();
	}
	
	//Preload functions...
	function update( data ) {			
		data.done;
		data.total;
		data.loaded;
		data.failed;
	
		var progW = (data.loaded / data.total) * $(document).width(); //progress bar is 200px wide
		var perc = parseInt(data.loaded / data.total * 100);
		$('#progress-bar a').html(perc);
		$('#progress-bar').stop().animate({ 'width' : progW }, 100, 'easeOut');
	};
	function complete( data ){
		update( data );			
	};
	function request( data ){
		update( data );
	};
	function finish() { //hide the summary
		//alert('made it');
		//return false;
		$('#progress-bar a').trigger('click');
	};	
	
	
	/* TEMP CODE 
	$('#loading-container').remove();
	$('#background-image').css('opacity', 1);
	//loadSite();
	
	$('#logo').fadeTo(1, 1);
	$('#navigation').fadeTo(1, 1, function() {
			loadNavigation();
			loadContent('listings');
	});
	$('#lighthouse').fadeTo(1, 1);			
	reloadScrollbar();*/
	
/**
 * RESIZE DOCUMENT
 * --------------------------------------------------------- */	
	$(window).resize(function() {
		resizeBackground();
	});
	
		
/**
 * RESIZABLE BACKGROUND IMAGE
 * --------------------------------------------------------- */
	var objDocBg = $('#background-image img'); //Background image obj
	objDocBg.hide(); //don't need show this unless the browser is size > 1920x1200;
	function resizeBackground()
	{
		//Gather browser size
		var browserwidth = $(window).width();
		var browserheight = $(window).height();
		
		//Show the background image
		objDocBg.show();
		
		//Define image ratio
		var ratio = 1092 / 3500;

		if ( (browserheight / ratio) < browserwidth)
		{
			return false;
		}
		//Resize image to proper ratio
		objDocBg.height(browserheight);
		objDocBg.width(browserheight / ratio);
		
		//RESIZE / POSITION ELEMENTS
		if (browserheight < 670)
		{
			var lighthouseHeight = ( (browserheight) / 13);
			$('#lighthouse img').css('height', lighthouseHeight +'px');
		}
		else {
			$('#lighthouse img').css('height', '50px');
		}
		
		if ( $('#content > div').is(':visible') )
		{
			reloadScrollbar();
		}
		else
		{
			$('.content-scroll').jScrollPaneRemove();
		}
		
		iItemW = parseInt($("#current-listings").width() - 10);
		$('.item-image').width(iItemW);
	}
	
	function reloadScrollbar()
	{
		if (!badBrowser)
		{
			$('.content-scroll').jScrollPaneRemove();
			$('.content-scroll').css({ 'height' : parseInt($('#content').height() - 60) }).jScrollPane();
		}
		else
		{
			//alert( $('.content-scroll:visible').parent().attr('id') )
			$('.content-scroll:visible').jScrollPaneRemove();
			$('.content-scroll:visible').css({ 'height' : parseInt($('#content').height() - 60) }).jScrollPane();
		}
	}
	resizeBackground();
	
/**
 * LOAD SITE
 * --------------------------------------------------------- */
	function loadSite() 
	{
		$('#logo').fadeTo(1000, 1, function() {
			
			$('#navigation').fadeTo(100, 1, function() {
				loadNavigation();
			});
			
			$('#lighthouse').fadeTo(500, 1, function() {
				$('#fabric').fadeTo(500, 1, function() {
					//logo is clicked
					$('a', $('#logo')).click(function() {
						objNav.removeClass('nav-current');
						loadContent('homepage');
						
					});
				});

			});
		});
		
		reloadScrollbar();
	}
	
	var objNav = $('#navigation a');
	var iNav = 0;
	function loadNavigation()
	{	
		if (iNav < objNav.length)
		{
			$(objNav[iNav]).animate({ paddingLeft : 0, opacity: 1}, 120, function() {
				loadNavigation(iNav);
				iNav++;
			});
		}
		else
		{
			loadHomepage();
			initNavigation();
		}
	}
	
	function initNavigation()
	{
		if (objNav == null)
		{
			objNav = $('#navigation a');
		}
		
		objNav.click(function() {
			objNav.removeClass('nav-current');
			var pageName = $(this).attr('class').replace('nav-', '');
			if (pageName == "client-login") return true;
			$(this).addClass('nav-current');
			loadContent(pageName);
		});
	}

/**
 * CONTENT
 * --------------------------------------------------------- */
	function loadHomepage()
	{
		objHomepage = $('#content-homepage');
		objHomepage.show();
		
		showContent(objHomepage);
		
	}

	function loadContent(pageName)
	{
		var objContainers = $('.content-container');
		var objParent = $('#content-'+ pageName);
		
		//Hide all containers expect current...
		objContainers.each(function() {
			if ( $(this).is(':visible') )
			{
				//hides current, loads new content
				hideContent( $(this), objParent );
			}
		});

		if (pageName == "calculator")
		{
			initCalculator();
		}
		
		if (pageName == "listings")
		{
			initListings();
		}
		
		if (pageName == "testimonials")
		{
			initTestimonials();
		}
		
		//Change the bg image
		if (pageName == "contact")
		{
			initContact();
			showBg();
		}
		else
		{
			hideBg();
		}
	}
	
	/**
	 * Hides content, then loads load immediately after.
	 * @param	content to be hidden
	 * @param	content to load after 
	 */
	function hideContent($objContent, $objContentToLoad)
	{	
		if (badBrowser)
		{
			$objContent.hide();
			showContent($objContentToLoad)
			return false;
		}
		
		$('.content-scroll', $objContent).stop().fadeTo(500, 0, function() {
			$('.title', $objContent).stop().fadeTo(500, 0, function() { 
				$objContent.hide(); //hide first content parent
				$objContentToLoad.show(); //show parent container
				showContent($objContentToLoad); //fade in new content
			});			
		});
	}
	
	function showContent($objContent)
	{
		if (badBrowser)
		{
			$objContent.show();
			reloadScrollbar();
			return false;
		}
		
		$('.title', $objContent).stop().fadeTo(500, 1, function() {
			//console.log($('.jScrollPaneContainer', $objContent)); 
			//, 'height' : parseInt($('#content').height() - 60)
			$('.content-scroll', $objContent).stop().fadeTo(300, 1, function() { 
				reloadScrollbar();
			});			
		});
	}
	
	function showBg()
	{
		$('#bg').fadeTo(4000, 0);
	}
	
	function hideBg()
	{
		$('#bg').fadeTo(4000, 1);
	}
	
	function initCalculator()
	{
		var objCost = $('#cost');	//input
		var objCom = $('#commission');	//input
		var objComTotal = $('#commission-total'); //input
		var objBalance = $('#balance'); //input
		var objRebate = $('#rebate'); //input
		var objTotalCost = $("#total-cost"); //span
		var objTotalSaved = $('#total-saved'); //span
		
		objCost.change(function() {
			
			var iCost = parseFloat( objCost.val().replace(',', '') );
			//objCost.formatCurrency({ symbol : ''}); //buggy
			
			var iComTotal = "";
			var iRebate = ""
			if (iCost > 100000)
			{
				iComTotal = 7000 + ( (iCost-100000) * .025 );
				iRebate = 3775 + ( (iCost-100000) * .0135 );
			}
			else
			{
				iComTotal = iCost * .07;
				iRebate = iCost * .0135;
			}
			if (isNaN(iComTotal)) iComTotal = "0";
			if (isNaN(iRebate)) iRebate = "0";
			objComTotal.val(iComTotal).formatCurrency({ symbol : ' '});
			objRebate.val(iRebate).formatCurrency({ symbol : ' '});
			objTotalCost.val(iComTotal-iRebate).formatCurrency();
			//objTotalCost.html(iComTotal-iRebate).formatCurrency();
			objTotalSaved.html(iRebate).formatCurrency();
		});
		
		$('#show-disclaimer a').click(function() {
			$('#show-disclaimer').hide()
			$('#disclaimer').show();
			reloadScrollbar();
		});
		
		$('#hide-disclaimer a').click(function() {
			$('#disclaimer').hide()
			$('#show-disclaimer').show();
			reloadScrollbar();
		});
	}
	
	function initListings()
	{
		$('div.item-description:last', $('#current-listings, #sold-listings')).css({ 'border' : 'none', 'padding-bottom' : 0, 'margin' : 0 });
		$('a.sold-listings').click(function() {
			$(this).addClass('sold-listings-sel');
			$('a.current-listings').removeClass('current-listings-sel');
			$('#current-listings').hide();
			$('#sold-listings').show();
			reloadScrollbar();
		});
		$('a.current-listings').click(function() {
			$(this).addClass('current-listings-sel');
			$('a.sold-listings').removeClass('sold-listings-sel');
			$('#sold-listings').hide();
			$('#current-listings').show();
			reloadScrollbar();
		});	
		
		// Load fullscreen listings
		$('.read-more').click(function() {
			//loadFullScreen('');
			var iListingId = $(this).attr('id').replace('listing-', '');
			$.get(
				'listing-item.php',
				{ id : iListingId },
				function(data)
				{
					loadFullScreen(data);
				}
			);
		});		
	}
	
	function initTestimonials()
	{
		$('div.testimonial:first').css({ 'margin-top' : 10 });
		$('div.testimonial:last').css({ 'border' : 'none', 'padding-bottom' : 0, 'margin' : 0 });		
	}
	
	function initContact()
	{
		
	}
	
	
/**
 * FULL SCREEN, IMAGES
 * --------------------------------------------------------- */
	var objImagesParent = ""; //Parent div holding images (prev / next)
	function loadFullScreen(html)
	{
		//Check if loaded already...
		if ($('#fullscreen-bg').is(':visible'))
		{
			$('#fullscreen-content').html(html);
			initFullScreenEvents();
		}
		//Load'r in...
		else {
			$('#fullscreen-bg').height($(document).height());
			$('#fullscreen-bg').css('display','block').fadeTo(300, .75, function() {
				$('#fullscreen-content').css('display', 'block').html(html).fadeTo(500, 1, function() {
					$('.tour-info', $(this)).css('display', 'block');
					$('#fullscreen-close').css('display', 'block');
					initFullScreenEvents();
					if ( $('h1', $(html)).length > 0 )
						Cufon.replace('h1');
					
					if ( $('.calendar-event-inner').innerHeight() > 240 )
					{
						$('#fullscreen-close').css('left', '162px');
					}	
					
				});
			});
		}
	}
	function initFullScreenEvents()
	{
		initFullScreenNext();

		//Remove fullscreen
		$('#fullscreen-close, #fullscreen-bg').click(function() {
			removeFullScreen();
		});
		//Escape, or backspace key is press
		$(document).keypress(function (e) {
			if (e.which == 0 || e.which == 8)
			{
				removeFullScreen();
			}
		});
	}
	function removeFullScreen()
	{
		//Remove previously added classes...
		$('#fullscreen-content').removeClass('fullscreen-video');
		$('#fullscreen-close').removeClass('fullscreen-video-close');

		//Remove inline styles...
		$('#fullscreen-content').attr('style', '');
		$('#fullscreen-close').attr('style', '');

		$('#fullscreen-bg, #fullscreen-close, #fullscreen-content').css('display', 'none');
		$('#fullscreen-content').html('');
	}
	function loadFullScreenImage(objImg)
	{
		var imgSrc  = $('img', objImg).attr('src').replace('_thumb', '');
		var imgDesc = $(objImg).next('span').html();
		var imgDim  = $(objImg).attr('rel').split('x');
		var imgW    = Number(imgDim[0]);
		var imgH    = Number(imgDim[1]);

		html  = '<img src="'+ imgSrc +'" />'; 
		html += '<div class="fullscreen-video-desc" style="margin-top: 6px">'+ imgDesc +'</div>';
		$('#fullscreen-content')
		.animate({
			'width'  	 : imgW +'px',
			'height' 	 : (imgH+40) +'px',
			'left' 		 : (imgW/2)*-1,
			'marginTop'  : ((imgH+40)/2)*-1
		},200); 
		$('#fullscreen-close')
		.animate( {
			'left' 		 : (imgW/2)-100,
			'marginTop'  : ((imgH-40)/2)+13
		},200);

		loadFullScreen(html);
	}
	function initFullScreenNext()
	{
		//Parent is the holder of thumbnails
		if (objImagesParent)
		{
			$('#fullscreen-content img').click(function() {			
				thisImageSrc = $(this).attr('src'); 		 //Get the current fullscreen image
				objChildImages  = $('img', objImagesParent); //Get children images (thumbnails)

				//Loop thumbnails...
				objChildImages.each(function() {

					//Check if the current image is the loop item
					var strChildSrc = $(this).attr('src').replace('_thumb', '');
					if (strChildSrc == thisImageSrc)
					{
						//Replace current image with the next image
						var objNext = $(this).parent('a').parent('div').next('div');
						var refA	= $('a', objNext);
						if ($(refA).length == 0) {
							refA = $('a:first', objImagesParent);													
						}

						//Load in image
						loadFullScreenImage(refA);
					}
				})
			});
		}
	}
});