//$(document).ready(loadAjax,initDataTable);
$(document).ready(loadAjax);



function loadAjax() {

	if ($("#dt_table").size() == 1) loadDataTable(); //check if a table set up for DataTables exists

	setBehavior();
		
	initButtonActions(); //email, print

} //loadAjax

function setBehavior() { //sets behavior of several components
	
	
	initTooltip();

	initQuoteActions(); //sets preventDefault on add/update/remove links

	initProdTable();

	setCheckboxesSettings();
	setDiscount();
}

function loadDataTable() {
	var colCount = $("#dt_table th").length;
	var ultim = colCount - 1;
	var penultim = ultim - 1;
	var aoColumnsArr = 	new Array( {"bSortable": false, "bSearchable": false }, null, null, { "bVisible":false, "bSortable": true, "bSearchable": false },	{"sType":"currency"} );

	for (var i = 0; i < colCount - 5; i++ )
		aoColumnsArr.push({"sType":"currency"});
	aoColumnsArr[penultim] = { "bSortable": false, "bSearchable": false };
	aoColumnsArr[ultim] = { "bSortable": false, "bSearchable": false };

	dtCurrencySortPlugin();
	dtCurrencyPlugin();

	$("#dt_table").dataTable( {
		"oLanguage": {
			"sLengthMenu": "Display _MENU_ products per page",
			"sZeroRecords": "No products found - sorry",
			"sInfo": "Showing _START_ - _END_ of _TOTAL_ products",
			"sInfoEmtpy": "Showing 0 - 0 of 0 products",
			"sInfoFiltered": "(filtered from _MAX_ total products)",
			"sSearch": "Search:"},
		"sPaginationType":"full_numbers",
		"sDom": '<"top"fl>rt<"bottom"ip<"clear">',
		"aaSorting": [[ 3, "asc" ]],
		"aoColumns": aoColumnsArr,
		"fnDrawCallback": function() {
			setBehavior();
		}
	});
}

function initButtonActions() {
	$("#email_quote_button").click(function(event){
		event.preventDefault();
		f_open_popup("email.php?a=e",1000,1000);
	});
	$("#print_quote_button").click(function(event){
		event.preventDefault();
		f_open_popup("print.php?a=p",1000,1000);
	});
	$("input#print").click(function(event){
		f_print();
	});
}

function f_open_popup(what,width,height) {
	window.open("/reps/"+what,"Info","width="+width+", height="+height+", toolbar=no, scrollbars=yes, resizable=no, menubar=no, status=no, directories=no, location=no, screenX=200, left=350, screenY=60, top=150"); 
}

function f_print() {
	window.print();
}


function f_add_to_quote(prod_id,qty){
	$.get("../../reps/quote_process.php", { action:"add", prod_id:prod_id, qty:qty},
		function(data) {
			$("#msg_"+prod_id).append("<div>added</div>").css({"color":"red","font-size":"10px","font-weight":"bold"});
			$("#msg_"+prod_id+" div").fadeOut(2000);
			$("#quote").html(data);
			initQuoteActions();
			initButtonActions();
		}
	);
}
function f_remove_from_quote(prod_id){
	$(".action",this).click(function(event){event.preventDefault()});
	
	if (confirm("Are you sure you want to remove this item?")) {
		$.get("../../reps/quote_process.php", { action:"remove", prod_id:prod_id}, 
			function(data) { 
	//			$("#quote").html(data);
				$("#quote #tr_"+prod_id).remove();
				$("#quote a span.quote strong").html($("#quote tr").length);
				if ($("#quote tr").length <= 0)
					$("#quote").html("");
				initQuoteActions();
				initButtonActions();
			}
		);
	
		if ($("#quote_product_list").size() == 1)
			$.get("../../reps/quote_data.php",
				function(data) { 
					$("#quote_product_list").html(data); 
					initQuoteActions();
					initButtonActions();
				}
			);
	}
}
function f_update_quote(prod_id,qty){
	$.get("../../reps/quote_process.php", { action:"update", prod_id:prod_id, qty:qty},
		function(data) {
			$("#quote").html(data);
			initQuoteActions();
			initButtonActions();
		});
	$.get("../../reps/quote_data.php", { },
		function(data) {
			$("#quote_product_list").html(data);
			initQuoteActions();
			initButtonActions();
		});
}

function initTooltip() {
	$("a.sku").mousemove(function(event){
		event.preventDefault();
		var pos = $(this).parent().offset();
		var height = $(this).parent().height(); //height of td
		var outerHeight = $(this).parent().outerHeight(); //outside height of td
		var width = $(this).parent().width(); //width of td
		var posTop = event.pageY-40; //gets top mouse position relative to current element
		var posLeft = event.pageX+10; //gets left mouse position relative to current element
//		var content = "<span>" + $(this).html() + " (" + event.pageX +","+ event.pageY + ")</span>";
		var content = $(this).html() + " (" + event.pageX +","+ event.pageY + ")";
//		var content = event.pageX +","+ event.pageY;
//		var content = $(this).attr("id"); //gets the value of the id attribute of the <a> tag
//		$("#tooltip").css("top",posTop).css("left",posLeft).height(height).width(width).show().append("span").html(content);
		$("#tooltip").css("top",posTop).css("left",posLeft).fadeIn(150); // remove all size constraints
		$("#tooltip #txt").html(content); // remove all size constraints
		$("#tooltip #txt").css("-moz-opacity","1.0").css("opacity","1");
	});
	$("a.sku").mouseout(function(event){
		$("#tooltip").hide();
	});	
}

function initQuoteActions() {
	$("a.action ").click(function(event){
		event.preventDefault();
	});
}

function initProdTable() {
	$(".prod_table tr").hover(
		function(){ $(this).css("background-color","#FFC").css("cursor","default"); },
		function(){ $(this).css("background-color",""); }
	);
	$("#product_list .paginate_button").hover(
		function(){ $(this).css("background-color","#CCC").css("border","1px solid #666"); },
		function(){ $(this).css("background-color","#DDD").css("border","1px solid #AAA"); }									  
	);	
}

function setDiscount() {
	$("#save_discount").attr("disabled",true);
	$("#session_discount").keyup(function(event){$("#save_discount").attr("disabled",false);});
}
function setCheckboxesSettings() {
	$("#save_opt").attr("disabled",true);
	$("#show_list_web").click(function(){$("#save_opt").attr("disabled",false);});
	$("#show_list_email").click(function(){$("#save_opt").attr("disabled",false);});
	$("#show_discount_web").click(function(){$("#save_opt").attr("disabled",false);});
	$("#show_discount_email").click(function(){$("#save_opt").attr("disabled",false);});
	$("#show_cost_web").click(function(){$("#save_opt").attr("disabled",false);});
	$("#show_cost_email").click(function(){$("#save_opt").attr("disabled",false);});

}

function dtCurrencyPlugin() {
	jQuery.fn.dataTableExt.aTypes.push(  
		function ( sData )  
		{  
			var sValidChars = "0123456789.-,";  
			var Char;  
			  
			/* Check the numeric part */  
			for ( i=1 ; i<sData.length ; i++ )   
			{   
				Char = sData.charAt(i);   
				if (sValidChars.indexOf(Char) == -1)   
				{  
					return null;  
				}  
			}  
			  
			/* Check prefixed by currency */  
			if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' )  
			{  
				return 'currency';  
			}  
			return null;  
		}  
	);	
}

function dtCurrencySortPlugin() {
	jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) {
		/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
		var x = a == "-" ? 0 : a.replace( /,/g, "" );
		var y = b == "-" ? 0 : b.replace( /,/g, "" );
		
		/* Remove the currency sign */
		x = x.substring( 1 );
		y = y.substring( 1 );
		
		/* Parse and return */
		x = parseFloat( x );
		y = parseFloat( y );
		return x - y;
	};
	
	jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) {
		/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
		var x = a == "-" ? 0 : a.replace( /,/g, "" );
		var y = b == "-" ? 0 : b.replace( /,/g, "" );
		
		/* Remove the currency sign */
		x = x.substring( 1 );
		y = y.substring( 1 );
		
		/* Parse and return */
		x = parseFloat( x );
		y = parseFloat( y );
		return y - x;
	};	
}
