var focusFlag = 1;
var rotateTimeout = '';
var new_start = 0;

$(document).ready(function() {


	$(".rotate_item").cycle({
		fx:      'fade',
		timeout: 6000,
		next: '#latest_next',
		prev: '#latest_prev'
	});

	$('.saveToCart').click(function(){
		$(this).after('<span class="wait">&nbsp;<img src="catalog/view/theme/default/image/loading.gif" alt="" /></span>');
	});

	$('.selectBoxes').click(function(){
		$('input[type="checkbox"]').attr('checked', true);
		return false;
	});

	$('.clearBoxes').click(function(){
		$('input[type="checkbox"]').attr('checked', false);
		return false;
	});

	/* Search */
	$('.button-search').bind('click', function() {
		url = 'index.php?route=product/search';

		var filter_name = $('input[name=\'filter_name\']').attr('value')

		if (filter_name) {
			url += '&filter_name=' + encodeURIComponent(filter_name);
		}

		//always search descriptions
		url += '&filter_description=true';

		location = url;
	});

	$('#header input[name=\'filter_name\']').keydown(function(e) {
		if (e.keyCode == 13) {
			url = 'index.php?route=product/search';

			var filter_name = $('input[name=\'filter_name\']').attr('value')

			if (filter_name) {
				url += '&filter_name=' + encodeURIComponent(filter_name);
			}


			//always search descriptions
			url += '&filter_description=true';

			location = url;
		}
	});

	/* Ajax Cart */
	$('#cart > .heading a').bind('click', function() {
		$('#cart').addClass('active');

		$.ajax({
			url: 'index.php?route=checkout/cart/update',
			dataType: 'json',
			beforeSend: function(){
				$('#cart > .content').addClass("large_pending");
			},
			success: function(json) {
				if (json['output']) {
					$('#cart .content').html(json['output']);
				}
			},
			complete: function(){
				$('#cart > .content').removeClass("large_pending");
				$('#cart > .content').addClass("bgWhite");
			}
		});

		$('#cart').bind('mouseleave', function() {
			$(this).removeClass('active');
		});
	});

	/* Mega Menu */
	$('#menu ul > li > a + div').each(function(index, element) {
		// IE6 & IE7 Fixes
		if ($.browser.msie && ($.browser.version == 7 || $.browser.version == 6)) {
			var category = $(element).find('a');
			var columns = $(element).find('ul').length;

			$(element).css('width', (columns * 143) + 'px');
			$(element).find('ul').css('float', 'left');
		}

		var menu = $('#menu').offset();
		var dropdown = $(this).parent().offset();

		i = (dropdown.left + $(this).outerWidth()) - (menu.left + $('#menu').outerWidth());

		if (i > 0) {
			$(this).css('margin-left', '-' + (i + 5) + 'px');
		}
	});

	// IE6 & IE7 Fixes
	if ($.browser.msie) {
		if ($.browser.version <= 6) {
			$('#column-left + #column-right + #content, #column-left + #content').css('margin-left', '195px');

			$('#column-right + #content').css('margin-right', '195px');

			$('.box-category ul li a.active + ul').css('display', 'block');
		}

		if ($.browser.version <= 7) {
			$('#menu > ul > li').bind('mouseover', function() {
				$(this).addClass('active');
			});

			$('#menu > ul > li').bind('mouseout', function() {
				$(this).removeClass('active');
			});
		}
	}
});

$('.success img, .warning img, .attention img, .information img').live('click', function() {
	$(this).parent().fadeOut('slow', function() {
		$(this).remove();
	});
});


function messageFadeout(){
	$('#notification').each(function(){
		thisOne = $(this);
		setTimeout(function(){
			thisOne.fadeTo('slow', 0.1, function(){
				thisOne.html(' ');
				thisOne.fadeTo('fast', 1);
			});
//			setTimeout("thisOne.html(' ').show()", 1900);
		} , 5000);

	});
}

function getAllLatest(){
	var latest_items = new Array();
	$(".latest_item_hid").each(function(){
		var item_contents = $(this).html();
		latest_items.push(item_contents);
	});
//	console.log(latest_items);
	return latest_items;
}

function fadeNewItem(rotateThis, rotateTo, milis, num){
	delayTime = parseFloat(num) * 3;
	milis = parseFloat(milis);

	setTimeout(function(){
	rotateThis.fadeTo(milis, 0.1 ,function(){
			rotateThis.html(rotateTo);
			$(this).fadeTo(milis, 1);
		});
	}, delayTime + '00');
}


function rotateLatestItems(start_at){
	latest_items = getAllLatest();
//	console.log(latest_items[1]);
//	return;

	//should be pulled dynamically
	var transition_count = 8;
	var max_count = 24;

	var new_start = parseFloat(start_at) + parseFloat(transition_count);
	if(new_start >= max_count){ new_start = 0; }

	var c = 0
	var transition_to = new Array();


		transition_to.push(latest_items[start_at], latest_items[start_at + 1], latest_items[start_at + 2],latest_items[start_at + 3], latest_items[start_at + 4], latest_items[start_at + 5], latest_items[start_at + 6], latest_items[start_at + 7]);

//	console.log(transition_to);
//	for(var i in latest_items){
//		if(++c >= start_at && c < new_start ){
//			transition_to.push(latest_items[i]);
//		}
//		else if(c >= max_count){
//			c = 0;
//
//		}
//	}

	var rotate_these = new Array();
	$('.latest_item').each(function(){
		var thisOne = $(this);
		rotate_these.push(thisOne);
	});


//	alert(start_at);
	for(var i in rotate_these){
//		rotate_these[i].fadeOut(500, function(){
//			$(this).html(transition_to[i]);
//			$(this).fadeIn(500);
//		});
//		rotate_these[i].fadeOut(500);
		var rotateThis = rotate_these[i];
		var rotateTo = transition_to[i];

		fadeNewItem(rotateThis, rotateTo, '750', i);
//		setTimeout(function(){ rotate_these[i].html(transition_to[i]);}, 500);
//		rotate_these[i].fadeIn(500);

	}
//	console.log(latest_items);
	if(focusFlag == 1){
		rotateTimeout = setTimeout(function(){rotateLatestItems(new_start)}, 8000);
	}
}

$(window).focus(function() {
	console.log('Focus');
	clearTimeout(rotateTimeout);
	rotateTimeout = setTimeout(function(){rotateLatestItems(new_start)}, 8000);
});

 $(window).blur(function() {
	console.log('Blur');
	clearTimeout(rotateTimeout);

 });


function attentionHere(attnObject){
//	alert('hello');
//	attnObject.remove();
	attnObject.css('font-weight', 'bold');
	attnObject.animate({ backgroundColor: "#F0B475"}, 800, function(){
		attnObject.animate({ backgroundColor: "#ffffff"}, 800, attentionHere(attnObject));
	});
}

$('.success img, .warning img, .attention img, .information img').live('click', function() {
	$(this).parent().fadeOut('slow', function() {
		$(this).remove();
	});
});


function addToCart(product_id) {
	$.ajax({
		url: 'index.php?route=checkout/cart/update',
		type: 'post',
		data: 'product_id=' + product_id,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information, .error').remove();

			if (json['redirect']) {
				location = json['redirect'];
			}

			if (json['error']) {
				if (json['error']['warning']) {
					$('#notification').html('<div class="warning" style="display: none;">' + json['error']['warning'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
				}
			}

			if (json['success']) {
				$('#notification').html('<div class="attention" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

				$('.attention').fadeIn('slow');

				$('#cart_total').html(json['total']);

				$('html, body').animate({ scrollTop: 0 }, 'slow');

				//delete this item from saved list after adding to cart
//				var deleteConfirm = confirm('Would you also like to remove this item from your saved list?');
				var deleteConfirm = true;
				if(deleteConfirm == true){
					$('input[type="checkbox"]').attr('checked', false);
					$('input[type="checkbox"][value="' + product_id + '"]').attr('checked', true);
					$('#updateButton').click();
				}
			}
		}
	});
}

function removeCart(key) {
	$.ajax({
		url: 'index.php?route=checkout/cart/update',
		type: 'post',
		data: 'remove=' + key,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();

			if (json['output']) {
				$('#cart_total').html(json['total']);

				$('#cart .content').html(json['output']);
			}
		}
	});
}

function removeVoucher(key) {
	$.ajax({
		url: 'index.php?route=checkout/cart/update',
		type: 'post',
		data: 'voucher=' + key,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();

			if (json['output']) {
				$('#cart_total').html(json['total']);

				$('#cart .content').html(json['output']);
			}
		}
	});
}

function addToWishList(product_id) {
	$.ajax({
		url: 'index.php?route=account/wishlist/update',
		type: 'post',
		data: 'product_id=' + product_id,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();

			if (json['success']) {
				$('#notification').html('<div class="attention" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

				$('.attention').fadeIn('slow');

// wishlist total broken, see doit.im covetedclothing.com 1.1
//				$('#wishlist_total').html(json['total']);

				$('html, body').animate({ scrollTop: 0 }, 'slow');
			}
		}
	});
}

function addToCompare(product_id) {
	$.ajax({
		url: 'index.php?route=product/compare/update',
		type: 'post',
		data: 'product_id=' + product_id,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();

			if (json['success']) {
				$('#notification').html('<div class="attention" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

				$('.attention').fadeIn('slow');

				$('#compare_total').html(json['total']);

				$('html, body').animate({ scrollTop: 0 }, 'slow');
			}
		}
	});
}

