$(document).ready(function(){
	assign_row_click();

	
	if( $("#partEnquiryForm").length > 0 ){
		$("#partEnquiryForm").submit(function(e){
			var aSelected = new Array();
			aSelected = oTableList.fnGetNodes();
			if(aSelected.length < 1){
				alert("Please select at least one product");
				e.preventDefault();
			} else if ( $("#partEnquiryForm input#partEnquiryName").val() == "" ){
				alert("Please enter your Name");
				$("#partEnquiryForm input#partEnquiryName").focus();
				e.preventDefault();
			} else if ( $("#partEnquiryForm input#partEnquiryCompanyName").val() == "" ){
				alert("Please enter your Company Name");
				$("#partEnquiryForm input#partEnquiryCompanyName").focus();
				e.preventDefault();
			} else if ( $("#partEnquiryForm input#partEnquiryCountry").val() == "" ){
				alert("Please enter your Country");
				$("#partEnquiryForm input#partEnquiryCountry").focus();
				e.preventDefault();
			} else if ( $("#partEnquiryForm input#partEnquiryEmail").val() == "" ){
				alert("Please enter your Email Address");
				$("#partEnquiryForm input#partEnquiryEmail").focus();
				e.preventDefault();
			} else if ( !isValidEmailAddress($("#partEnquiryForm input#partEnquiryEmail").val()) ){
				alert("Please enter a valid Email Address");
				$("#partEnquiryForm input#partEnquiryEmail").focus();
				e.preventDefault();
			} else if ( $("#partEnquiryForm input#partEnquiryEmail").val() != $("#partEnquiryForm input#partEnquiryEmailConfirm").val() ){
				alert("Please check that your email addresses match");
				$("#partEnquiryForm input#partEnquiryEmailConfirm").focus();
				e.preventDefault();
			} else if ( !$("#partEnquiryForm input#partEnquiryQuote").attr('checked') && !$("#partEnquiryForm input#partEnquiryOrder").attr('checked') ){
				alert("Please indicate whether you want a quote or wish to order your products");
				$("#partEnquiryForm input#partEnquiryEmailQuote").focus();
				e.preventDefault();
			} else {
				//Success, Send form
				iPart = 0;
				$.each(aSelected, function(index, value){
					iPart++;
					var partNumber = $(value).children("td:eq(0)").html();
					var partQty = $(value).children("td:eq(2)").children("input").val();
					$("#partEnquiryForm").append("<input type='hidden' name='product_" + partNumber + "' value='" + partQty + "' />");
				});
			}
			
		});
	}
	
	if( $("#productEnquiryForm").length > 0 ){
		$("#productEnquiryForm").submit(function(e){
			var aSelected = new Array();
			aSelected = oQuoteTable.fnGetNodes();
			if(aSelected.length < 1){
				alert("Please select at least one product");
				e.preventDefault();
			} else if ( $("#productEnquiryForm input#productEnquiryName").val() == "" ){
				alert("Please enter your Name");
				$("#productEnquiryForm input#productEnquiryName").focus();
				e.preventDefault();
			} else if ( $("#productEnquiryForm input#productEnquiryCompanyName").val() == "" ){
				alert("Please enter your Company Name");
				$("#productEnquiryForm input#productEnquiryCompanyName").focus();
				e.preventDefault();
			} else if ( $("#productEnquiryForm input#productEnquiryCountry").val() == "" ){
				alert("Please enter your Country");
				$("#productEnquiryForm input#productEnquiryCountry").focus();
				e.preventDefault();
			} else if ( $("#productEnquiryForm input#productEnquiryEmail").val() == "" ){
				alert("Please enter your Email Address");
				$("#productEnquiryForm input#productEnquiryEmail").focus();
				e.preventDefault();
			} else if ( !isValidEmailAddress($("#productEnquiryForm input#productEnquiryEmail").val()) ){
				alert("Please enter a valid Email Address");
				$("#productEnquiryForm input#productEnquiryEmail").focus();
				e.preventDefault();
			} else if ( $("#productEnquiryForm input#productEnquiryEmail").val() != $("#productEnquiryForm input#productEnquiryEmailConfirm").val() ){
				alert("Please check that your email addresses match");
				$("#productEnquiryForm input#productEnquiryEmailConfirm").focus();
				e.preventDefault();
			} else {
				//Success, Send form
				iproduct = 0;
				$.each(aSelected, function(index, value){
					iproduct++;
					var productNumber = $(value).children("td:eq(0)").html();
					var productQty = $(value).children("td:eq(1)").children("input").val();
					$("#productEnquiryForm").append("<input type='hidden' name='product_" + productNumber + "' value='" + productQty + "' />");
				});
			}
			
		});
	}
	

	var oTableList = $("#partTableList").dataTable({
		"bPaginate": false,
		"bFilter": false,
		"oLanguage": {
			"sEmptyTable": "You have not selected any items"
		},
		
		"aoColumns": [
  			null,
  			null,
  			{
  				"bSearchable": false,
  				"bSortable": false,
  				"bVisible":    true
  			},
  			{
  				"bSearchable": false,
  				"bSortable": false,
  				"bVisible":    true
  			}
  		]
	});
	
	var oTable = $("#partTable").dataTable({
		"bProcessing": true,
		"bServerSide": true,
		"sAjaxSource": '../wp-content/themes/boldy/partTableData.php',
		
		"fnInitComplete": function() { assign_row_click(oTable, oTableList); },
		"fnInfoCallback": function() {
			assign_row_click(oTable, oTableList);
		},
		
		"bPaginate": true,
		"sPaginationType": "full_numbers",
		"bLengthChange": false,
		"bFilter": true,
		"bSort": true,
		"bInfo": true,
		"bAutoWidth": true,
		
		"aaSorting": [[ 1, "asc" ]],
		
		"aoColumns": [
			null,
			null,
			null,
			{
				"bSearchable": false,
				"bSortable": false,
				"bVisible":    true
			}
		]
	});
	
	var oManualTable = $("#manualTable").dataTable({
		"bProcessing": true,
		//"sAjaxSource": '../wp-content/themes/boldy/partTableData.php',
		
		//"fnInitComplete": function() { assign_row_click(oTable, oTableList); },
		//"fnInfoCallback": function() { assign_row_click(oTable, oTableList); },
		
		"bPaginate": true,
		"sPaginationType": "full_numbers",
		"bLengthChange": false,
		"bFilter": true,
		"bSort": true,
		"bInfo": true,
		"bAutoWidth": true,
		
		"aaSorting": [[ 1, "asc" ]],
		
		"aoColumns": [
		              null,
		              null,
		              {
		            	  "bSearchable": false,
		            	  "bSortable": false,
		            	  "bVisible":    true
		              }
		              ]
	});
	
	var oBrochureTable = $("#brochureTable").dataTable({
		"bProcessing": true,
		"bPaginate": true,
		"sPaginationType": "full_numbers",
		"bLengthChange": false,
		"bFilter": true,
		"bSort": true,
		"bInfo": true,
		"bAutoWidth": true,
		
		"aaSorting": [[ 1, "asc" ]],
		
		"aoColumns": [
		              null,
		              null,
		              {
		            	  "bSearchable": false,
		            	  "bSortable": false,
		            	  "bVisible":    true
		              }
		              ]
	});
	
	var oQuoteTable = $("#quoteTable").dataTable({
		"bProcessing": true,
		"bPaginate": true,
		"sPaginationType": "full_numbers",
		"bLengthChange": false,
		"bFilter": true,
		"bSort": true,
		"bInfo": true,
		"bAutoWidth": true,
		
		"aaSorting": [[ 0, "asc" ]],
		
		"aoColumns": [
		              null,
		              null,
		              {
		            	  "bSearchable": false,
		            	  "bSortable": false,
		            	  "bVisible":    true
		              }
		              ]
	});
	var oQuoteTableAdd = $("#quoteTableAdd").dataTable({
		"bProcessing": true,
		"bPaginate": true,
		"sPaginationType": "full_numbers",
		"bLengthChange": false,
		"bFilter": true,
		"bSort": true,
		"bInfo": true,
		"bAutoWidth": true,
		
		"aaSorting": [[ 0, "asc" ]],
		
		"aoColumns": [
		              null,
		              {
		            	  "bSearchable": false,
		            	  "bSortable": false,
		            	  "bVisible":    true
		              }
		              ]
	});
	
	/*$("a#checkSelected").click( function(event) {
		event.preventDefault();
		
		var aSelected = new Array();
		aSelected = fnGetSelected(oTable);
		alert(aSelected.length);
	});*/
	
	var qsParm = new Array();
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qsParm[key] = val;
		}
	}
	var brochureSearch = qsParm['brochure'];
	if( qsParm['brochure'] == '' ){
		var brochureSearch = qsParm['search'];
	}
	if( brochureSearch/length ){
		brochureSearch = brochureSearch.replace(/[^A-Za-z0-9_]/, '');
		$('#brochureTable_filter input').val( brochureSearch ).keyup();
	}
	
});

function assign_row_click(oTable, oTableList){
	//Remove previous Clicks
	$("#partTable tr").unbind();
	
	//Get Array of highlighted items
	var toHighlight = new Array();
	toHighlight[0] = 'arrayContainsHighlightedParts';
	var iHighlight = 0;
	$("#partTableList tbody").children('tr').each( function(){
		if( $(this).children(0).attr('class') != 'dataTables_empty' ){
			iHighlight++;
			toHighlight[iHighlight] = $(this).children(0).html();
		}
	});
	
	//Cycle through array and assign highlights
	$("#partTable tbody").children('tr').each( function(){
		if( $.inArray( $(this).children(0).html(), toHighlight ) > 0 ){
			$(this).addClass("row_selected");
			$(this).find("input").attr('checked', true);
		}
	});
	
	$("#partTable tr").click( function(e) {
		adding = true;
		if ( $(this).hasClass("row_selected") ){
			$(this).removeClass("row_selected");
			$(this).find("input").attr('checked', false);
			adding = false;
		} else {
			/*if(!e.ctrlKey) {
				var aReturn = new Array();
				var aTrs = oTable.fnGetNodes();
				for ( var i=0 ; i<aTrs.length ; i++ ){
					if ( $(aTrs[i]).hasClass('row_selected') ){
						$(aTrs[i]).removeClass("row_selected");
						$(aTrs[i]).find("input").attr('checked', false);
					}
				}
			}*/
			$(this).addClass("row_selected");
			$(this).find("input").attr('checked', true);
		}
		fnUpdateList(oTable, oTableList, this, adding);
	});
}

function fnGetSelected( oTableLocal ){
	var aReturn = new Array();
	var aTrs = oTableLocal.fnGetNodes();
	
	for ( var i=0 ; i<aTrs.length ; i++ ){
		if ( $(aTrs[i]).hasClass('row_selected') ){
			aReturn.push( aTrs[i] );
		}
	}
	return aReturn;
}

function fnUpdateList( oTableLocal, oTableListLocal, row, adding ){
	var aTrsList = oTableListLocal.fnGetNodes();
	
	if(adding){
		oTableListLocal.fnAddData([
			$( row ).children("td:eq(0)").html(),
			$( row ).children("td:eq(1)").html(),
	        "<input name='qty_" + $( row ).children("td:eq(0)").html() + "' value='1' />",
	        "<a href='#' class='deleteTableLink'>Delete</a>"
		]);
	} else {
		for ( var i=0 ; i<aTrsList.length ; i++ ){
			if( $(aTrsList[i]).children("td:eq(0)").html() == $(row).children("td:eq(0)").html() ){
				oTableListLocal.fnDeleteRow( aTrsList[i] );
			}
		}
	}
	reCheckLinks(oTableLocal, oTableListLocal);
}
function fnListDelete( oTableLocal, oTableListLocal, row ){
	var aTrs = oTableLocal.fnGetNodes();
	var aTrsList = oTableListLocal.fnGetNodes();
	
	for ( var i=0 ; i<aTrs.length ; i++ ){
		if( $(aTrs[i]).children("td:eq(0)").html() == $(row).parent().parent().children("td:eq(0)").html() ){
			$(aTrs[i]).removeClass("row_selected");
			$(aTrs[i]).find("input").attr('checked', false);
		}
	}
	for ( var i=0 ; i<aTrsList.length ; i++ ){
		if( $(aTrsList[i]).children("td:eq(0)").html() == $(row).parent().parent().children("td:eq(0)").html() ){
			oTableListLocal.fnDeleteRow( aTrsList[i] );
		}
	}
}

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function reCheckLinks(oTableLocal, oTableListLocal){
	$("#partTableList tbody tr td a.deleteTableLink").unbind();
	$("#partTableList tbody tr td a.deleteTableLink").click( function(e) {
		e.preventDefault();
		fnListDelete( oTableLocal, oTableListLocal, this );
		//oTableListLocal.fnDeleteRow();
	});
}
