Shadowbox.init();

var products = [
	'colored-metal-building-components',
	'miscellaneous',
	'metal-building-components',
	'expanded-metal',
	'angles',
	'square-tubing',
	'tubing'
];
var processing = [
	'plate-processing',
	'beam-cambering',
	'angle-rolling',
	'beam-cutting',
	'plate-burning',
	'plate-burning-2',
	'slitting',
	'strip-production'
];
var locationTitles = [];
locationTitles['SLC'] = 'Salt Lake City';
locationTitles['CLS'] = 'Southern California';
locationTitles['HOU'] = 'Houston';
locationTitles['JV2'] = 'Houston';
locationTitles['XPC'] = 'Houston';
locationTitles['SAN'] = 'San Antonio';
locationTitles['IRV'] = 'Houston';
locationTitles['DEN'] = 'Denver';
locationTitles['KNX'] = 'Knoxville';
locationTitles['UTS'] = 'Salt Lake City';
locationTitles['WLY'] = ' Houston';
var imageRotateTimer = null;
var canvasesTimer = null;

function setupCanvases(duration) {
	
	if (duration == undefined) {
		duration = 5000;
	}
	
	clearTimeout(canvasesTimer);
	
	canvasesTimer = setTimeout('rotateCanvases()', duration);
}

function rotateCanvases() {
	
	var element = $('#canvas-container div');
	var next = +$(element).attr('rel') + 1;
	
	if (next >= canvases[Param_lang].length) {
		next = 0;
	}
	
	$(element).fadeOut(
		250,
		function() {
			$(this).children('h1').html(canvases[Param_lang][next].a);
			Cufon.refresh();
			$(this).attr('title', canvases[Param_lang][next].a.replace(/<br \/>/gi, ' ')).attr('class', canvases[Param_lang][next].b).attr('rel', next).fadeIn(250);
		}
	);
	
	setupCanvases();
}

function setupImages(duration) {
	
	if (duration == undefined) {
		duration = 2500;
	}
	
	clearTimeout(imageRotateTimer);
	
	imageRotateTimer = setTimeout('rotateImages()', duration);
}

function rotateImages() {
	
	var type = $('#image-rotate').attr('class');
	var images = eval(type);
	
	var element = $('#image-rotate').find('img');
	var next = +$(element).attr('rel') + 1;
	
	if (next >= images.length) {
		next = 0;
	}
	
	var text = generateImageCaption(images[next]);
	
	$(element).fadeOut(
		250,
		function() {
			$(this).closest('#image-rotate').find('p').text(text);
			$(this).attr('alt', text).attr('src', Path_skin + '/images/' + type + '/' + images[next] + '.jpg').fadeIn(250).attr('rel', next);
		}
	);
	
	setupImages();
}

function generateImageCaption(text) {
	
	var words = text.split('-');
	var text = new Array;
	
	for (var i = 0; i < words.length; i++) {
		
		text[i] = (words[i].charAt(0).toUpperCase() + words[i].substr(1));
	}
	
	return text.join(' ');
}

function loadValueSteel(start, per, pageturn) {
	
	updateCart();
	
	if (start == '' || start == null) start = 0;
	if (per == '' || per == null) per = 25;
	if (pageturn == '' || pageturn == null) pageturn = false;
	
	if (pageturn) {
		
		$('table tbody tr').hide();
		$('table tbody tr').slice(start, parseInt((start * 1) + (per * 1))).show();
	}
	else {
		
		$('#value-steel-data').html(
			'<tr>' +
				'<td colspan="10" align="center">' +
					'<img src="' + Path_skin + '/images/loading.gif" width="220" height="19" alt="Loading" />' +
				'</td>' +
			'</tr>'
		);
		
		$('.sort-column').attr('disabled', 'disabled');
		
		var url = Path_site + '/value-steel-data';
		var json = null;
		var where = {};
		var params = new Array;
		
		$('.sort-column').each(
			function(i, col) {
				if ($(this).val() != '' && $(this).val() != null) {
					eval('where.' + $(this).attr('name') + ' = \'' + $(this).val() + '\'');
				}
			}
		);
		
		for (key in where) {
			params.push(key + ':' + eval('where.' + key));
		}
		
		where = params.join(',');
		
		if (where != '') {
			where = '?where=' + where;
		}
		
		$.getJSON(
			url + where,
			function(json) {
				
				var total = json.total;
				var pages = total / per;
				
				if (String(pages).split('.').length > 1) {
					var pages = Math.floor(pages) + 1;
				}
				
				$('.pagination').html('Page');
				
				if (pages != 1) {
					$('.pagination').append('s');
				}
				
				$('.pagination').append(': ');
				
				$('.pagination').append('<a href="#" class="prev-page">&laquo;</a> ');
				
				for (var i = 0; i < pages; i++) {
					
					var pageStart = parseInt(per * i);
					var selected = (pageStart == start) ? ' selected' : '';
					
					$('.pagination').append(
						'<a href="' + pageStart + '" class="change-page' + selected + '">' +
							parseInt(i + 1) +
						'</a> '
					);
				}
				
				$('.pagination').append('<a href="#" class="next-page">&raquo;</a>');
				
				getOptions('type', json.type);
				getOptions('thickness', json.thickness);
				getOptions('location', json.location);
				getOptions('grade', json.grade);
				
				$('#value-steel-data').find('tr').remove();
				
				if (json.data.length == 0) {
					
					$('#value-steel-data').append(
						'<tr>' +
							'<td colspan="10" align="center">' +
								'No results' + 
							'</td>' +
						'</tr>'
					);
					
					$('.pagination').html('Pages: 0');
				}
				else {
					
					for (i in json.data) {
						
						var row = json.data[i];
						var selected = (row.incart == 'true') ? ' class="selected"' : '';
						
						if (row.id == undefined) continue;
						
						$('#value-steel-data').append(
							'<tr valign="top"' + selected + '>' +
								'<td align="center">' +
									'<a href="#" rel="' + row.id + '" class="add-row"><img src="' + Path_skin + '/images/icons/plus.gif" border="0" width="14" height="14" alt="Add Item" /></a>' +
									'<a href="#" rel="' + row.id + '" class="remove-row"><img src="' + Path_skin + '/images/icons/minus.gif" border="0" width="14" height="14" alt="Remove Item" /></a>' +
								'</td>' +
								'<td nowrap="nowrap">' + row.type + '&nbsp;</td>' +
								'<td nowrap="nowrap">' + row.grade + '&nbsp;</td>' +
								'<td nowrap="nowrap">' + row.thickness + '&nbsp;</td>' +
								'<td nowrap="nowrap">' + row.width + '&nbsp;</td>' +
								'<td nowrap="nowrap">' + row.length + '&nbsp;</td>' +
								'<td nowrap="nowrap">' + row.pcs + '&nbsp;</td>' +
								'<td nowrap="nowrap">' + row.ext_wt + '&nbsp;</td>' +
								'<td>' + row.remark + '&nbsp;</td>' +
								'<td nowrap="nowrap">' + row.location + '&nbsp;</td>' +
							'</tr>'
						);
					}
					
					$('table tbody tr').hide();
					$('table tbody tr').slice(start, parseInt((start * 1) + (per * 1))).show();
				}
				
				$('.sort-column').removeAttr('disabled');
			}
		);
	}
}

function getOptions(column, values) {
	
	var selectElement = $('#' + column);
	var options = new Array();
	
	for (i in values) {
		
		if (values[i] == null || values[i] == '') continue;
		
		options[i] = '<option value="' + escape(values[i]) + '"';
		
		if (selectElement.val() == escape(values[i])) {
			options[i] += ' selected="selected"';
		}
		
		options[i] += '>' + values[i];
		
		if (column == 'location' && locationTitles[values[i]] != undefined) {
			options[i] += ' - '+ locationTitles[values[i]];
		}
		
		options[i] += '</option>';
	}
	
	selectElement.html('<option value="">All</option>' + options.join(''));
}

function updateCart() {
	
	$.get(
		Path_site + '/value-steel-cart',
		function(data) {
			
			$('#cart-amount').html(data + ' Item');
			
			if (data != 1) {
				$('#cart-amount').append('s');
			}
			
			if (data == 0) {
				$('.checkout, .empty-cart').hide();
			}
			else {
				$('.checkout, .empty-cart').show();
			}
		}
	);
}

function generateMap(location, content, title) {
	
	location = location.split(',');
	
	var mapLatlng = new google.maps.LatLng(location[0], location[1]);
	
	var mapOptions = {
		zoom: 16,
		center: mapLatlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	
	var map = new google.maps.Map(
		document.getElementById('map'),
		mapOptions
	);
	
	var mapInfo = '<div id="map-info">' + content + '</div>';
	
	var infowindow = new google.maps.InfoWindow({
		content: mapInfo
	});
	
	var marker = new google.maps.Marker({
		position: mapLatlng,
		map: map,
		title: title
	});
	
	infowindow.open(map, marker);
	
	google.maps.event.addListener(marker, 'click', function() {
		infowindow.open(map,marker);
	});
}

$(document).ready(
	function() {
		
		$('#navigation li').hover(
			function() {
				$(this).toggleClass('hover');
			}
		);
		
		if ($('#canvas-container').length == 1 && canvases[Param_lang].length > 1) {
			setupCanvases();
		}
		
		if ($('#image-rotate').length == 1) {
			setupImages();
		}
		
		$('#upload').change(
			function() {
				 $('#fake-upload-field').val($(this).val());
			}
		);
		
		$('.map-link').click(
			function() {
				
				var width = 640;
				var height = 480;
				var content = $(this).closest('p').clone();
				var title = $('strong', content);
				var location = $(this).attr('rel');
				
				title = title.html().split('<br>');
				title = title[0] + ' - ' + title[1]; 
				
				$('.map-link', content).remove();
				content = '<p>' + $.trim(content.html().replace(/\|/gi, '')) + '</p>';
				
				Shadowbox.open({
					content: '<div id="map" style="width: ' + width + 'px; height: ' + height + 'px;"></div>',
					player: 'html',
					title: title,
					width: width,
					height: height,
					options: {
						onFinish: function() {
							generateMap(location, content, title);
						}
					}
				});
				
				return false;
			}
		);
		
		if ($('#value-steel').length > 0) {
			
			$('.remove-cart-item').click(
				function() {
					
					var element = $(this);
					var removeID = $(element).attr('rel');
					
					$.get(
						Path_site + '/value-steel-remove',
						{
							id: removeID
						},
						function() {
							
							if ($(element).parents('tbody').find('tr').length > 1) {
								$(element).parents('tr').remove();
							}
							else {
								window.location = Path_site + '/value-steel';
							}
						}
					);
					
					return false;
				}
			);
			
			$('.amount-select, .price-field').change(
				function() {
					
					if ($(this).val() == null || $(this).val() == '') {
						$(this).val('0.00');
					}
					
					var rowID = $(this).parents('tr').attr('rel');
					
					var row = {
						'id': rowID
					}
					
					row.cwt = $('#cwt-' + row.id).val()
					row.weight = $('#weight-' + row.id).val(),
					row.pieces = $('#pieces-' + row.id).val(),
					row.price = $('#price-' + row.id).val()
					
					$('#price-' + row.id).val((row.price * 1).toFixed(2));
					
					row.totalWeight = (row.weight * row.pieces).toFixed(2);
					row.totalPrice = (row.pieces * row.cwt * row.price).toFixed(2);
					
					$('#total-weight-' + row.id + '-display').html(row.totalWeight + ' lbs');
					$('#total-price-' + row.id + '-display').html('$' + row.totalPrice);
					$('#total-weight-' + row.id).val(row.totalWeight);
					$('#total-price-' + row.id).val(row.totalPrice);
					
					var totalWeight = 0;
					var totalPrice = 0;
					
					$('#value-steel .weight').each(
						function() {
							totalWeight += ($(this).val() * 1);
						}
					);
					
					$('#value-steel .price').each(
						function() {
							totalPrice += ($(this).val() * 1);
						}
					);
					
					$('#final-weight-display').html(totalWeight.toFixed(2) + ' lbs');
					$('#final-price-display').html('$' + totalPrice.toFixed(2));
					$('#final-weight').val(totalWeight.toFixed(2));
					$('#final-price').val(totalPrice.toFixed(2));
					
					return false;
				}
			);
		}
		
		if ($('#value-steel-data').length > 0) {
			
			var perPage = 25;
			
			$('.sort-column').change(
				function() {
					
					loadValueSteel(0, perPage);
					
					return false;
				}
			);
			
			$('#search-form').click(
				function() {
					
					$('.sort-column').change();
					return false;
				}
			);
			
			$('#reset-form').click(
				function() {
					
					location.reload(true);
					
					return false;
				}
			);
			
			$('.prev-page').live(
				'click',
				function() {
					
					var prev = $('.change-page.selected').prev();
					
					if ($(prev).attr('class') != 'prev-page') {
						$(prev).click();
					}
					
					return false;
				}
			);
			
			$('.change-page').live(
				'click',
				function() {
					
					var id = $(this).attr('href');
					
					$('.pagination a').removeClass('selected');
					loadValueSteel(id, perPage, true);
					$('.pagination a[href=' + id + ']').addClass('selected');
					
					return false;
				}
			);
			
			$('.next-page').live(
				'click',
				function() {
					
					var next = $('.change-page.selected').next();
					
					if ($(next).attr('class') != 'next-page') {
						$(next).click();
					}
					
					return false;
				}
			);
			
			$('.add-row').live(
				'click',
				function() {
					
					var addID = $(this).attr('rel');
					
					$(this).siblings('.remove-row').show();
					$(this).closest('tr').addClass('selected');
					$(this).hide();
					
					$.get(
						Path_site + '/value-steel-add',
						{
							id: addID
						},
						function(data) {
							
							updateCart();
						}
					);
					
					return false;
				}
			);
			
			$('.remove-row').live(
				'click',
				function() {
					
					var removeID = $(this).attr('rel');
					
					$(this).siblings('.add-row').show();
					$(this).closest('tr').removeClass('selected');
					$(this).hide();
					
					$.get(
						Path_site + '/value-steel-remove',
						{
							id: removeID
						},
						function(data) {
							
							updateCart();
						}
					);
					
					return false;
				}
			);
			
			$('.empty-cart').live(
				'click',
				function() {
					
					$('tr.selected td a.remove-row').click();
					
					$.get(
						Path_site + '/value-steel-remove',
						function(data) {
							updateCart();
						}
					);
					
					return false;
				}
			);
			
			loadValueSteel(0, perPage);
		}
	}
);
