/**
 * @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();
	
	//Gallery 
	switchGalleryImage();
	
	// Products
	switchImage();
	setMainImage();
	enquiryForm();
	enquireLink();
	
	solcialLinks();
	
	// Shopping Basket System
	clearBasket();
	addToBasket();
	removeItem();
	updateItemQuantity();
	
	makePaymentButton();
	toDifferentAddress();
	if($('#distroGmap').length) Distributors.init();
	$('ul.fancyMenu,ul.buttonMenu').buttonset();
	
	homePageImageCycle();
	Twitter.init();
	
	Website.init();
	
});


var Website = {
	
	init: function(){
		this.homeLogoMouse();
		this.makeFancyButtons();
		if($('#featured').length > 0) this.makeTabs();
	}, 
	
	makeTabs: function(){
		$('#featured').tabs({fx:{opacity: "toggle"}}).tabs("rotate", 5000, true);
	},
	
	makeFancyButtons: function(){
		$('.fancyMenu').buttonset();
	},
	
	homeLogoMouse: function(){
		
		$('#homeLogo').mouseenter(function(){
			var offsY = parseInt($('#homeLogo').height());
			 $('#homeLogo').animate({
                height: 85
            }, 'fast', 'linear', function(){
                
            });
		}).mouseleave(function(){
			var offsY = parseInt($('#homeLogo').height());
			$('#homeLogo').animate({
                height: 65
            }, 'fast', 'linear', function(){
				
            });
		});
	}
	
}

var Twitter = {

    displayTweet: 0,
	balloon: 0,
    init: function(){
    
		$('div.balloon ul li').hide();
		$('div.balloon ul li#tweet0').show();
        Twitter.balloon = $("div.balloon");
        Twitter.display_tweet = 0;
        if ($("div.balloon ul li#tweet1").html() !== null) {
        
            setTimeout(function(){
                Twitter.swapTweet(Twitter.display_tweet);
            }, 12000);
            
            var firstTweet = $("li#tweet0");
            setTimeout(function(){
                Twitter.scrollTweet(firstTweet);
            }, 7500);
        }
        
    },
    
    swapTweet: function(tweet){
        var nextTweet = (tweet + 1) % 5;
        var li = $("li#tweet" + nextTweet);
        
        $("#tweet" + tweet).fadeOut(300);
        setTimeout(function(){
			li.children('div.post').css('left', 0);
            li.fadeIn(400);
        }, 400);
        
        setTimeout(function(){
            Twitter.scrollTweet(li);
        }, 3800);
        
        Twitter.display_tweet = nextTweet;
        setTimeout(function(){
            Twitter.swapTweet(Twitter.display_tweet);
        }, 11300);
        
    },
    
    scrollTweet: function(li){
        var post = li.children("div.post"), pWidth = post.width();
        if (pWidth > parseInt(Twitter.balloon.css('width'))) {
            var leftEnd = li.find('div.end');
            if (leftEnd.length === 0) {
                leftEnd = $('<div class="end left" />').appendTo(li);
            }
            var offsX = parseInt(leftEnd.width());
            post.animate({
                left: offsX - pWidth - 100
            }, 23000, 'linear', function(){
                post.css('left', offsX);
            });
        }
        
    }
    
}

var Distributors = {
		
		init: function(){
			this.getMarkers();
			this.distribClick();
		}, 
		
		getMarkers: function(){
			$.getJSON(ajaxUR, {area: 'site', meth: 'getMarkers'}, function(data){
				$('#distroGmap').gMap({
					zoom: 5,
					markers: data,
					scrollwheel: false
				});
				$gmap.setCenter(new GLatLng(54.201129479036595, -2.988206148147583), 5); // center of the UK
				$('div.childInfo').hide();
			});
		}, 
		
		distribClick: function(){
			$('a.distribClick').live("click", function(){
				var id = $(this).attr("rel");
				var childInfo = $(this).parent().parent().children('div.childInfo');
				if(childInfo.is(':hidden')){
					$('div.childInfo').slideUp('fast');
					childInfo.slideDown('fast');
					myclick(id);
				}
				return false;
				
			})
		}, 
		
		addListeners: function(){
			GEvent.addListener($gmap, "click", function(marker, point){
				if(marker) alert(marker.attr('id'));
			});
		}
	}

function toDifferentAddress(){
	$('input#toDifferentAddress').click(function(){
			$('ul#deliveryForm').slideDown('slow');
		});
		$('input#toBillingAddress').click(function(){
			$('ul#deliveryForm').slideUp('slow');
		});
		if($('input#toDifferentAddress').is(':checked')) $('ul#deliveryForm').slideDown('slow');
}

function makePaymentButton(){
	$('a#makePayment').click(function(){
			var theButton = $(this);
			theButton.attr('disabled', true).children('span').text('Please wait...');
			$('ul.errors').slideUp('slow', function(){
				$(this).remove();
			})
			var formData = $('form').serialize();
			$.post(ajaxUR, formData, function(data){
				if(data.Status == 'OK'){
					$('form').parent().append(data.Form);
					$('form#processor').submit();
				}
				else {
					$('form').parent().prepend(data.Errors);
					theButton.attr('disabled', false).children('span').text('Make Payment');
					$('html, body').animate({
						scrollTop: $("#content").offset().top
					}, 2000);
				}
			}, 'json');
			return false;
		});
}


// Gallery

function switchGalleryImage(){
	$('a.imageThumb').click(function(){
		var image = $(this).children('img').attr('src');
		$('img#theImage').attr('src', image.replace('_thumb', '_main'));
		return false;
	});
}

// Image Cycles

function homePageImageCycle(){
	
	if($('div#imageCycle > div').length){
		$('div#imageCycle > div').cycle({
			fx: 'fade',
			speed: 2500
		});
	}
	
}

/** 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 course');
		}
		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 = siteUR + '/images/noimage.png';
		else 
			var img = siteUR + '/images/products/' + firstThumb + '_main.png';
			var imgLarge = siteUR + '/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', siteUR + '/images/products/'+theID+'_main.png');
		var imgLarge = siteUR + '/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();
}
