$(document).ready(function() {
	/* Search */
	$('.button-search').bind('click', function() {
		url = $('base').attr('href') + 'index.php?route=product/search';

		var filter_name = $('input[name=\'filter_name\']').attr('value')

		if (filter_name) {
			url += '&filter_name=' + encodeURIComponent(filter_name);
		}

		location = url;
	});

	$('#header input[name=\'filter_name\']').keydown(function(e) {
		if (e.keyCode == 13) {
			url = $('base').attr('href') + 'index.php?route=product/search';

			var filter_name = $('input[name=\'filter_name\']').attr('value')

			if (filter_name) {
				url += '&filter_name=' + encodeURIComponent(filter_name);
			}

			location = url;
		}
	});

	/* Ajax Cart */
	$('#cart > .heading a').bind('click', function() {
		$('#cart').addClass('active');

		$.ajax({
			url: 'index.php?route=checkout/cart/update',
			dataType: 'json',
			success: function(json) {
				if (json['output']) {
					$('#cart .content').html(json['output']);
				}
			}
		});

		$('#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');
			});
		}
	}

    /* Mega Menu */
    $('#gift-finder-bar 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 = $('#gift-finder-bar').offset();
        var dropdown = $(this).parent().offset();

        i = (dropdown.left + $(this).outerWidth()) - (menu.left + $('#gift-finder-bar').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) {
            $('#gift-finder-bar > ul > li').bind('mouseover', function() {
                $(this).addClass('active');
            });

            $('#gift-finder-bar > 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();
		});
	});

   $('#mn_finder').click(function(e){
       e.preventDefault();
       //return false; //added to disable slide down
       if ( $('#gift-finder-bar').is(':visible') )
       {
           $('#gift-finder-list').fadeOut('slow', function(){
               $('#gift-finder-bar').slideUp('slow');
           });
       }
       else
       {
           $('#gift-finder-bar').slideDown('slow', function(){
               $('#gift-finder-list').fadeIn('slow');
           });
       }
   });
   $('#gift-finder-bar > ul > li').mouseover(function(){
        var sElem = $(this).attr('id').replace('gf_', '#gfd_');
        $(sElem).show();
   });
   $('#gift-finder-bar > ul > li').mouseout(function(){
        var sElem = $(this).attr('id').replace('gf_', '#gfd_');
        $(sElem).hide();
   });
   $('.gift-finder-next').click(function(e){
       e.preventDefault();
       var sElem = $(this).attr('id').replace('gfl_', '#gfd_');
       $(sElem).hide();
   });
   $('.impedient').click(function(e){
       e.preventDefault();
   });

   $('.gift-finder-submit').click(function(e){
       e.preventDefault();
       if ( $('#gift-finder-form input[type="checkbox"]').filter(":checked").length > 0 )
       {
            //console.log('found checked box');
           $('#gift-finder-form').submit();
       }
       else
       {
           alert('Please check at least one category from the gift finder category lists to search for your gift.');
       }
   });
   $('select.selectbox').selectbox();
   $('#logobox').click(function(){
       location.href='/';
   });
});

function addToCart(product_id, img_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>');

					$('.warning').fadeIn('slow');

					$('html, body').animate({ scrollTop: 0 }, 'slow');
				}
			}

			if (json['success']) {
				$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

				$('.success').fadeIn('slow');

				$('#cart_total').html(json['total']);

				$('html, body').animate({ scrollTop: 0 }, 'slow');
			}
		},
        complete: function () {
            if ( $('#cartdiv').is(":visible") )
            {}
            else
            {
                $('#cartdiv').fadeIn('slow');
            }
            var image = $('#'+img_id).offset();
            var cart  = $('#cart .heading').offset();

            $('#'+img_id).before('<img src="' + $('#'+img_id).attr('src') + '" id="temp" style="position: absolute; top: ' + image.top + 'px; left: ' + image.left + 'px;" />');

            params = {
                top : cart.top + 'px',
                left : cart.left + 'px',
                opacity : 0.0,
                width : $('#cart .heading').width(),
                height : $('#cart .heading').height()
            };

            $('#temp').animate(params, 'slow', false, function () {
                $('#temp').remove();
            });
        }
	});
}

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="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

				$('.success').fadeIn('slow');

				$('#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="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

				$('.success').fadeIn('slow');

				$('#compare_total').html(json['total']);

				$('html, body').animate({ scrollTop: 0 }, 'slow');
			}
		}
	});
}

//Giftfinder tickbox functions
function unCheckAll( categoryList ){
    if( categoryList && $('#'+categoryList+"_untick").is(':checked') ){
        $('#gf_'+categoryList+" :input").each(function(index){
            $(this).attr('checked', false);
            $('#'+categoryList+"_untick").attr('checked', true);
        });

    }

    $.ajax({
        url: 'index.php?route=common/header/ajax_gf_filter_categories',
        type: 'post',
        data: $('#gift-finder-list :input').serializeArray(),
        dataType: 'json',
        success: function(json) {
            $.each( json['categories'], function(mainCategory){
                $.each( json['categories'][mainCategory]['children'], function(category){
                    if( categoryList != json['categories'][mainCategory]['name'].toLowerCase() ){
                        if( json['categories'][mainCategory]['children'][category]['product_total'] == 0 ){
                            $("li #gf_" + json['categories'][mainCategory]['children'][category]['sElemId']).hide();
                        }else{
                            $("li #gf_" + json['categories'][mainCategory]['children'][category]['sElemId']).show();
                        }
                    }
                });    
            });            
        }
    });    
}

function unCheckDefault( categoryList ){
    $('#'+categoryList+"_untick").attr('checked', false);
    
    $.ajax({
        url: 'index.php?route=common/header/ajax_gf_filter_categories',
        type: 'post',
        data: $('#gift-finder-list :input').serializeArray(),
        dataType: 'json',
        success: function(json) {
            $.each( json['categories'], function(mainCategory){
                $.each( json['categories'][mainCategory]['children'], function(category){
                    if( categoryList != json['categories'][mainCategory]['name'].toLowerCase() ){
                        if( json['categories'][mainCategory]['children'][category]['product_total'] == 0 ){
                            $("li #gf_" + json['categories'][mainCategory]['children'][category]['sElemId']).hide();
                        }else{
                            $("li #gf_" + json['categories'][mainCategory]['children'][category]['sElemId']).show();
                        }
                    }
                });    
            });            
        }
    });
}
