var showImageVariations = 0;


/*
	* Function to see whether any attributes have not been selected
*/

function validateAttributes ($this) {

	var missingVals = [];
	$this.find('.attribute_selected').each(function() {
		if ($(this).val() == '' || $(this).val() == undefined || $(this).val() == null) {
			missingVals[missingVals.length] = $(this).attr('title');
		}
	});

	var all_radio_buttons = [];

	$this.find('input[type=radio]').each(function() {
		all_radio_buttons[$(this).attr('name')] = $(this).attr('title');
	});

	for (x in all_radio_buttons) {
		if ($this.find('input[type=radio][name='+x+']:checked').val()) {
		} else {
			missingVals[missingVals.length] = all_radio_buttons[x];
		}
	}

	return missingVals;
}


    /**
     * event handler for standard <select> attribute value
     * selections
     */

    $('.attribute_select:visible').livequery(function() {
	    
	    
        /**
         * if the quantity drop down exists, or
         * were on the wishlist page, update quantity
         */

	    $(this).change(function() {
	//	if ($('select[name="product_quantity"]').length || $(this).closest('.productAttributes').hasClass('type_wishlist')) {
		    var quantity = getAttributeQuantity($(this).closest('.productAttributes'));
		    if (quantity !== false && $(this).closest('.productAttributes').hasClass('type_wishlist')) {
	//		updateWishListQuantity($(this), quantity);
	//	    }
		}
	    });
    });

    $('.attribute_radio:visible').livequery(function() {

	    $(this).click(function() {
		if ($('select[name="product_quantity"]').length || $(this).closest('.productAttributes').hasClass('type_wishlist')) {
		    var quantity = getAttributeQuantity($(this).closest('.productAttributes'));
		    if (quantity !== false && $(this).closest('.productAttributes').hasClass('type_wishlist')) {
	//		updateWishListQuantity($(this), quantity);
		    }
		}
	    });

    });

$(document).ready(function() {
    showImageVariations = parseInt($('input[name="show_image_variations"]').val());

    preSelectAttributes();


	/*
		* If it's a radio button, alter the design of it and make it so when you click on a button, it alters the radio button value too
	*/

    $('.attribute_value_list').find('a').unbind('click').click(function(e) {
	    e.preventDefault();

	    if (!$(this).hasClass('notavailable')) {
		    $(this).closest('.attribute_value_list').find('a').removeClass('selected');
		    $(this).addClass('selected');
		    $(this).closest('.attribute_container').find('.attribute_selected').val($(this).attr('href'));
	    }
    });

    /**
     * add to basket submission
     */
    $('.add-to-basket').livequery('submit', function() {
       // $(this).unbind('submit');
        $(this).find('.errors').empty();
        $(this).find('.errors').hide();


	if ($(this).hasClass('compare_add')) {


	var missingVals = [];

            $(this).find('.productAttributes').each(function() {

		if ($(this).parent().parent().find('.compare_add_to_basket:checked').length) {

			$(this).find('.attribute_selected').each(function() {

				if ($(this).val() == '' || $(this).val() == undefined || $(this).val() == null) {
					missingVals[missingVals.length] = $(this).attr('title');
				}
			});
		}

                if (missingVals.length) {

		//	$('.compare_errors').addClass('errorbox').html('Sorry, you have missed something');

                    var container = $('<div />').addClass('errorbox');
                    $('<h3 />').html('Sorry you have missed something').appendTo(container);
                    container.appendTo($(this).find('.errors'));
                    $(this).find('.errors').show();
                }
            });

            if (missingVals.length) {
                return false;

            } else {

		    var data = $(this).serialize();


		    if ($('.compare_add_to_basket:checked').length) {
			    $.post('/ajax/Ajax_Basket/addToBasketDropdown', { all_fields: data, add_compare: true }, function(responseJson) {

					    $.colorbox.close();
					    $('.mini_basket_complete_container').fadeIn('300').html(responseJson[0]);
					    $('.mini_basket_pod_items').html(responseJson[1]);
					    $('.mini_basket_pod_items_text').html(responseJson[2]);
					    $('.mini_basket_pod_totals_price').html(responseJson[3]);
					    $.scrollTo(0,0, { duration: '500' });
					    $('.compare_add_to_basket').attr('checked', false);
					    loaded_mini_basket = false;

			    }, 'json');

		    }

                return false;

	    }







	} else if ($(this).hasClass('basket_cross_sell_add')) {

		var missingVals = [];

		$(this).find('.productAttributes').each(function() {
		//	console.log('Ssearching');


			if ($(this).parent().parent().find('.basket_cross_sell_add_to_basket:checked').length) {

				$(this).find('.attribute_selected').each(function() {

					if ($(this).val() == '' || $(this).val() == undefined || $(this).val() == null) {
						missingVals[missingVals.length] = $(this).attr('title');
					}

					});
				}

				if (missingVals.length) {
					var container = $('<div />').addClass('errorbox');
					$('<h3 />').html('Sorry you have missed something').appendTo(container);
					container.appendTo($(this).find('.errors'));
					$(this).find('.errors').show();
				}
				});

            if (missingVals.length) {
                return false;

            } else {

		    var data = $(this).serialize();
		    $.scrollTo($('.basket_data'), { duration: '500' });
		    $('.basket_cross_sell_add_to_basket').attr('checked', false);

		    $.post('/ajax/Ajax_Basket/addToBasketDropdown', { all_fields: data, add_cross_sell: true }, function(responseJson) {

				loaded_mini_basket = false;
				update_basket($(this));


			}, 'json');

                return false;

	    }



	} else if ($(this).hasClass('bundleadd')) {
		var missingVals = [];

            $(this).find('.productAttributes').each(function() {
                $(this).find('.attribute_selected').each(function() {
                    if ($(this).val() == '' || $(this).val() == undefined || $(this).val() == null) {
                        missingVals[missingVals.length] = $(this).attr('title');
                    }
                });
                if (missingVals.length) {
                    var container = $('<div />').addClass('errorbox');
                    $('<h3 />').html('Sorry you have missed something').appendTo(container);
                    container.appendTo($(this).find('.errors'));
                    $(this).find('.errors').show();
                }

            });
		    if (missingVals.length) {
			return false;
		    }


        } else {

		missingVals = validateAttributes($(this));

            if (missingVals.length) {
                var container = $('<div />').addClass('errorbox');
                $('<h3 />').html('Sorry you have missed something').appendTo(container);
                var ul = $('<ul />').appendTo(container);
                $(missingVals).each(function(i, item) {
                    $('<li />').html('This option is required: <span class="attributes_error">'+item+'</span>.').appendTo(ul);
                });
                if (!$(this).hasClass('bundleadd')) {
                    container.appendTo($(this).find('.errors'));
                }
                $(this).find('.errors').show();
                return false;
            }
        }
        
        if ($(this).hasClass('add-to-basket-ajax') && !$(this).hasClass('add-to-basket-disabled')) {
            /**
             * ajax submission instead
	     * this would be used for quicklook
             */
		    var data = $(this).serialize();
		    $.post('/ajax/Ajax_Basket/addToBasketDropdown', { all_fields: data }, function(responseJson) {
        		$.colorbox.close();
        		$('.mini_basket_complete_container').fadeIn('300').html(responseJson[0]);
        		$('.mini_basket_pod_items').html(responseJson[1]);
        		$('.mini_basket_pod_items_text').html(responseJson[2]);
        		$('.mini_basket_pod_totals_price').html(responseJson[3]);

			loaded_mini_basket = false;

			/* 
				* If we are on the basket page, add it directly to the basket and update
			*/
			var href = window.location.href;
			var hostname = window.location.hostname;
			href = href.substring(href.indexOf(hostname)+hostname.length, href.length);

			if (href == '/basket') {
				$.scrollTo($('.basket_data'), { duration: '500' });
				update_basket($(this));
			} else {
				$.scrollTo(0,0, { duration: '500' });
			}

        	}, 'json');

            return false;
        }
    });
});

function preSelectAttributes()
{
    /**
     * pre-select attributes if there is only one option
     */
    $('.attribute_value_list').each(function()
    {
        if ($(this).find('a').length == 1)
        {
            $(this).find('a').addClass('selected');
            $(this).closest('.attribute_container').find('.attribute_selected option[value!=""]').each(function()
            {
                $(this).parent().val($(this).val());
            });
            //$(this).closest('.attribute_container').hide();
        }
    });

    $('.attribute_selected:visible').each(function() {
        if ($(this).find('option[value!=""]').length == 1) {
            $(this).find('option[value!=""]').each(function() {
                $(this).parent().val($(this).val());
                //$(this).closest('.attribute_container').hide();
            });
        }

    });

	/*
		* If there is only 1 radio button available to choose from, make it selected
	*/

    $('.attribute_container:visible').each(function() {
	    
       // console.log($(this).find('input[type=radio]').length);

        if ($(this).find('input[type=radio]').length == 1) {
                $(this).find('input[type=radio]:first').attr('checked', 'checked');
        }
    });


    $('.productAttributes').each(function() {
        getAttributeQuantity($(this));
    });
}

/**
 * check that all attributes have been selected
 * and if they have, get a valid quantity
 * and enable the quantity drop down
 */
function getAttributeQuantity(container) {

    var quantityObj = container.closest('form').find('select[name="product_quantity"], select[name="ql_product_quantity"]');
    if (!quantityObj || container.hasClass('type_wishlist')) {
        var quantityObj = container.parent().find('select[name="product_quantity"], select[name="ql_product_quantity"]');
    }

    var selectedValues = [];
    var allFields = '';

    $('.productAttributes').find('.attribute_selected').each(function() {
        if ($(this).val() != '' && $(this).val() != undefined && $(this).val() != null && $(this).attr('type') != 'radio') {
            selectedValues[selectedValues.length] = $(this).val();
	    allFields += $(this).attr('name') + "=" + $(this).val() + "&";
        } else if ($(this).attr('type') == 'radio' && $(this).attr('checked')) {
            selectedValues[selectedValues.length] = $(this).val();
	    allFields += $(this).attr('name') + "=" + $(this).val() + "&";
	}
    });

    if (selectedValues.length) {


//	console.log(allFields);
//	console.log(container.closest('form').serialize());

        /**
         * get a stock amount via ajax
         */
        var index = $('.productAttributes').index(container);
        var productID = $('input[name="product_id"]:eq('+index+'), #product_id').val();
        if (container.closest('form').find('input[name="ql_product_id"]').length) {
            productID = container.closest('form').find('input[name="ql_product_id"]').val();
        }

//	console.log(index);
//	console.log(productID);


        var ajaxURL = window.location.href;
        if (container.attr('rel') != '' && container.attr('rel') != undefined) {
            ajaxURL = container.attr('rel');
        }

        if (container.closest('form').find('input[name="ql_product_filename"]').length) {
            ajaxURL = container.closest('form').find('input[name="ql_product_filename"]').val();
        }

	params = { ajax: true, attributes: allFields, product_id: productID }

	if (container.hasClass('type_quicklook')) {
		params['quicklook'] = true;
	}

        var response = $.ajax({type: 'post', url: '/ajax/Ajax_Products/getVariationData',  data: params, async: false, dataType: 'json'}).responseText;
        response = jQuery.parseJSON(response);

        var variation_stock = parseInt(response.variation_stock);
        if (variation_stock > 10) {
            variation_stock = 10;
        }


	if (container.hasClass('type_quicklook')) {

		if (response.show_pre_order_button) {
			if ($('.add_to_basket_button').length) {
				$('.add_to_basket_button').attr('src', $('.add_to_basket_button').attr('src').replace(/addtobasket_small.gif$/, 'preordernow_small.gif'));
			}
		} else {
			if ($('.add_to_basket_button').length) {
				$('.add_to_basket_button').attr('src', $('.add_to_basket_button').attr('src').replace(/preordernow_small.gif$/, 'addtobasket_small.gif'));
			}
		}

	} else {

		if (response.show_pre_order_button) {
			if ($('.add_to_basket_button').length) {
				$('.add_to_basket_button').attr('src', $('.add_to_basket_button').attr('src').replace(/addtobasket.gif$/, 'preordernow.gif'));
			}
		} else {
			if ($('.add_to_basket_button').length) {
				$('.add_to_basket_button').attr('src', $('.add_to_basket_button').attr('src').replace(/preordernow.gif$/, 'addtobasket.gif'));
			}
		}

	}

	if ($('.details_product_stock_information').length) {
		$('.details_product_stock_information').html(response.stock_information);
	}

	if ($('.details_product_delivery_information').length) {
//		$('.details_product_delivery_information').html(response.delivery_information);
	}


	if ($('.details_price_now').length) {
		$('.details_price_now').find('span').html(response.variation_price);
	}

        if (quantityObj.length && variation_stock > 0)
        {
            quantityObj.empty();
            for (var i = 1; i <= variation_stock; i++)
            {
                $('<option />').val(i).text(i).appendTo(quantityObj);
            }
            quantityObj.removeAttr('disabled');
        }

        if (response.images != '') {

		if (container.hasClass('type_quicklook')) {
			$('.quicklook_thumbs_container').html(response.images);
		} else {
			$('.details_thumbs_container').html(response.images);
		}

            /**
             * update zoom images and  product thumbnails
             */

            $('#zoom1 img, .MagicThumb-image, .MagicThumb-image-zoomed').each(function() {
                var srcParts = $(this).attr('src').split('/');
                srcParts[srcParts.length-1] = response.main_image;
                $(this).attr('src', srcParts.join('/'));
            });
    
	    var hrefParts = $('#zoom1').attr('href').split('/');
	    hrefParts[hrefParts.length-1] = response.main_image;
	    $('#zoom1').attr('href', hrefParts.join('/'));
	    MagicZoomPlus.refresh();

        }

        if (container.hasClass('type_wishlist')) {
            return variation_stock;

        } else {
            /**
             * we're on the normal product details page
             */
            if (variation_stock == 0)
            {
                quantityObj.attr('disabled', 'disabled');
                return;
            }
        }

    } else {
        //quantityObj.empty();

	    if ($('.productAttributes').find('.attribute_selected:visible').length) {
		quantityObj.attr('disabled', 'disabled');
	    }

        return false;
    }
}
















/**
 * function to update wishlist stock text
 * based on current element
function updateWishListQuantity(element, quantity)
{
    if (quantity > 0)
    {
        element.closest('tr').find('.stockflag').removeClass('out').addClass('in').html('In Stock');
        element.closest('tr').find('.despatch').html('<strong>24 hours</strong>').show();
    }
    else
    {
        element.closest('tr').find('.stockflag').removeClass('in').addClass('out').html('Out of Stock');
        element.closest('tr').find('.despatch').html('').hide();
    }
}

function loadBasketButtonEvents()
{
    $('.basketadd').unbind('click').click(function(e)
    {
        if (attributesSelected('.type_'+$(this).attr('rel')) == false)
        {
		    e.preventDefault();
	    }
    });
}
*/

