var sizes_count;

$(document).ready(function(){
	sizes_count = $("th.size_header").length;
	show_steps(0);
	show_steps(1);
	
	$("a.available_colors").click(function(){
		var image_src = $(this).attr('href');
		$("img.product_details_picture").attr('src',image_src);
		return false;
	});
	
	$("#screenprint").click(function(){
		document.getElementById('noofcolors').style.display='';
		/*document.getElementById('color_name').style.display='';
		document.getElementById('color_holder').style.display='';
		document.getElementById('steps1').style.display='none';*/
	});
	
	$("#embroidary").click(function(){
		document.getElementById('noofcolors').style.display='none';
		/*document.getElementById('steps').style.display='none';
		document.getElementById('color_name').style.display='none';		
		document.getElementById('steps1').style.display='';*/
	});
	
	$('div#hidden_color_holder div.color_holder').click(function(){
		var selected_color = $(this).attr('color');
		var selected_color_id = $(this).attr('color_id');
		var selected_color_title = $(this).attr('title');
		
		//=======================================================
		//new added
		var is_multiple = $(this).hasClass('multi_color');
		
		show_steps(2);
		if (!is_multiple) {
			//=======================================================
			$('div#selector div.color_holder').html('');
			$('div#selector div.color_holder').css('background',selected_color).attr('color',selected_color).attr('color_id',selected_color_id);
			//========================================================
		} else {
			$('div#selector div.color_holder').html('');
			$('div#selector div.color_holder').html($(this).html()).attr('color_id',selected_color_id).attr('is_multiple','true');
		}
		
		$('div#hidden_color_holder').fadeOut('fast');
		$("input#add_to_options").attr('disabled','disabled').val('...');
		$("div#color_name").html(selected_color_title);

		reset_sizes_combo(true);
		$("select#sizes").removeAttr('disabled');
		
		if ($("select#sizes").val() != '') $("select#sizes").trigger('click');
	});

	$('select#sizes').change(function(){
		show_steps(3);
		$("select#sizes option:first-child").removeAttr('selected');
		$("input#number").removeAttr('disabled').val(1);
		$("input#add_to_options").removeAttr('disabled').val('Add');
	});
	
	$('div#selector div.color_holder').click(function(){
		var selector = $(this);
		var selector_position = $(selector).offset();

		show_steps(0);
		show_steps(1);

		reset_sizes_combo(true);

		$('div#hidden_color_holder').css({'top':selector_position.top+$(selector).height()+5,'left':selector_position.left}).fadeIn('fast');
	});
	
	$("input#add_to_options").click(function(){
		show_steps(0);
		show_steps(1);
		show_steps(2);
		add_to_options();
		reset_sizes_combo(false);
	});
	
	$("input#proceed_to_design").click(function(){
		add_to_step();
	});
	
	$("table#quantities tr td input.quantity").keyup(function(){
		update_total_quantity();
	});
	
	$("input#calc_price").click(function(){
		calculate_price();
	});
});

function show_steps(step_number){
	switch(step_number){
		case 0:
			$("div#steps img").stop().fadeTo('fast',0.2);
			break;
		default:
			$("div#steps img:nth-child("+step_number+")").stop().fadeTo('slow',1);
	}
}

function reset_sizes_combo(disabled){
	if (disabled){
		$("select#sizes").attr('disabled','disabled');
	} else {
		$("select#sizes").removeAttr('disabled');
	}
	
	$("select#sizes option").removeAttr('selected');
	$("select#sizes option:first-child").attr('selected','selected');
	$("input#number").attr('disabled','disabled').val(1);
	$("input#add_to_options").attr('disabled','disabled').val('...');
}

function set_events(){
	$("table#quantities td img.delete").unbind('click').click(function(){
		if(confirm('Are you sure you want to delete this item?')){
			var price = parseFloat($("table#added_options tr#bottom_th span.total_price").text()) - parseFloat($(this).parent('td').siblings('td').children('span.price').text());
			$("table#added_options tr#bottom_th span.total_price").text(price);
			$(this).parent('td').parent('tr').remove();
			update_total_quantity();
		}
	});
}

function add_to_options() {
	var color = $('div#selector div.color_holder').attr('color');
	var color_id = $('div#selector div.color_holder').attr('color_id');
	var size = $('div#selector select#sizes').val();
	var number = $('div#selector input#number').val();
	var counter,updated_object,updated_index;
	
	if ($("table#quantities tr td div[color_id="+color_id+"]").length) {
		var size_cols = $("table#quantities tr td div[color_id="+color_id+"]").parents("td").siblings('td');

		for(counter = 1; counter <= sizes_count; counter++)
			if($('th.size_header').eq(counter - 1).text() == size){
				var current_number = parseInt($(size_cols).eq(counter-1).text());
				$(size_cols).eq(counter-1)	.text(number)
											.addClass('has_value')
											.attr('size',size);
				updated_index = counter-1;
			}
		
		updated_object = $(size_cols).eq(updated_index);
	} else {
		var new_row = '',size_cols = '';

		for (counter = 1; counter <= sizes_count; counter++) {
			if($('th.size_header').eq(counter - 1).text() == size){
				size_cols += '<td class="has_value" size="'+size+'">'+number+'</td>';
				updated_index = counter;
			} else {
				size_cols += '<td>0</td>';
			}
		}
		
		//==================================================================
		//alert(color_id);
		//alert($('div#selector div.color_holder').attr('is_multiple'));
		
		if ($('div#selector div.color_holder').attr('is_multiple') =='true') {
			//$('div#selector div.color_holder').html('');
			var multi_color = $('div#selector div.color_holder').html();
			new_row = "<tr class='quantity_row'><td><div color_id='"+color_id+"' class='color_holder'>"+multi_color+"</div></td>"+size_cols+"<td><img class='delete' src='images/delete_small.png'/></td></tr>";
			$('div#selector div.color_holder').removeAttr('is_multiple');
		} else {
			new_row = "<tr class='quantity_row'><td><div color_id='"+color_id+"' color='"+color+"' class='color_holder' style='background: "+color+";'></div></td>"+size_cols+"<td><img class='delete' src='images/delete_small.png'/></td></tr>";
		}
		
		//==================================================================
		//new_row = "<tr class='quantity_row'><td><div color_id='"+color_id+"' color='"+color+"' class='color_holder' style='background: "+color+";'></div></td>"+size_cols+"<td><img class='delete' src='images/delete_small.png'/></td></tr>";
		$("table#quantities tr:last-child").before(new_row);
		updated_object = $("table#quantities tr:last-child").prev('tr').children('td').eq(updated_index);
		set_events();
	}

	show_highlight(updated_object);
	update_total_quantity();
}

function show_highlight(object) {
	$(object).append("<div class='highlight'></div>");
	var highlight = $(object).children('div.highlight');
	var object_offset = $(object).offset();
	
	$(highlight).css({'top':object_offset.top+1 , 'left':object_offset.left+2 , 'width':$(object).width()+1 , 'height':$(object).height()+1})
				.animate({opacity:0},100,'',function(){
					$(this).fadeTo('slow',0.8,function(){
						$(this).fadeTo('slow',0,function(){
							$(this).remove();
						});
					});
				});
}

function show_table_loading(bln_show){
	if(bln_show){
		var options_table = $("table#quantities");
		var table_dims = $(options_table).offset();
		$(options_table).before("<div class='loading'></div>");
		var loading_div = $(options_table).siblings("div.loading");
		var loading_div_dims = $(loading_div).offset();
		$(loading_div)	.width($(options_table).width())
						.height($(options_table).height())
						.css({'top':table_dims.top, 'left':table_dims.left})
						.fadeTo('fast',0.6);
		$(loading_div).after("<img class='loading' src='images/loading.gif'/>");
		var loading_image = $(loading_div).siblings("img.loading");
		$(loading_image).css({'top':loading_div_dims.top + ($(loading_div).height() / 2) - 25, 'left':loading_div_dims.left + ($(loading_div).width() / 2) - 25});
	} else {
		$("div.loading").remove();
		$("img.loading").remove();
	}
}

function add_to_step () {
	var data_rows = $('table#quantities tr.quantity_row');
	var row_color,row_color_id,current_row,row_sizes,counter,size_label,current_col,colors = new Array(),data = '';
	var product_id = $('div#selector div.color_holder').attr('pid');
	var total_count = parseInt($('span#total_quantity_span').text());
	var logo_colors_f = parseInt($('select#number_of_colors').val());
	var logo_colors_b = parseInt($('select#number_of_colors_back').val());
	
	if($('#radio input:radio:checked').val() == 1) var design_type = 1;
	else var design_type = 2;
	
	$(data_rows).each(function(){
		current_row = $(this);
		row_color_id = $(current_row).children("td:eq(0)").children("div.color_holder").attr('color_id');
		row_color = $(current_row).children("td:eq(0)").children("div.color_holder").attr('color');
		row_sizes = $(current_row).children("td").not(':first-child').not(':last-child');
		counter = 0;
		$(row_sizes).each(function(){
			current_col = $(this);
			
			if(parseInt($(current_col).text()) > 0){
				size_label = $("th.size_header").eq(counter).text();
				data += "colors["+row_color_id+"]["+size_label+"]="+$(this).text()+"&";
			}
			counter++;
		});
	});
	
	$("input#proceed_to_design").attr('disabled','disabled');
	show_table_loading(false);
	show_table_loading(true);

	if (total_count < 12) {
		show_table_loading(false);
		$("input#proceed_to_design").removeAttr('disabled');
		alert('You need to enter at least a total of 12 t-shirts!');
	} else {
		$.ajax({
			type: "POST",
			url: "ajax_processes/add_step_to_session.ajax.php",
			data: 'pid='+product_id+'&logo_colors_f='+logo_colors_f+'&logo_colors_b='+logo_colors_b+'&designtype='+design_type+'&'+data,
			success: function(result){
				//alert(result)
				/*$("span#total_prices").html('');
				$("div#messages").remove();
				$("div.product_details").prepend("<div id='messages' class='success'><ul><li>The product is successfully added to your shopping basket. You can use the link at the top of the page to view the shopping basket.</li></ul></div>");
				show_table_loading(false);
				$("input#proceed_to_design").removeAttr('disabled');*/
				//window.location = '?page=product_designer';
				//================================================
				//new part
				//window.location = '?page=order_description';
				window.location = '?page=cart';
			}
		});
	}
}

function update_total_quantity(){
	var quantities_table = $('table#quantities');
	var total_quantity_span = $('span#total_quantity_span');
	var quantity_cols = $(quantities_table).children('tbody').children('tr').children('td');
	var current_value,total_quantity = 0;
	
	$(quantity_cols).each(function(){
		current_value = (isNaN(parseInt($(this).text())))? 0:parseInt($(this).text());
		total_quantity += current_value;
	});
	
	$(total_quantity_span).text(total_quantity);
}

function calculate_price() {
	show_table_loading(false);
	show_table_loading(true);	
	
	if($('#radio input:radio:checked').val() == 1) var design_type = 1;
	else var design_type = 2;
	
	//alert(design_type);
	var design = parseInt($('span#total_quantity_span').text());
	var total_quantity = parseInt($('span#total_quantity_span').text());
	var logo_colors_f = parseInt($('select#number_of_colors').val());
	var logo_colors_b = parseInt($('select#number_of_colors_back').val());
	var number_cols = $('td.has_value');
	var numbers = new Array(),size,quantities = '',sizes = '';
	var product_id = $('div#selector div.color_holder').attr('pid');
	//alert("design: " + design + "\ntotal_quantity: " + total_quantity + "\nlogo_colors_f: " + logo_colors_f + "\nlogo_colors_b: " + logo_colors_b + "\nnumber_cols: " + number_cols + "\nproduct_id: " + product_id);
	
	$(number_cols).each(function(){
		size = $(this).attr('size');
		(numbers[size] != undefined)?
			numbers[size] += parseInt($(this).text()):
			numbers[size] = parseInt($(this).text());
	});
	
	for(size in numbers){
		sizes += size+',';
		quantities += numbers[size]+',';
	}
	if(total_quantity < 12){
		show_table_loading(false);
		alert('You need to enter at least a total of 12 t-shirts!');
		return false;
	}	
	$.ajax({
		type: "POST",
		url: "ajax_processes/price_calc.ajax.php",
		data: 'pid='+product_id+"&logo_colors_f="+logo_colors_f+'&logo_colors_b='+logo_colors_b+'&quantity='+total_quantity+'&sizes='+sizes+'&quantities='+quantities+'&designtype='+design_type,
		dataType: 'xml',
		success: function(result){
			show_table_loading(false);
			var each_price = 'Each Quantity Price:$'+$(result).find('eachqtyprice').text();
			$('span#each_qty_price').html(each_price);
			var prices = 'Total: $'+$(result).find('total').text();
			$('span#total_prices').html(prices);
		}
	});
}
