/**
 * build the notification object, used for any
 * notifications to the user with the purr jquery
 * plugin
 */
var loaded_mini_basket = false;

$(function() {
/*
 * Deal with text area and input text-box character counters.
 */
        $('.char_counter').each(function() {
                $('#'+$(this).attr('target')).livequery('keydown keyup', function() {
                        referers = $('[target="'+$(this).attr('id')+'"]');
                        remaining_length = $(this).attr('maxlength') - $(this).val().length;

                        referers.html(remaining_length);
                });
        });
        $('.char_counter').keydown();

	$('.content_tabs_large, .content_tabs').tabs();
});

	/*
	 * Image rollovers.  Any image with class "rollover" will have _on
	appended to the filename (excluding extension) on over, and removed
	on blur.
	 *
	 */

	$('.template_button').livequery(function() {


		$(this).each(function(e) {

			if ($(this).attr('a')) {

				$(this).after('<span class="button_end template_button_end"></span>');	

			} else {

				$(this).after('<span class="button_ending template_button_end"></span>');	

			}
			
		});

		$(this).hover(
			function () {
				   final_button = $(this).next('.template_button_end');
				   $(this).css('background-image', $(this).css('background-image').replace(/\.([^\.]*)$/, '_on.$1'));
				   $(this).next('.template_button_end').css('background-image', final_button.css('background-image').replace(/\.([^\.]*)$/, '_on.$1'));
				   
			},
			function() {
				   final_button = $(this).next('.template_button_end');
				   $(this).css('background-image', $(this).css('background-image').replace(/_on\.([^\.]*)$/, '.$1'));
				   $(this).next('.template_button_end').css('background-image', final_button.css('background-image').replace(/_on\.([^\.]*)$/, '.$1'));
			}
			);

    });

	$('img.rollover:not(.active), input.rollover:not(.active)').live('mouseover mouseout', function(event) {
        if (event.type == 'mouseover') {
            $(this).attr('src', $(this).attr('src').replace(/\.([^\.]*)$/, '_on.$1'));
        } else {
		$(this).attr('src', $(this).attr('src').replace(/_on\.([^\.]*)$/, '.$1'));
        }
    });

$('.template_snippet_popup').live('click', function(e) {
		e.preventDefault();

		popup_width = '400px';
		popup_height = '500px';

		if ($(this).attr('rev')) {
			values = $(this).attr('rev');
			values = values.split(';');
			for (key in values) {
				if (values[key].substr(0, 5) == 'width') {
					popup_width = values[key].substr(6);
				}
				else if (values[key].substr(0, 6) == 'height') {
					popup_height = values[key].substr(7);
				}
			}
		}

		$.get('/ajax/Ajax_Content/getSnippet', { snippet_name: $(this).attr('rel') }, function (response) {
			$.colorbox({width: popup_width, height: popup_height, html: response['snippet_content'], scrolling: true, onOpen:function() { $("body").css("overflow", "hidden"); }, onClosed:function() { $("body").css("overflow", "auto"); }});
			}, 'json');
		});

function processingPopupStart() {
	$.colorbox({width: 300, height: 180, html: '<div class="center"><br /><p><strong>PLEASE WAIT</strong></p><img src="/aurora/_backend/templates/_images/template/loading.gif" alt="" /><br /><br /><p>Your request is being processed...</p></div>', scrolling: false, close: '', onOpen:function() { $("body").css("overflow", "hidden"); }, overlayClose: false, escKey: false});
}

function processingPopupStop() {
	$.colorbox.close();
}

$(document).ready(function() {

    /**
     * product quicklook code
     */

    $('.quicklook_container, .productlist_grid_item, .productlist_list_item').live('hover', function(e) {
        if (e.type == 'mouseover') {
            $(this).find('.quicklook_button').fadeIn('fast');
        } else {
            $(this).find('.quicklook_button').fadeOut('fast');
        }
    });

    /**
     * generic code to allow any link with
     * a class of quicklook and a rel of
     * product id to open a quicklook
     */
    $('a.quicklook').unbind('click').live('click', function()
    {
        if ($(this).attr('rel') != undefined && $(this).attr('rel') != '')
        {
            openAuroraQuicklook($(this).attr('rel'));
        }
        return false;
    });

/*
    $('a.quicklook').hover(function() {
        var srcParts = $(this).find('img').attr('src').split('/');
        srcParts[srcParts.length-1] = 'quicklook_large_on.gif';
        $(this).find('img').attr('src', srcParts.join('/'));
    }, function() {
        var srcParts = $(this).find('img').attr('src').split('/');
        srcParts[srcParts.length-1] = 'quicklook_large.gif';
        $(this).find('img').attr('src', srcParts.join('/'));
    });
*/

    /**
     * code for selecting a product swatch and it
     * updating the main product images
     */
    $('.productlist_grid_swatches a').unbind('click').live('click', function()
    {
        var container;
        if ($(this).closest('.productlist_grid_item').length)
        {
            container = $(this).closest('.productlist_grid_item');
        }
        else if ($(this).closest('.productlist_list_item').length)
        {
            container = $(this).closest('.productlist_list_item');
        }
        var productID = container.attr('rel');

        $('.productlist_grid_swatches a').removeClass('selected');
        $(this).addClass('selected');

        var selectedValues = [];
        selectedValues[selectedValues.length] = $(this).attr('rel');
        $.getJSON('/ajax/Ajax_Products/getVariationImage', {product_id: productID, find_variation_image: true, variation: JSON.stringify(selectedValues)}, function(response)
        {
            var imageID = response[0];
            if (imageID != '' && imageID != undefined && imageID != null)
            {
                var srcParts = container.find('.productlist_grid_image img').attr('src').split('/');
                srcParts[srcParts.length-1] = imageID;
                container.find('.productlist_grid_image img').attr('src', srcParts.join('/'));
            }
        });
        return false;
    });
});

/**
 * function to load a quicklook window
 * based on a passed product id
 */
function openAuroraQuicklook(productID)
{
    if (productID == undefined) {
        return false;
    }

    $.get('/ajax/Ajax_Products/getQuickViewContent', { quick_view: productID }, function (response) {
        $.colorbox({width:"595px", height:"480px", html: response[0], scrolling: true, onOpen:function() { $("body").css("overflow", "hidden"); }, onClosed:function() { $("body").css("overflow", "auto"); }});
		setTimeout("MagicZoomPlus.refresh()", 1000);
		$('.quicklook_tabs').tabs();
	}, 'json');
}

$('.generic_view_mini_basket_dropdown').livequery(function() {

		$(this).mouseover(function () {

			//	alert(loaded_mini_basket);

			if ($('.mini_basket_pod_items').html().replace(/[^\d]/g, "") > '0') {

				if (loaded_mini_basket) {

			//	$('.mini_basket_complete_container').fadeIn('300');
				$('.mini_basket_complete_container').show();

				} else {

				$.get('/ajax/Ajax_Basket/getDropdownBasket', function(responseJson) {

					$('.mini_basket_complete_container').html(responseJson[0]).show();
					loaded_mini_basket = true;


					}, 'json');

				}

			}

		});

});

$(document).click(function() {

	if ($('.mini_basket_complete_container:visible')) {
		$('.mini_basket_complete_container').fadeOut('300');
	}
});

$('.mini_basket_close').livequery('click', function(e) {
	e.preventDefault();

	$('.mini_basket_complete_container').fadeOut('300');

});

$('.template_login').livequery('click', function(e) {
	e.preventDefault();

	$this = $(this);

	$.get('/ajax/Ajax_Login/getLoginForm', function (responseJson) {
		$.colorbox({width:"640px", height:"270px", html: responseJson['loginForm'], scrolling: true, onOpen:function() { $("body").css("overflow", "hidden"); }, onClosed:function() { $("body").css("overflow", "auto"); }});


		}, 'json');

		$('body').append('<div class="template_popup_login_form_redirect">' + $this.attr('rel') + '</div>');
		$('.template_popup_login_form_redirect').hide();

});



    $('.template_popup_login_form').livequery('submit', function(e) {

	    e.preventDefault();

		$.get('/ajax/Ajax_Login/submitLoginForm', { ajax: true, login_email_address: $('.popup_login_email_address').val(), login_password: $('.popup_login_password').val() }, function (responseJson) {

			if (responseJson[0] == true) {
				$('.template_popup_login_container').hide();
				$('.template_popup_login_container').find('.correctbox').find('h2').html(responseJson[1]);
				$('.template_popup_login_container').fadeIn('500');

				if ($('.template_popup_login_form_redirect').length) {
					setTimeout("window.location = '" + $('.template_popup_login_form_redirect').html() + "'", 1000);

				} else {
					setTimeout("window.location = '/checkout'", 1000);
				}

			} else {
				$('.template_popup_login_error').fadeIn("500", function () {
					$(this).addClass('errorbox');
					$(this).find('h2').html(responseJson[1]).fadeIn("500");
				});
			}



		}, 'json');


    });


    $('.email_signup_form').livequery('submit', function(e) {

	e.preventDefault();

	var params = { email_signup: $(this).find('.email_signup').val(), email_first_name: $(this).find('.email_first_name').val(), email_last_name: $(this).find('.email_last_name').val(), email_list: $(this).find('.email_list').val() }
	var httpsOrNot = (("https:" == document.location.protocol) ? "i-want-https" : "i-want-no-https");
	params[httpsOrNot] = true;

	params['custom_fields'] = $(this).find('.custom_email_field').serialize();

		$.get('/ajax/Ajax_Email/emailSignup', params, function (responseJson) {
			$.colorbox({width:"400px", height:"200px", html: responseJson['email_signup_response'], scrolling: true, onOpen:function() { $("body").css("overflow", "hidden"); }, onClosed:function() { $("body").css("overflow", "auto"); }});

		}, 'json');

    });

    $('.template_print_page').livequery('click', function(e) {

	    e.preventDefault();
	    window.print();

    });


var changeSearchTimeout;
var changeSearchLastValue;

function auroraSearchProducts () {

	$this = $('.template_search_input');

	if ($('.template_search_input').val() != changeSearchLastValue) {

		$.getJSON('/products/search/s:'+$this.val(), { ajax: true, items_per_page: '5', search: $this.val() }, function (responseJson) {
			if(responseJson[0] > 0) {
				$('.template_quicksearch_container').show().html(responseJson[1]);
			} else {
				$('.template_quicksearch_container').hide();
			}
		});

		changeSearchLastValue = $('.template_search_input').val();
	}

}

$('.template_search_input').livequery('keyup', function(e) {
	clearTimeout(changeSearchTimeout);
	changeSearchTimeout = setTimeout("auroraSearchProducts()", 300);
});


/**
 * This function take a string block of text/HTML and an array of data and merges the two.
 * @param string text
 * @param array data The data to be merged
 */
function mergeHtmlBlock(text, data) {
	// Replace the script tag place holders
	text = text.replace(/\/\*TEMPLATE SCRIPT/ig, '');
	text = text.replace(/TEMPLATE SCRIPT\*\//ig, '');
	// Remove the hidden block place holders (these allow html to be completely commented out if required)
	text = text.replace(/\<\!\-\-TEMPLATE HIDDEN BLOCK/ig, '');
	text = text.replace(/TEMPLATE HIDDEN BLOCK\-\->/ig, '');
	// jQuery thinks it's being clever when it URL encodes HTML for you, but not always,
	// so here we must undo this damage if it is found.
	text = text.replace(/\%7b/ig, '{');
	text = text.replace(/\%7d/ig, '}');
	for (var_name in data) {
		text = text.replace(new RegExp('{'+var_name+'}', 'g'), data[var_name]);
	}
	return text;
}

$('.template_change_currency').livequery(function() {
	$(this).hover(
		function () {
			$(".template_currency_links").show();
		},
		function() {
			$(".template_currency_links").hide();
		}
	);
});

