Number.prototype.toDecimals=function(n){
    n=(isNaN(n))?
        2:
        n;
    var
        nT=Math.pow(10,n);
    function pad(s){
            s=s||'.';
            return (s.length>n)?
                s:
                pad(s+'0');
    }
    return (isNaN(this))?
        this:
        (new String(
            Math.round(this*nT)/nT
        )).replace(/(\.\d*)?$/,pad);
}

function isNotBlank(sText){
	// Validate blank Text fields
	var check =/[\S]/;
	return check.test(sText);
}

var ModifiedFinalPrice = 0;

function priceCalculator() { 

	var basePrice = document.getElementById("basePrice").value;
	var allattr = document.getElementById("hidCalAttr").value;

	var finalPrice = parseFloat(basePrice);
	
	if (isNotBlank(allattr)) {
		var aryattr = allattr.split(','); 
		var length = aryattr.length
		for (var i=0; i<length; i++) { 
			if (aryattr[i] != '') {
				var attrval = document.getElementById(aryattr[i]).value;
				if (attrval != '') {
					var theval = attrval.split(':+:');
					if (theval.length > 1) {
						var strPriceMod = theval[1];
						var strPercent = strPriceMod.substring( strPriceMod.length-1);
						if (strPercent=='%'){
							var strTempPriceMod = strPriceMod.replace('%','');
							if (strTempPriceMod > 0){
								finalPrice = parseFloat(finalPrice) + ((strTempPriceMod/100)*parseFloat(finalPrice))
							}else if (strTempPriceMod < 0){
								finalPrice = parseFloat(finalPrice) + ((strTempPriceMod/100)*parseFloat(finalPrice))
							}
						}else{
							finalPrice = parseFloat(finalPrice) + parseFloat(theval[1]);
						}				
						//finalPrice = parseFloat(finalPrice) + parseFloat(theval[1]);
					}
				}
			}
		} 
	} 
	var oIsObj = document.getElementById("spanFinalPrice");
	
	ModifiedFinalPrice = finalPrice.toDecimals(2)
	if (oIsObj != null){
		document.getElementById("spanFinalPrice").innerHTML = "$" + finalPrice.toDecimals(2);
	}
	//document.getElementById('basePrice').value = finalPrice.toDecimals(2);
    
}

function updateModifier(curCtrl, hidCtrl, sValue) { 
	//alert(sValue);
	if (isNotBlank(document.getElementById(curCtrl).value)) {
		document.getElementById(hidCtrl).value = ':-:0:+:' + sValue
	}else {
		document.getElementById(hidCtrl).value = ':-:0:+:0' 
	}

	priceCalculator()

} 

function getSecondary(grpId, sPrimCtrl, isdiv) {

	// alert('test');
	// var oPrimCtrl = eval(primCtrl);
	var oGrpList = document.getElementById('groupList_'+grpId);
	var sGrpList = oGrpList.value ;
	// alert(sGrpList);
	var secCtrl = document.getElementById('ctrlSec_' + grpId);
	var oPrimCtrl = document.getElementById(sPrimCtrl);
	var ind = oPrimCtrl.selectedIndex;
	var sPrimValue = oPrimCtrl.options[ind].value;
	// alert (sPrimValue);
		
	getSecValues(sPrimValue, sGrpList, secCtrl, isdiv) ;

	priceCalculator()
	
}

function getSecValues(primValue, grpList, secCtrl, isdiv) {
	var grpArr = grpList.split('||')
	var z = 0;	
	
	if (!isdiv) 	secCtrl.options=""

	for (var i=0; i<grpArr.length;i++) {
		// alert('Main Item ' + grpArr[i]);
		var grpsubArr = grpArr[i].split(':-:')
		if (grpsubArr[0] == primValue) {
			//alert(primValue);
			
			var strDisplay='';
			var sValue='';
			var strPriceMod='';
			var strTempPriceMod='';
			var strPercent='';
			
			var arrDisp = grpsubArr[1].split(':+:')
			sValue = arrDisp[0];
			
			if (arrDisp[1]!='0'){
				strPriceMod = arrDisp[1];
				strPercent = strPriceMod.substring( strPriceMod.length-1);
				if (strPercent=='%'){
					strTempPriceMod = strPriceMod.replace('%','');
					if (strTempPriceMod > 0){
						strPriceMod = ' [add ' + arrDisp[1] + ']'		
					}else{
						strPriceMod = ' [substract ' + arrDisp[1].replace('-','') + ']'
					}
				}else{
					if (arrDisp[1] > 0){
						strPriceMod = ' [add $' + arrDisp[1] + ']'		
					}else{
						strPriceMod = ' [substract $' + arrDisp[1].replace('-','') + ']'
					}				
				}
				//strDisplay = arrDisp[0] + '  ' + arrDisp[1] + ' - ' + strPriceMod
				strDisplay = arrDisp[0] + strPriceMod
			}else{
				strDisplay = arrDisp[0]
			}
			if (!isdiv) {
				var Option1 = new Option(strDisplay,grpsubArr[0] + ':-:' + grpsubArr[1]);
				secCtrl.options[z] = Option1
				z++;
			}else {
				secCtrl.innerHTML = strDisplay ;
				document.getElementById('basePrice').value = strDisplay ;
			}
		}
	}
}

/* 
  ******************************************************************
  FUNCTIONS RELATED TO AJAX RETRIEVAL OF ATTRIBUTE VALUES FOR SEARCH 
  ****************************************************************** 
*/

var arrObjs = [];
var attr_ids = '';
var attr_values = '';
function reloadAttributes(obj) {

	arrObjs = [];
	attr_ids = '';
	attr_values = '';
	
	// total number of search attributes
	var t = parseInt(document.getElementById('hidAttribs').value);

	// current attribute (number)
	var c = obj.name.replace('cboAttr','');
	var p = parseInt(c);
	c = parseInt(c) + parseInt(1);

	// now create a delimited string to get the values
	for(i=1; i <= t; i++) {
		tname = 'Attr' + i;
		attr_id = document.getElementById('hid'+tname);
		cbo_obj = document.getElementById('cbo'+tname);

		if (cbo_obj.options) {
			cbo_sel = cbo_obj.options[cbo_obj.selectedIndex].value;

			if (attr_ids != '') attr_ids + ',';
			if (attr_values != '') attr_values = attr_values + ',';

			// add to global variables (used in CreateList)
			if (i <= p) {
				attr_values += attr_id.value + ':-:' + cbo_sel ;
			} else {
				attr_values += attr_id.value + ':-:' + '' ;
			}
			attr_ids = attr_ids + ',' + attr_id.value;

		}
	}

	//load the Array
	loadArray(c, t);

	//get the next Object to loop thru
	var nextObj = getNextObj(arrObjs);
	if (nextObj != null) {
		var tmp = nextObj.name.replace('cboAttr','hidAttr');
		id = document.getElementById(tmp).value;
		
		//alert('Id='+id + '\n Ids=' + attr_ids + '\n Filter=' + attr_values);
		MyAjaxCaller(nextObj.id, 'Value', id, attr_ids, attr_values);
	} 

}

function loadArray(c, t) {

	// get the next item 	
	next_attrid = parseInt('0');
	var next_attrcbo;
	if (c <= t) {
		var ctr = 0;
		for(i=c; i <= t; i++) {
			tname = 'Attr' + i;
			cbo_obj = document.getElementById('cbo'+tname);
			if (cbo_obj.options) {
				next_attrobj = document.getElementById('hid'+tname);
				next_attrcbo = document.getElementById('cbo'+tname);
				next_attrid = next_attrobj.value;

				//add to global array
				arrObjs[ctr] = next_attrcbo;
				ctr += 1 ;
			}
		}
	}	
}

function MyAjaxCaller(ctrl, tag, id, ids, filter) {
	var strPath = '/cms/incommerce/support/';
	var str = location.href;
    if (str.indexOf('/cms/') < 0) {
	    strPath = '/incommerce/support/';
    }
	var AjaxServerPageName = strPath + 'SearchAttr.aspx';
	
	var QParam = '?attr_id=' + id + '&attr_ids=' + ids + '&filter='+ filter ;
	var obj = document.getElementById(ctrl);

	var requestUrl = AjaxServerPageName + QParam ;

	var ajax = new AjaxDelegate(requestUrl, CreateList, ctrl, tag);
	ajax.Fetch();
}

function CreateList(url, response, ctrl, tag) {
	var data = new Array();
	data =	response ;

	var obj = document.getElementById(ctrl);	
	removeAllOptions(obj);						//remove existing values
	//alert('test');
	loadXMLToDropdown(data, obj, tag);			//load data from source
	
	// now remove the current item and see if there's more & call it
	arrObjs.clean(obj);
	var nextObj = getNextObj(arrObjs);
	if (nextObj != null) {
		var tmp = nextObj.name.replace('cboAttr','hidAttr');
		id = document.getElementById(tmp).value;

		//alert('Id='+id + '\n Ids=' + attr_ids + '\n Filter=' + attr_values);

		MyAjaxCaller(nextObj.id, tag, id, attr_ids, attr_values);
	} 

}

function removeAllOptions(from) { 
	//remove all options
	var max = from.options.length
	for (var i=0; i<max; i++) {
		from.options[0] = null; 
	}
	from.selectedIndex = -1; 
} 

function loadXMLToDropdown(xml, dd, tagName) {
    var xmldoc, parser;
    var Elem;
    var destination="", addtext, addvalue;

	var isIE = true;
    try {	// Internet Explorer Only
		xmldoc = new ActiveXObject("Microsoft.XMLDOM") 
		xmldoc.async = false 
		xmldoc.loadXML(xml)         
	} catch(e) {	// other browsers
		isIE = false;	
        parser = new DOMParser();
        xmldoc = parser.parseFromString(xml,"text/xml");
	}

	Elem = xmldoc.getElementsByTagName(tagName) ; 
	Provlength = Elem.length; 
	        
	for(i=0; i < Provlength; i++) 
	{ 
		if (isIE == true) {
			addvalue = Elem.item(i).getAttribute("id");
			addtext = Elem.item(i).text; 		    
			//addvalue = addtext;
		} else {
			addvalue = Elem[i].childNodes[0].getAttribute("id");
			addtext = Elem[i].childNodes[0].nodeValue; 
			//addvalue = addtext;
		}
		
		dd.options[i] = new Option(addtext,addvalue);              
	} 
} 

//remove item from array
Array.prototype.clean = function(deleteValue) {  
	for (var i = 0; i < this.length; i++) {    
		if (this[i] == deleteValue) {               
			this.splice(i, 1);      
			i--;    
		}  
	}  
	return this;
};

// get next item in Array
function getNextObj(arryObj) {
	var nextObj ;
	for (arryObj.length; i >= 0; i--) {
		if (arryObj[i] != null) {
			nextObj = arryObj[i]; 
			break;
		}
	}
	return nextObj;
}



/* 
  ******************************************************************
  END FUNCTIONS RELATED TO AJAX RETRIEVAL OF ATTRIBUTE VALUES 
  ****************************************************************** 
*/
