/**
 * @author Damon Skelhron
 */

var siteUR = '';
var ajaxUR = '';
var gLat;
var gLong;

$(document).ready(function(){

	// Inital values
	siteUR = 'http://' + document.domain + '/';
	ajaxUR = siteUR + '_ajax.php';
	
	// Contact Page
	getLatitudeLongitude();

	// Global
	makeSaveSubmit();
	hideBar();
	
	// Products
	switchImage();
	setMainImage();
	enquiryForm();
	enquireLink();
	
	solcialLinks();
	
	// Shopping Basket System
	clearBasket();
	addToBasket();
	removeItem();
	updateItemQuantity();

});

/** Shopping basket system **/

function updateItemQuantity(){
	$('a.updateItem').click(function(){
		$(this).text('Updating').append(makeAjaxLoader());
		
		var theText = $(this);
		var theRow = $(this).parent().parent().parent();
		var theID = theRow.attr('id');
		theID = theID.split('product-');
		theID = theID[1];
		
		var quantity = $('input[name="quantity['+theID+']"]').val();
		
		$.getJSON(ajaxUR, {area: 'site', meth: 'updateQuantity', id: theID, quantity: quantity}, function(data){
			if(data.Status == 'OK'){
				theText.text('Update Quantity');
				$('span#productPrice-'+theID).text(data.ProductTotal);
				updateBasketTotals(data, 'Quantity updated', false);
				destroyAjaxLoader();
			}
			else {
				theText.text('Update Quantity');
				destroyAjaxLoader();
				alert('Unable to update quantity at this time');
			}
			
		});
		return false;
	});
}

function removeItem(){
	$('a.removeItem').click(function(){
		
		$(this).text('Removing').append(makeAjaxLoader());
		
		var theRow = $(this).parent().parent().parent();
		var theID = theRow.attr('id');
		theID = theID.split('product-');
		theID = theID[1];
		
		$.getJSON(ajaxUR, {area: 'site', meth: 'removeItem', id: theID}, function(data){
			if (data.Status == 'OK') {
				theRow.remove();
				updateBasketTotals(data, 'Item has been removed from basket', false);
				updateBasketTable();
			}
			else {
				alert('Unable to remove item at this time');
				$(this).text('Remove Item');
				destroyAjaxLoader();
			}
		});
		return false;
	});
}

function updateBasketTable(){
	if($('table#productTable tbody tr').length == 0) $('table#productTable tbody').append('<tr><td colspan="3">Your basket is empty</td></tr>');
}

function clearBasket(){
	$('a#clearBasket').click(function(){
		$.getJSON(ajaxUR, {area: 'site', meth: 'clearBasket'}, function(data){
			updateBasketTotals(data, '', false);
		});
		return false;
	});
}

function showAlert(message){
	var $alert = $('#alert');
	$alert.html(message);
	var alerttimer = window.setTimeout(
		function () {
			$alert.trigger('click');
		},
		3000
	);
	$alert.animate({height: $alert.css('line-height') || '150px'}, 600).click(function () {
		window.clearTimeout(alerttimer);
		$alert.animate({height: '0'}, 600);
	});
}

function addToBasket(){
	$('a#addToBasket').click(function(){
		// ajax post to _ajax add to basket, return price update the items totals top of page.
		$(this).append(makeAjaxLoader());
		$.getJSON(ajaxUR, $('form#addBasket').serialize(), function(data){
			updateBasketTotals(data, 'Item has been added to your basket', true);
		});
		return false;
	});
}

function updateBasketTotals(data, message, showMessage){
	
	var itemTotal = $('span#itemTotal');	
	itemTotal.text(data.Basket.Total);
	
	var itemCount = $('span#itemCount');
	itemCount.text(data.Basket.Items);
	
	destroyAjaxLoader();
	if(showMessage) showAlert(message);
}


/** -- Global -- */

function solcialLinks(){
	
	// Favs.
	
	$('a#addFavorites').click(function(){
		alert ('he');
		if(document.all) window.external.AddFavorite(location.href,document.title);
		else if(window.sidebar) window.sidebar.addPanel(document.title,location.href,'');
		
		return false;
		
	});
	
	// Print 
	$('a#printPage').click(function(){
		window.print();
		return false;
	});
	
	
	
}

function hideBar(){
	$('a#hideBar').click(function(){
		$(this).parent().parent().parent().slideUp('fast');
		return false;
	});
}

function makeSaveSubmit(){
	
	$('a.formSave').click(function(){
		//alert('hei');
		$(this).closest('form').submit();
		return false;
	});	
}


/** -- Contact Page -- */
function getLatitudeLongitude(){
	if ($('#gMap').length > 0) {
		$.getJSON(ajaxUR, {
			area: 'site',
			meth: 'gmaplatlog'
		}, function(json){
			if (json.Status == 'OK') {
				gLat = json.Data.Lat;
				gLong = json.Data.Long;
				makeGMap();
			}
		});
	}
}

function makeGMap(){
	if($('#gMap').length > 0){
		$("#gMap").gMap({
			zoom: 15,
			markers:[
			{
				latitude: gLat,
				longitude: gLong,
	            html: "We are here!",
				popup: false 
			}]
		});
	}
}

function enquireLink(){
	$('a#enquireProduct').click(function(){
		var $productEnquiry = $('#productEnquiry');
		if(!$productEnquiry.is(':visible')){
			$productEnquiry.slideDown('slow');
			$(this).text('Hide enquiry form');
		}
		else {
			$productEnquiry.slideUp('fast');
			$(this).text('Enquire about this product');
		}
		return false;
	});
}

function enquiryForm(){
	if($('#productEnquiry').length > 0){
		var $productEnquiry = $('#productEnquiry');
		if ($productEnquiry.hasClass('errors')) {
			$productEnquiry.slideDown('slow');
			$('a#enquireProduct').text('Hide enquiry form');
		}
	}
}


function setMainImage(){
	
	if ($('li#firstThumb').length > 0) {
		var firstThumb = $('li#firstThumb').children('a').attr('id').split('switchImage-');
		firstThumb = firstThumb[1];
		if (firstThumb == 'noimg') 
			var img = '/images/noimage.png';
		else 
			var img = '/images/products/' + firstThumb + '_main.png';
			var imgLarge = '/images/products/' + firstThumb + '_large.png';
			
		$("img#mainImage").attr('src', img);
		$("a.cloud-zoom").attr("href", imgLarge);
	}
}

function switchImage(){
	
	$('a[id^="switchImage-"]').click(function(){
		var theID = $(this).attr('id').split('switchImage-');
		theID = theID[1];
		$("img#mainImage").attr('src', '/images/products/'+theID+'_main.png');
		var imgLarge = '/images/products/' + theID + '_large.png';
		$("a.cloud-zoom").attr("href", imgLarge).CloudZoom();
		return false;
	});
		
}

function makeAjaxLoader(){
	var ajaxLoader = document.createElement('img');
	ajaxLoader.setAttribute('src', '/images/ajax-loader.gif');
	ajaxLoader.setAttribute('id', 'ajaxLoader');
	return ajaxLoader;
}

function destroyAjaxLoader(){
	$('img#ajaxLoader').remove();
}
