(function() {

function validate(e){

	var error = '';


	if($('#type').val() == 'length'){
	
		if(!$('#length').val().length)
			error += 'Length is Required.\n';
	}
	else{

		if(!$('#quantity').val().length)
			error += 'Quantity is Required.\n';
			
		if(!$('#dimension\\[length\\]').val().length && !$('#dimension\\[length_fraction\\]').val().length
			&& !$('#dimension\\[width\\]').val().length && !$('#dimension\\[width_fraction\\]').val().length)
			error += 'Dimension is Required.\n';
	}

	if(error.length){
	
		alert(error);

		return false;
	}
}

function type_change(e){

	if($('#type').val() == 'length'){
	
		$('#length_table').show();
		$('#other_table').hide();
	}
	else{
	
		$('#length_table').hide();
		$('#other_table').show();
	}
}

function image_switch(e){

	var t = $(e.target);

	if(t.is('img')){

		var link = t.parent();

        // remove active class from all thumbs
	    $('#product_image_micros img').removeClass('active')
        
        // get image info from href of clicked anchor
		var image_info = link.attr('href').substring(link.attr('href').indexOf('#')+1);
    	image_info = image_info.split('&');
    	var image_id = image_info[0];
    	var image_type = image_info[1];
    	
    	// add active class to clicked thumb
	    $(t).addClass('active')

        // set new image url
        var product_id = $('#product_id').val();        
        $('#product_image').attr('src', '/modules/catalog/images/product/'+product_id+'/'+image_id+'-medium.'+image_type);
        
        return false;
    }
}

$(document).ready(function(){

    $('#product_form').submit(validate);
    $('#type').change(type_change);

    if($('#product_image_micros'))
	    $('#product_image_micros').click(image_switch);

	if($('#type'))
		type_change();
});

})();