var nRowCounter = 1;
var arArticles = new Array();
var sArray = '';

function GetArticleInfo(nCode, nRow){	
	var Request = new AjaxRequest();
	Request.Async = true;
	Request.Attributes = nRow;
	Request.CallBack = "GetArticleInfoCallBack";
	Request.Url = "vip_ajax.php";
	Request.FilePath = "vip_ajax.php";
	Request.ClassName = "test";
	Request.MethodName = "GetArticleDetails";
	Request.RegisterArgument("Code", nCode);
	Request.Send();
}

function GetArticleInfoCallBack(xmlHttp, Attributes){
	if(document.all){
		var xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
		xmlDocument.loadXML(xmlHttp.responseText);
	}else{
		xmlDocument = xmlHttp.responseXML
	}
	var sTagID = "Name" + Attributes + "";
	document.getElementById("Name" + Attributes).innerHTML = xmlDocument.getElementsByTagName("cell")[0].childNodes[0].nodeValue;
	document.getElementById("Measure" + Attributes).innerHTML = xmlDocument.getElementsByTagName("cell")[1].childNodes[0].nodeValue;
	document.getElementById("PriceLow" + Attributes).innerHTML = xmlDocument.getElementsByTagName("cell")[2].childNodes[0].nodeValue;
	document.getElementById("PriceHigh" + Attributes).innerHTML = xmlDocument.getElementsByTagName("cell")[3].childNodes[0].nodeValue;
	document.getElementById("Bonus" + Attributes).setAttribute('value', xmlDocument.getElementsByTagName("cell")[4].childNodes[0].nodeValue);
	//document.getElementById("Bonus" + Attributes).value = xmlDocument.getElementsByTagName("cell")[4].childNodes[0].nodeValue;
	var nCount = document.getElementById("Pcs" + Attributes).value;
	document.getElementById("Value" + Attributes).innerHTML = nCount * xmlDocument.getElementsByTagName("cell")[3].childNodes[0].nodeValue;
	arArticles[Attributes] = xmlDocument.getElementsByTagName("cell")[2].childNodes[0].nodeValue;
	sArray += 'arArticles['+ Attributes +'] = '+ xmlDocument.getElementsByTagName("cell")[2].childNodes[0].nodeValue +'; ';
}

function AddNew(){
	nRowCounter = nRowCounter + 1;
	sHTML = '<input id="input'+ nRowCounter +'" type="text" name="Code[]" onchange="GetArticleInfo(this.value, ' + nRowCounter + ')" onkeyup="this.setAttribute(\'value\', this.value);" />';
	var oTable = document.getElementById('ElTable');
	var nLastRow = oTable.rows.length;
	var oRow = oTable.insertRow(nLastRow);
	oRow.setAttribute('id', 'row' + nRowCounter);
	var oFirstCell = oRow.insertCell(0);
	var sSpacerHTML = '<img src="im/spacer.gif" alt="" />';
	var oCell = oRow.insertCell(1); oCell.innerHTML = sSpacerHTML;
	oCell.setAttribute('id', 'Name' + nRowCounter);
	var oCell = oRow.insertCell(2); oCell.innerHTML = sSpacerHTML;
	oCell.setAttribute('id', 'Measure' + nRowCounter);
	var oCell = oRow.insertCell(3); oCell.innerHTML = sSpacerHTML;
	oCell.setAttribute('id', 'Pieces' + nRowCounter);
	oCell.innerHTML = '<input type="text" id="Pcs'+ nRowCounter +'" name="Pcs[]" value="1" onkeyup="this.setAttribute(\'value\', this.value);" onchange="ChangePcs(' + nRowCounter + ', this.value)" />';
	var oCell = oRow.insertCell(4); oCell.innerHTML = sSpacerHTML;
	oCell.setAttribute('id', 'PriceLow' + nRowCounter);
	oCell.setAttribute('class', 'VipStatus');
	var oCell = oRow.insertCell(5); oCell.innerHTML = sSpacerHTML;
	oCell.setAttribute('id', 'HappyField' + nRowCounter);
	oCell.setAttribute('class', 'TO');
	oCell.innerHTML = '<input id="Bonus'+ nRowCounter +'" type="text" name="Bonus[]" value="0" onkeyup="this.setAttribute(\'value\', this.value);" onchange="HappyTime(' + nRowCounter + ', this.value, true)" />';
	var oCell = oRow.insertCell(6); oCell.innerHTML = sSpacerHTML;
	oCell.setAttribute('id', 'PriceHigh' + nRowCounter);
	oCell.setAttribute('class', 'VipStatus');
	var oCell = oRow.insertCell(7); oCell.innerHTML = sSpacerHTML;
	oCell.setAttribute('id', 'Value' + nRowCounter);
	oCell.setAttribute('class', 'VipStatus');
	oCell.innerHTML = '<input type="hidden" id="ArticleValue'+ nRowCounter +'" name="Price'+ nRowCounter +'" />';
	oFirstCell.innerHTML = sHTML;
}

function Order(){
	var oTextarea = document.getElementById("OrderHTML");
	var oForm = document.getElementById("OrderForm");
	var sTableHTML = document.getElementById("TableHTML").innerHTML;
	var sHTML = '<script type="text/javascript">' + sArray + '</script>';
	oTextarea.value = sHTML + sTableHTML;
	oForm.submit();	
}

function ChangePcs(nRow, nValue){
	document.getElementById('Value' + nRow).innerHTML = RoundNumber(arArticles[nRow] * nValue, 2);
	HappyTime(nRow, document.getElementById('Bonus' + nRow).value, false);
}

function HappyTime(nRow, nValue, bRefreshPrice){
	var nPieces = document.getElementById('Pcs' + nRow).value;
	var nTotalValue = arArticles[nRow] * nPieces;
	var nPercent = (nTotalValue / 100) * nValue ;
	if(bRefreshPrice){
		var nRefreshPercent = (arArticles[nRow] / 100) * nValue ;
		document.getElementById('PriceHigh' + nRow).innerHTML = RoundNumber(arArticles[nRow] - nPercent, 2);
	}
	document.getElementById('Value' + nRow).innerHTML = RoundNumber(nTotalValue - nPercent, 2);
}

function UpdateOffer(){
	var oHiddenArea = document.getElementById('HiddenArea');
	var sOffer = document.getElementById('TableHTML').innerHTML;
	oHiddenArea.innerHTML = sOffer;
}

function RoundNumber(nNum, nDecimal) {
	return Math.round(nNum * Math.pow(10, nDecimal)) / Math.pow(10, nDecimal);
}

var not_whitespace = new RegExp(/[^\s]/);//This can be given inside the funciton - I made it a global variable to make the scipt a little bit faster.
var parent_count;
function xml2array(xmlDoc,parent_count) {
	var arr;
	var parent = "";
	parent_count = parent_count || new Object;

	var attribute_inside = 0; /*:CONFIG: Value - 1 or 0
	*	If 1, Value and Attribute will be shown inside the tag - like this...
	*	For the XML string...
	*	<guid isPermaLink="true">http://www.bin-co.com/</guid>
	*	The resulting array will be...
	*	array['guid']['value'] = "http://www.bin-co.com/";
	*	array['guid']['attribute_isPermaLink'] = "true";
	*	
	*	If 0, the value will be inside the tag but the attribute will be outside - like this...	
	*	For the same XML String the resulting array will be...
	*	array['guid'] = "http://www.bin-co.com/";
	*	array['attribute_guid_isPermaLink'] = "true";
	*/

	if(xmlDoc.nodeName && xmlDoc.nodeName.charAt(0) != "#") {
		if(xmlDoc.childNodes.length > 1) { //If its a parent
			arr = new Object;
			parent = xmlDoc.nodeName;
			
		}
	}
	var value = xmlDoc.nodeValue;
	if(xmlDoc.parentNode && xmlDoc.parentNode.nodeName && value) {
		if(not_whitespace.test(value)) {//If its a child
			arr = new Object;
			arr[xmlDoc.parentNode.nodeName] = value;
		}
	}

	if(xmlDoc.childNodes.length) {
		if(xmlDoc.childNodes.length == 1) { //Just one item in this tag.
			arr = xml2array(xmlDoc.childNodes[0],parent_count); //:RECURSION:
		} else { //If there is more than one childNodes, go thru them one by one and get their results.
			var index = 0;

			for(var i=0; i<xmlDoc.childNodes.length; i++) {//Go thru all the child nodes.
				var temp = xml2array(xmlDoc.childNodes[i],parent_count); //:RECURSION:
				if(temp) {
					var assoc = false;
					var arr_count = 0;
					for(key in temp) {
						if(isNaN(key)) assoc = true;
						arr_count++;
						if(arr_count>2) break;//We just need to know wether it is a single value array or not
					}

					if(assoc && arr_count == 1) {
						if(arr[key]) { 	//If another element exists with the same tag name before,
										//		put it in a numeric array.
							//Find out how many time this parent made its appearance
							if(!parent_count || !parent_count[key]) {
								parent_count[key] = 0;

								var temp_arr = arr[key];
								arr[key] = new Object;
								arr[key][0] = temp_arr;
							}
							parent_count[key]++;
							arr[key][parent_count[key]] = temp[key]; //Members of of a numeric array
						} else {
							parent_count[key] = 0;
							arr[key] = temp[key];
							if(xmlDoc.childNodes[i].attributes.length) {
								for(var j=0; j<xmlDoc.childNodes[i].attributes.length; j++) {
									var nname = xmlDoc.childNodes[i].attributes[j].nodeName;
									if(nname) {
										/* Value and Attribute inside the tag */
										if(attribute_inside) {
											var temp_arr = arr[key];
											arr[key] = new Object;
											arr[key]['value'] = temp_arr;
											arr[key]['attribute_'+nname] = xmlDoc.childNodes[i].attributes[j].nodeValue;
										} else {
										/* Value in the tag and Attribute otside the tag(in parent) */
											arr['attribute_' + key + '_' + nname] = xmlDoc.childNodes[i].attributes[j].nodeValue;
										}
									}
								} //End of 'for(var j=0; j<xmlDoc. ...'
							} //End of 'if(xmlDoc.childNodes[i] ...'
						}
					} else {
						arr[index] = temp;
						index++;
					}
				} //End of 'if(temp) {'
			} //End of 'for(var i=0; i<xmlDoc. ...'
		}
	}

	if(parent && arr) {
		var temp = arr;
		arr = new Object;
		
		arr[parent] = temp;
	}
	return arr;
}

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
	 for(var item in arr) {
	  var value = arr[item];
	 
	  if(typeof(value) == 'object') { //If it is an array,
	   dumped_text += level_padding + "'" + item + "' ...\n";
	   dumped_text += dump(value,level+1);
	  } else {
	   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
	  }
	 }
	} else { //Stings/Chars/Numbers etc.
	 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
} 

function RemoveArticle(nArticleID, nRow, bAjax){	
	var oTR = document.getElementById("Row" + nRow);
	var oInput = document.getElementById("Hidden" + nRow);
	oInput.value = 0;
	oTR.style.display = "none";
	
	if(bAjax){
		var Request = new AjaxRequest();
		Request.Async = true;
		Request.CallBack = "RemoveArticleCallBack";
		Request.Url = "vip.php";
		Request.FilePath = "vip.php";
		Request.RegisterArgument("ArticleID", nArticleID);
		Request.Send();
	}
}

function RemoveArticleCallBack(xmlHttp, Attributes){
}