$(document).ready(doStuff);



function doStuff() {

	if ($("#dt_table").size() == 1) loadDataTable(); //check if a table set up for DataTables exists

	setBehavior();
		
	clickHandler();
	
} //loadAjax

function setBehavior() { //sets behavior of several components
	
	initTooltip();

	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 clickHandler() {
	$("body").click(function(event){
		var target = $(event.target);
	
		//a
		if (target.is("a")) {
			if (target.hasClass("update_quote")) { event.preventDefault(); updateQuote(target); }
			if (target.hasClass("remove_from_quote")) { event.preventDefault(); removeFromQuote(target); }
			if (target.hasClass("add_showroom_popup")) { event.preventDefault(); addShowroomPopup(); }
			if (target.hasClass("del_showroom")) { event.preventDefault(); delShowroom(target); }
			if (target.hasClass("edit_showroom")) { event.preventDefault(); editShowroomPopup(target); }
			if (target.parent().hasClass("wtb_popup_bar")) { event.preventDefault(); closeAddShowroomPopup(); }
			if (target.attr("id") == "email_quote_button") { event.preventDefault(); f_open_popup("email.php?a=e",1000,1000); }
			if (target.attr("id") == "print_quote_button") { event.preventDefault(); f_print(); }
		}
		
		//input
		if (target.is("input")) {
			if (target.hasClass("add_to_quote")) { addToQuote(target); }
			if (target.attr("id") == "add_showroom_butt") addShowroom();
			if (target.attr("id") == "save_showroom_butt") saveShowroom();
			if (target.attr("id") == "copy_info") copyInfoRegistration();
		}

		//img
		if (target.is("img")) {
			if (target.parent().hasClass("remove_from_quote")) { event.preventDefault(); removeFromQuote(target); }
			if (target.parent().attr("id") == "email_quote_button") { event.preventDefault(); f_open_popup("email.php?a=e",1000,1000); }
			if (target.parent().attr("id") == "print_quote_button") { event.preventDefault(); f_print(); }
		}

	});
} //clickHandler


function f_open_popup(what,width,height) {
	window.open("/partners/"+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 addToQuote(target) {

		var prodId = target.attr("id").substr("add_to_quote_".length);
		var prodQty = $("#qty_"+prodId).val();
		target.attr("disabled","disabled").val("adding...");
		
		$.ajax({
			type: "GET",
			url: "../../partners/quote_process.php",
			data: "action=add&prod_id="+prodId+"&qty="+prodQty,
			dataType: "text",
			success: function(data){
				$("#quote").html(data);
				target.attr("disabled","").val("add");
			}
		}); // end $.ajax

} //addToQuote

function updateQuote(target) {

	var prodId = target.attr("id").substr("update_quote_".length);
	var prodQty = $("#qty_"+prodId).val();
	target.parent().html("updating...");

	$.ajax({
		type: "GET",
		url: "../../partners/quote_process.php",
		data: "action=update&prod_id="+prodId+"&qty="+prodQty,
		dataType: "text",
		success: function(data){
			$("#quote").html(data);
			target.html("update");
		}
	}); // end $.ajax

	$.ajax({
		type: "GET",
		url: "../../partners/quote_data.php",
		success: function(data){
			$("#quote_product_list").html(data);
		}
	}); // end $.ajax

} //updateQuote

function removeFromQuote(target) {

			if (confirm("Are you sure you want to remove this item?")) {
				if (target.is("a"))
					var prodId = target.attr("id").substr("remove_from_quote_".length);
				else if (target.is("img"))
					var prodId = target.parent().attr("id").substr("remove_from_quote_".length);
				var prodQty = $("#qty_"+prodId).val();

				if (target.is("a"))
					target.parent().html("removing...");
				
				$.ajax({
					type: "GET",
					url: "../../partners/quote_process.php",
					data: "action=remove&prod_id="+prodId,
					dataType: "text",
					success: function(data){
						$("#quote").html(data);

					}
				}); // end $.ajax
	
				if ($("#quote_product_list").size() == 1) {
					$.ajax({
						type: "GET",
						url: "../../partners/quote_data.php",
						success: function(data){
							$("#quote_product_list").html(data);
						}
					}); // end $.ajax
				}
			} //if (confirm("Are you sure you want to remove this item?")) {

} //removeFromQuote

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 addShowroomPopup() {
	$("#modal_background").toggle();
	$("#wtb_popup_add").html("loading...").toggle();
	$.ajax({
		type: "GET",
		url: "../../partners/admin/add_showroom.php",
		data: "",
		dataType: "text",
		success: function(data){
			$("#wtb_popup_add").html(data);
			var popupPosition = popupBoxPosition("#wtb_popup_add");
			var popupLeft = popupPosition[0];
			var popupTop = popupPosition[1];
			$("#wtb_popup_add").css({"left":popupLeft,"top":popupTop});
			var countryId = $("#wtb_country_id").val();
			if (countryId == 1 || countryId == 2)
				$("#wtb_country_name").parent().parent().hide();
			wtbStateId();
		}
	}); // end $.ajax
} //addShowroomPopup

function editShowroomPopup(target) {
	var wtbId = target.attr("id").substr("edit_showroom_".length);
	$("#modal_background").css("display","block");
	$("#wtb_popup_edit").html("loading...").show();
	$.ajax({
		type: "GET",
		url: "../../partners/admin/edit_showroom.php",
		data: "wtb_id="+wtbId,
		dataType: "text",
		success: function(data){
			$("#wtb_popup_edit").html(data);
			var popupPosition = popupBoxPosition("#wtb_popup_edit");
			var popupLeft = popupPosition[0];
			var popupTop = popupPosition[1];
			$("#wtb_popup_edit").css({"left":popupLeft,"top":popupTop});
			var countryId = $("#wtb_country_id").val();
			if (countryId == 1 || countryId == 2)
				$("#wtb_country_name").parent().parent().hide();
			wtbStateId();
		}
	}); // end $.ajax
} //editShowroomPopup

function closeAddShowroomPopup() {
	$(".wtb_popup").hide();
	$("#modal_background").hide();
} //closeAddShowroomPopup

function wtbStateId() {
	$("#wtb_country_id").change(function(event){
		var countryId = $(this).val();
		var $countryNameTR = $("#wtb_country_name").parent().parent();
		if (countryId == 1 || countryId == 2) {
			$("#wtb_country_name").val("");
			$countryNameTR.hide();
		}
		if (countryId == 9999)
			$countryNameTR.show();
	});
} //wtbStateId

function addShowroom() {
	var wtbCompany = $("#wtb_company").val();
	var wtbAddress = $("#wtb_address").val();
	var wtbCity = $("#wtb_city").val();
	var wtbState = $("#state_id").val();
	var wtbZip = $("#wtb_zip").val();
	var wtbCountryId = $("#wtb_country_id").val();
	var wtbCountryName = $("#wtb_country_name").val();
	var wtbPhone = $("#wtb_phone").val();
	var wtbFax = $("#wtb_fax").val();
	var wtbWebsite = $("#wtb_website").val();
	var wtbEmail = $("#wtb_email").val();
	var wtbContact = $("#wtb_contact").val();
	
	$("#add_showroom_butt").attr("disabled","disabled").val("adding...");
	
	$.ajax({
		type: "GET",
		url: "../../partners/admin/wtb_ops.php",
		data: "action=add_showroom&wtb_company="+wtbCompany+"&wtb_address="+wtbAddress+"&wtb_city="+wtbCity+"&state_id="+wtbState+"&wtb_zip="+wtbZip+"&wtb_country_id="+wtbCountryId+"&wtb_country_name="+wtbCountryName+"&wtb_phone="+wtbPhone+"&wtb_fax="+wtbFax+"&wtb_website="+wtbWebsite+"&wtb_email="+wtbEmail+"&wtb_contact="+wtbContact,
		dataType: "text",
		success: function(data){
			if ($("#wtb_table_div table").size() == 1) {
				//do nothing
			} else {
				var str = "<table cellpadding='0' cellspacing='0' border='0' class='display wtb_table'>";
						str += "<thead>";
							str += "<th>Company</th>";
							str += "<th><div>City /</div><div>State</div></th>";
							str += "<th>Address</th>";
							str += "<th><div>Phone /</div><div>Fax</div></th>";
							str += "<th>Web</th>";
							str += "<th>Country</th>";
							str += "<th>&nbsp;</th>";
						str += "</thead>";
						str += "<tbody>";
						str += "</tbody>";
					str += "</table>";
				$("#wtb_table_div").html(str);
			}
			$("#wtb_table_div table tbody").append(data);
			$("#modal_background").hide();
			$(".wtb_popup").hide();
		}
	}); // end $.ajax

} //addShowroom

function saveShowroom() {
	var wtbId = $("#wtb_id").val();
	var wtbCompany = escape($("#wtb_company").val());
	var wtbAddress = $("#wtb_address").val();
	var wtbCity = $("#wtb_city").val();
	var wtbState = $("#state_id").val();
	var wtbZip = $("#wtb_zip").val();
	var wtbCountryId = $("#wtb_country_id").val();
	var wtbCountryName = $("#wtb_country_name").val();
	var wtbPhone = $("#wtb_phone").val();
	var wtbFax = $("#wtb_fax").val();
	var wtbWebsite = $("#wtb_website").val();
	var wtbEmail = $("#wtb_email").val();
	var wtbContact = $("#wtb_contact").val();
	
	$("#save_showroom_butt").attr("disabled","disabled").val("saving...");
	
	$.ajax({
		type: "GET",
		url: "../../partners/admin/wtb_ops.php",
		data: "action=save_showroom&wtb_id="+wtbId+"&wtb_company="+wtbCompany+"&wtb_address="+wtbAddress+"&wtb_city="+wtbCity+"&state_id="+wtbState+"&wtb_zip="+wtbZip+"&wtb_country_id="+wtbCountryId+"&wtb_country_name="+wtbCountryName+"&wtb_phone="+wtbPhone+"&wtb_fax="+wtbFax+"&wtb_website="+wtbWebsite+"&wtb_email="+wtbEmail+"&wtb_contact="+wtbContact,
		dataType: "text",
		success: function(data){
			if (data) {
				var $tr = $("#wtb_tr_"+wtbId);
				$tr.replaceWith(data);
			}
			$("#modal_background").hide();
			$(".wtb_popup").hide();
		}
	}); // end $.ajax

} //editShowroom

function delShowroom(target) {
	var wtbId = target.attr("id").substr("del_showroom_".length);
	var $td = target.closest("td");
	var $tr = $td.parent();
	var $table = $tr.parent().parent();
	if (confirm("Really delete?")) {
		$td.html("deleting...");
		$.ajax({
			type: "GET",
			url: "../../partners/admin/wtb_ops.php",
			data: "action=del_showroom&wtb_id="+wtbId,
			dataType: "text",
			success: function(data){
				if (data) {
					$tr.remove();
					var rowCount = $("tr",$table).length;
					if (rowCount == 0)
						$table.replaceWith("<h2 id='no_wtb'>There are no showrooms</h2>");
				} else {
					
				}
			}
		}); // end $.ajax
	} //	if (confirm("Really delete?")) {
} //delShowroom

function copyInfoRegistration() {
	$("#cust_ship_first_name").val($("#cust_first_name").val());
	$("#cust_ship_last_name").val($("#cust_last_name").val());
	$("#cust_ship_address1").val($("#cust_address1").val());
	$("#cust_ship_city").val($("#cust_city").val());
	$("#cust_ship_state_id").val($("#state_id").val());
	$("#cust_ship_zip").val($("#cust_zip1_us").val());
} //copyInfoRegistration

/* ============================================================================================================================== */
function browserWidth() {
	return window.innerWidth != null ? window.innerWidth: document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth:document.body != null ? document.body.clientWidth:null;
}
function browserHeight() {
	return window.innerHeight != null? window.innerHeight: document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight:document.body != null? document.body.clientHeight:null;
}
function popupBoxPosition(divName) {
	var browser_w = browserWidth();
	var browser_h = browserHeight();
	var box_w = $(divName).outerWidth();
	var box_h = $(divName).outerHeight();
	var scroll_top = $("body").scrollTop();
	var left = Math.round((browser_w - box_w) / 2);
	var top = Math.round((browser_h - box_h) / 2) + scroll_top;
	var position = new Array(left,top);
	return position;
}


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;
	};	
}

