CMW = window.CMW || {};
CMW.soal = CMW.soal || {}; 

CMW.soal.util= function(){
	var YuS = YAHOO.util.Selector;
	var YuDs = YAHOO.util.DataSource;
	var localeSettings = null;
	// Divisor used to break a number into groups of three characters
	var FORMAT_DIVISOR = 1000;
	var my = {
		// Provide locale specific settings.
		//     returns: an Object containing locale specific settings
		//     TODO - figure out how locale gets set
		getLocaleSettings : function () {
		    if (localeSettings == null) {
		        localeSettings = new Object();
		        localeSettings.currencyCharacter = "$";
		        localeSettings.thousandsSeparator = ",";
		    }
		    
		    return localeSettings;
		},

		// Make an integer from one of the table values. This function will return sensible results for things like 
		// null, empty string, and &nbsp;, as well as handling things like currency characters ($) and separators (comma).
		//     parameters:string - the string containing an integer value
		//     returns: the integer representation of the string
		makeInteger : function (string) {
		    if (string == null) {
		        return 0;
		    }
		
		    string = YAHOO.lang.trim(string);
		
		    if (string == "") {
		        return 0;
		    }
		    else if (string == "&nbsp;") {
		        return 0;
		    } else if (string.indexOf(".") != -1) {
			    return 0;
		    } else if (string.indexOf("-") != -1) {
			    return 0;
		    }
		
		    var integer = parseInt(string);
		
		    if (isNaN(integer)) {
		        return 0;
		    }
		
		    return integer;
		},

		// Figure out what the next three digits to display are in the point value we are currently formatting.
		//     parameters:currentValue - the value to be formatted (this value MUST be a positive integer)
		//     returns: a string of digits from 0 to 999
		formatDigits : function (currentValue) {
		    var lastGroup = currentValue < FORMAT_DIVISOR;
		    var digits = currentValue % FORMAT_DIVISOR;
		    var string = "";
		
		    // Make sure the number has leading zeroes if this is not the last group of three digits.
		
		    if (digits < 10 && !lastGroup) {
		        string = "00" + digits;
		    }
		    else if (digits < 100 && !lastGroup) {
		        string = "0" + digits;
		    }
		    else {
		        string = "" + digits;
		    }
		
		    return string;
		},

		// Format a points value for display.
		//     parameters:points - the points value to be formatted (this value MUST be a positive integer)
		//     returns: a string that can be displayed in the HTML
		formatPoints : function (points) {
		    // Nothing to do if points is less than 1000. Just convert it to a string.
		
		    if (points < FORMAT_DIVISOR) {
		        return points + "";
		    }
		    
		    var localeSettings = CMW.soal.util.getLocaleSettings();
		
		    // Add thousands separators
		    var currentValue = Math.floor(points / FORMAT_DIVISOR);
		    var displayValue = my.formatDigits(points);
		
		    do {
		        displayValue = my.formatDigits(currentValue) + localeSettings.thousandsSeparator + displayValue;
		        currentValue = Math.floor(currentValue / FORMAT_DIVISOR);
		    } while (currentValue > 0);
		
		
		    return displayValue;
		},
		createColDef : function(cols, tbl){
			var colDef = [];
			var tblLabels = YuS.query('tr th', tbl);
			for(i=0;i<cols.length;i++){
				if(cols[i].type != 'hidden'){
					colDef.push({key:cols[i].key,label: tblLabels[i].innerHTML,className:tblLabels[i].className,formatter:cols[i].type,sortable:cols[i].sort});
				}
			}
			return colDef;
		},
		createFieldDef : function(cols){
			var fieldDef = [];
			for(i=0;i<cols.length;i++){
				if(cols[i].parser){
					fieldDef.push({key:cols[i].key,parser:cols[i].parser});
				} else {
					fieldDef.push({key:cols[i].key});
				}
			}
			
			return fieldDef;
		},
		formatBoolean : function(elCell, oRecord, oColumn, oData) {
	        var bChecked = oData;
	        bChecked = (bChecked) ? " checked" : "";
	        elCell.innerHTML = "<input type=\"checkbox\"" + bChecked +
	                " disabled=\"disabled\" class=\"boolean\">";
	    },
    formatStatus : function(elCell, oRecord, oColumn, oData) {
			if(oData == 'Closed') {
				elCell.innerHTML = '<input type="checkbox" checked="checked" disabled="disabled" class="boolean"> '+ 'Done';
			} else {
				elCell.innerHTML = "";
			}
    },
	    
	    parseNumberFromCurrency : function(sString) {
	        // Remove dollar sign and make it a float
	        return parseFloat(sString.substring(1));
	    },
	    
	    sortOnHiddenKey : function(a, b, desc) {
		    // Deal with empty values
		    if(!YAHOO.lang.isValue(a)) {
		        return (!YAHOO.lang.isValue(b)) ? 0 : 1;
		    }
		    else if(!YAHOO.lang.isValue(b)) {
		        return -1;
		    }
		
		    // If values are equal, then compare by Column1
		    return comp(a.getData("hiddenKey"), b.getData("hiddenKey"), desc);
		},
		
	    getColumnDef : function(hdr, type, sort, parser){
	    	var item = new Object();
			item.key = hdr;
			item.type = (type == undefined ? 'text' : type);
			item.sort = (sort == undefined ? false : sort);
			if(parser != undefined) {
				item.parser = parser;
			} else {
				if(item.type == 'date'){
					item.parser = YuDs.parseDate;
				} else if(item.type == 'number') {
					item.parser = YuDs.parseNumber;
				} else if(item.type == 'hidden') {
					item.parser = null;
				} else {
					item.parser = YuDs.parseString;
				}
			}
			return item;
		}
	    
	};
	return my;
}();

/*Request Certificates*/
CMW.soal.RequestCerts = function() {
	var YuD = YAHOO.util.Dom;
	var YuE = YAHOO.util.Event;	
	
	// Define some constants for the columns in each item table
	var QUANTITY_COLUMN   = 0;
	var CERT_VALUE_COLUMN = 1;
	var POINTS_COLUMN     = 2;
	var TOTAL_COLUMN      = 3;
	// The <div> where the total cost of the order goes
	var ORDER_TOTAL_DIV_ID = "orderTotal";
	
	// Prefix on all the item table's ids
	var ITEM_TABLE_ID_PREFIX = "certTable";
	
	var my =  {	
		init: function() {
			my.calculateTable();
			CMW.ui.Quantity.initFields();
			var temp = YuD.get(ITEM_TABLE_ID_PREFIX);
			var temp2 = YuD.getElementsByClassName("i-quantity", "INPUT", ITEM_TABLE_ID_PREFIX);
			YuE.on(YuD.getElementsByClassName("i-quantity", "INPUT", ITEM_TABLE_ID_PREFIX), 'change', function(ev){
				var tar = YuE.getTarget(ev);
				if(tar.tagName == "INPUT") {
					my.calculateTable();
				}
			});
			
		},
		
		
		calculateTable : function() {
		    // Find the table from the tableName
		    var table = YuD.get(ITEM_TABLE_ID_PREFIX);
		    // Recalculate the table
		    var quantitySubtotal = 0;
		    var certValueSubtotal = 0;
		    var pointsSubtotal = 0;
		
		    for (var index = 1; index < table.rows.length - 1; index++) {
		        var currentRow = table.rows[index];
		        var quantityEl = YuD.getFirstChild(currentRow.cells[QUANTITY_COLUMN]);
		        var quantity = CMW.soal.util.makeInteger(quantityEl.value);
		        var pointsCol = currentRow.cells[POINTS_COLUMN];
		        var pointsPerCert = CMW.soal.util.makeInteger(pointsCol.innerHTML);
		        
		        if (quantity == 0) {
		            // The user has not chosen to order any of this particular item. Clear out this row
		            // and continue to the next row.
		            // not needed currentRow.cells[QUANTITY_COLUMN].firstChild.value = "0";
		            currentRow.cells[TOTAL_COLUMN].innerHTML = "0";
		
		            continue;
		        }
		
		        var points = quantity * pointsPerCert;
		
		        quantitySubtotal += quantity;
		        pointsSubtotal += points;
		        
		        currentRow.cells[TOTAL_COLUMN].innerHTML = CMW.soal.util.formatPoints(points);
		    }
		
		    var subtotalRow = table.rows[table.rows.length - 1];
		
		    my.updateColumn(subtotalRow, QUANTITY_COLUMN, quantitySubtotal, quantitySubtotal);
		
		    my.updateColumn(subtotalRow, TOTAL_COLUMN, pointsSubtotal, CMW.soal.util.formatPoints(pointsSubtotal));
		
			var qtySumVal = YuD.get("orderTotal");
		    qtySumVal.innerHTML = CMW.soal.util.formatPoints(pointsSubtotal);
		    var memberPoints = YuD.get("memberPoints");
		    var lowestPoints = YuD.get("lowestPoints");
		    var hasMember = YuD.get("hasMember");
		    
		    var insuffPts = YuD.get("pointsError");
		    if (parseInt(YuD.get("memberPoints").value) < pointsSubtotal) {
		    	YuD.removeClass("pointsError","i-hidden");
		    } else {
		    	YuD.addClass("pointsError","i-hidden");
		    }

		    if ((parseInt(YuD.get("memberPoints").value) < parseInt(YuD.get("lowestPoints").value)) ||
		   		 (YuD.get("memberStatus").value != "1" )   || (YuD.get("hasMember").value == '0') ||
		   		 (quantitySubtotal == 0) || (parseInt(YuD.get("memberPoints").value) < pointsSubtotal)
		   		 || (YuD.get("disableSubmit").value == "true")) {
			    my.disableBtn(true);
		    } else {
			    my.disableBtn(false);   
		    }
		    
		},
		
		updateColumn: function(row, cellIndex, value, formattedValue) {
		    if ((value == 0) && (cellIndex != TOTAL_COLUMN)) {
		        row.cells[cellIndex].innerHTML = "&nbsp;";
		    }
		    else {
		        row.cells[cellIndex].innerHTML = formattedValue;
		    }
		},
		disableBtn: function(onOff){
			// YuD.get("requestCert.submitBtn").disabled = onOff;
			YuD.get("submitBtn").disabled = onOff;
		}
	};
	return my;
}();
/* End Request Certificate */

CMW.soal.ReplaceCard = function() {
	//private
	var YuD = YAHOO.util.Dom,
		YuE = YAHOO.util.Event;
	var portlet;
	//public
	var my = {
		init : function(src){
			portlet = YuD.getElementsByClassName('plReplacementCard', 'div');
			if(portlet){
				portlet = portlet[0];
				YuE.on(portlet,'click',function(ev){
					var tar = YuE.getTarget(ev);
					if(YuD.hasClass(tar, 'i-popupLk')){
						var href = CMW.ui.convertLink(portlet, tar);
						if(href != "") {
							YuE.stopEvent(ev);
							CMW.util.popupWindow(href);
						}
					}
				});
			}
		}
	};
	return my;
}();

CMW.soal.LogOut = function () {
	var YuD = YAHOO.util.Dom;
	var YuE = YAHOO.util.Event;
	
	var my = {
		init : function() {
			my.initFields();
		},
		
		initFields : function() {
			var logoutLinks = YuD.getElementsByClassName('i-logout', 'A', '', function() {	
				YuE.on(this, 'click', function(ev){
					var href = "consumerLogout.jsp";
					YAHOO.util.Connect.asyncRequest('POST', href, {success: my.show, failure: my.asyncError});
				});
			});			
		},
		
		show : function(o){			
		},
		
		asyncError : function(o){
			if(o.responseText !== undefined){
				CMW.soal.DataPanel.setBody(o.responseText);
			}
		}	
	};
	
	return my;
}();

YAHOO.util.Event.onDOMReady(CMW.soal.LogOut.init, CMW.soal.LogOut);

// Commented out because exists in JSP - YAHOO.util.Event.onDOMReady(CMW.soal.RequestCerts.init, CMW.soal.RequestCerts); 

