
function OrderGroup(groupName, priceColumn, currency, discount) {
	this.groupName 	= new String(groupName);
	this.priceColumn 	= parseInt(priceColumn);
	this.currency		= parseInt(currency);
	this.discount		= parseFloat(discount);
	this._elemnts 	= new Array();
	function AddElement() {
			
	}
	OrderGroup.prototype.AddElement	= AddElement;	
}
function Product(_productID, _descriptionForSale, _prices, _currency, _promotion) {
  	this.ID;
   this.productID = _productID; 		      
	if (_prices) {
		this.price = _prices[0];        
		this.originalPrice = _prices[0];
	}
	this.prices = _prices;		
   this.totalPrice;
	this.descriptionForSale = _descriptionForSale;
	this.col = 2;
	this.currency = _currency; // 0 = U$D; 1 = BGL
	this.currencyAbr;
	this._count = 0;
	this._items = Array();
	this.container = null;
	this.description = "";
	this.promotion = _promotion;
	
	Product.prototype.CheckExist =  function(productID) {
   	var result = false;
		for (i in this._items) {			
			if  ((this._items[i] != null) && (this._items[i].productID == productID)) {
				result = true;
				break;
			}
		}
		return result;
   }
   Product.prototype.CalcPrice = function () {			
   	this.currencyAbr = (!bAllInBGL)?"USD":"BGL";
      if (bAllInBGL) {
      	this.price = (this.currency == 0)? this.prices[selectedrow] * us2bg : this.prices[selectedrow];
      } else {
      	this.price = (this.currency == 0)? this.prices[selectedrow] : this.prices[selectedrow] / us2bg;
      }
      this.totalPrice =  this.price * this._count;
   }
   Product.prototype.Add = function (_productID, _descriptionForSale, _prices, _currency, _promotion) {
		
		if (!this.CheckExist(_productID)) {
			
			//add new				
			var _item = new Product(_productID, _descriptionForSale, _prices, _currency, _promotion);                
			_item.ID = this._count++;
			_item._count = 1;
			_item.CalcPrice();
			
			this._items[_productID] = _item;			
			this.Draw();
		} else {
			
			_item = this._items[_productID];
			_item._count++;
			_item.totalPrice = _item._count * _item.price;
			
			el = document.getElementById("total" + _item.ID);
			if (el) {
				el.value = FormatFloat(_item.totalPrice);
			}
			count = document.getElementById("count" + _item.productID);
			if (count) {
				count.value = _item._count;
			}
		}
			
		this.DrawAllSum();            
      document.getElementById("obj_count").value = this._count;
		//store to cookie
		this.serialize(this._items);
		
   }
	   
	Product.prototype.Remove = function(id) {   	
		var container = document.getElementById("container");
		if (container) {
			var newSpan = document.createTextNode("");
			for (el in container.childNodes) {
				child = container.childNodes[el];
				if (child.id == "container"+id) {
					container.replaceChild(newSpan, child);
				}
			}
			for (i in this._items) {
				var item = this._items[i];
				if ((item != null) && (item.ID == id)) {
					this._items[i] = null;					
					document.getElementById("obj_count").value = this._count;
					this.DrawAllSum();
					this.serialize(this._items);
					break;
				}
			}
	   }      
   }
	
	Product.prototype.Draw = function () {
		var container = document.getElementById("container");
		if (container) {
			for (i in this._items) {
				if (this._items[i] != null) {					
					if ((container.childNodes[this._items[i].ID] != null) && (container.childNodes[this._items[i].ID] != "")) {
						//
					} else {						
						var str =  "<div id='container" + this._items[i].ID + "'><table cellpadin='0' cellspacing='0' border='0'><tr><td style='width:320px' align='left'>" + this._items[i].descriptionForSale +"</td>";
						str	+= "<td><input type='text' disabled = 'true' class='price' id='price" + this._items[i].ID + "' value='"+ FormatFloat(this._items[i].price) + "' style='width:45px'/></td>";
						str   += "<td><input type='text' class='txt_field_count' style='width:30px;' maxlength='2' id = 'count" + this._items[i].productID + "' name='count_" + this._items[i].ID + "' style='width:20' value='"  + this._items[i]._count + "' onChange='JavaScript:onCountChange(this);'/></td>";
						str   += "<td><input type='text' disabled = 'true' class='total' id='total" + this._items[i].ID +"' value='" + FormatFloat(this._items[i].totalPrice) + "' style='width:45px; color:#FF0000' /></td>";
						str   += "<td><input type='button' value='I' class='button_border' style='width:20px; height:21px;  font-weight: bold' onclick='JavaScript:AddDescription(\"" + this._items[i].productID + "\");'/></td>";
						str   += "<td><input type='button' value='X' class='button_border' style='width:20px; height:21px; font-weight: bold; color: red;' onclick='JavaScript:base.Remove(" + this._items[i].ID + ");'/></td>";
						str   += "</tr></table>";
						str	+= "<input type='hidden' name='priceID_" + this._items[i].ID +"' value='" + this._items[i].productID + "'>";
						str	+= "<input type='hidden' id ='price_" + this._items[i].ID + "' name='price_" + this._items[i].ID +"' value='" + FormatFloat(this._items[i].price) + "'>";
						str	+= "<input type='hidden' name='name_" + this._items[i].ID +"' value='" + this._items[i].descriptionForSale + "'>";
						str	+= "<input type='hidden' id = 'description_" + this._items[i].productID + "' name='description_" + this._items[i].ID +"' value='" + this._items[i].description + "'>";
						str	+= "</div>";
						container.insertAdjacentHTML("beforeEnd", str);
					}
				}
			}
		} else {
			//alert("container is not defined!");
		}
	}
   function AllIn(bAllInBGL) {
            if (!us2bg) {
            	alert("Валутният курс не е дефиниран!");
               return;
            }			
            for (i in this._items) {
	           	var item = this._items[i];
               if (item != null) {
                	//alert(item.descriptionForSale + " " + item.originalPrice);
                    if (!bAllInBGL) {
                    	item.currencyAbr = "USD";
		                item.price = (item.currency == 0)? item.prices[selectedrow] : item.prices[selectedrow] / us2bg;
                    } else {
                    	item.currencyAbr = "BGL";
                        //alert(item.originalPrice);
                        item.price = (item.currency == 0)? item.prices[selectedrow] * us2bg : item.prices[selectedrow];
                    }
                    item.totalPrice = item.price * item._count;
                    _pr = document.getElementById("price" + item.ID);
						  if (_pr) {
						      _pr.value = FormatFloat(item.price);
						  }
					
                    _total = document.getElementById("total" + item.ID)
						  if(_total)
						  	_total.value = FormatFloat(item.totalPrice);
                    
						  if (document.getElementById("abr" + item.ID))
	                    document.getElementById("abr" + item.ID).value = item.currencyAbr;
                }
            }
            this.DrawAllSum();
        }
   Product.prototype.DrawAllSum = function() {		
		//alert(stacktrace());
   	sum = 0;
      for (i in this._items) {
      	if (this._items[i] != null) {
         	sum += this._items[i]._count * this._items[i].price;
         }
     	}
		dds = parseFloat(sum + sum*.2);		
		dds = FormatFloat(dds);
		sum = FormatFloat(sum);
		sum += (!bAllInBGL)?"&nbsp;USD":"&nbsp;BGL";
		dds += (!bAllInBGL)?"&nbsp;USD":"&nbsp;BGL";
		SetHtmlElementByName("allsum", sum );
		//SetHtmlElementByName("allsumdds", dds );
	}
	Product.prototype._debug = function(element) {
   	str ="";
      for (el in element) {
	   	str += "Key= " + el + " - " + element[el] + "\n\n";
	   }
      alert(str);
	}
   
	function onCountChange(sender) {
         var oldValue = sender.value;
			id = sender.id.substring(5);
            if (isNaN(sender.value)) {
                sender.value = this._items[id]._count;
            } else {
            	var item = this._items[id];
                item._count = sender.value;
                item.totalPrice = item._count * item.price
                el = document.getElementById("total" + item.ID);
                if (el) {
                    el.value = FormatFloat(item.totalPrice);
                }
                this.serialize(this._items);
				this.DrawAllSum();
            }
        }
		function onColumnChange(column) {			            			
			this.AllIn(bAllInBGL);
		}
		//serialize one element
	    function serialize(arr) {
	        str = new  String();
	        for (index in arr) {
	        	if (arr[index]) {
					str += _serialize(arr[index]) + "~";
				}
	        }
			str = str.substring(0,str.length-1);  //remove last character
			//alert(str);			
	        document.cookie = "order=" + str + "; path=/";		
	    }
	    function _serialize(object) {
	    	str = new String();
	        for (el in object) {			
	                if ((el != "_items") && (el != "container") && (typeof(object[el]) != "function")) {
	               	 var obj = object[el];
		                if (isArray(obj)) {
		                    str += el + ":[";
		                    for (ar in obj) {
		                        str += obj[ar] + "-";
		                    }
		                    str = str.substring(0,str.length-1); //remove last character
		                    str += "]|"
		                } else if (isString(obj)){
		                    str +=  el + ":\"" + escape(_escape(obj)) + "\"|";
		                } else {
		                    str +=  el + ":\"" + obj + "\"|";
		                }
	                }
	        }
	        str = str.substring(0,str.length-1);  //remove last character
	        return str;
	    }
	    //unserialize one element
	    function unserialize(str) {
	    	/*%3A = :
		%22 = "
		%7C = |*/
			if (str.indexOf('%3A') != -1) {				
				//safe string ;)
			  	
				str = replaceAll(str, "%3A", ":");
				str = replaceAll(str, "%22", "\"");
				str = replaceAll(str, "%7C", "|");
				str = replaceAll(str, "%5B", "["); 
				str = replaceAll(str, "%5C", "\\");
				str = replaceAll(str, "%5D", "]"); 
				str = replaceAll(str, "%7E", "~");
				//alert("safe" + str);
			}
			var globalarray = str.split("~");
	        result = Array();
	        for(index in globalarray) {
	            bahmamamu = globalarray[index];
	            if (bahmamamu != "") {
	                var tmpObject = _unserialize(bahmamamu);
	                var priceElement = new Product();
	                priceElement.ID = index;
	                priceElement.productID 		= unescape(tmpObject["productID"]);
	                priceElement.prices 			= tmpObject["prices"];					
	                priceElement.price				= parseFloat(tmpObject["price"]);
	                priceElement.originalPrice 	= parseFloat(tmpObject["originalPrice"]);
	                priceElement.totalPrice		= parseFloat(tmpObject["priceElement"]);
	                priceElement.descriptionForSale = unescape(tmpObject["descriptionForSale"]);
	                priceElement.col				= parseInt(tmpObject["col"]);
	                priceElement.currency		= parseInt(tmpObject["currency"]);
	                priceElement.currencyAbr	= unescape(tmpObject["currencyAbr"]);
						 priceElement._count			= parseInt(tmpObject["_count"]);				
	                priceElement.description	= unescape(tmpObject["description"]);
					    result[tmpObject["productID"]] = priceElement;
	            }
	
	        }
	        this._items = result;
			var ind = parseInt(index);
			this._count =  (ind == 0)? 0: ind + 1;				
			document.getElementById("obj_count").value = this._count;
			this.Draw();
			this.DrawAllSum();
			this.AllIn(bAllInBGL);
	    }
	    function _unserialize(str) {
	        parsedelements = Array();
	        var hash = Array();
	        var elements = str.split("|");
	        for (a in elements) {
	        		hash = elements[a].split(":");
	            if (hash.length == 2) {
		            if ((hash[1].indexOf('[') != -1) && (hash[1].indexOf(']') != -1)) {
		                //get array elements
		                str2 = hash[1].substring(1, hash[1].length - 1);
						_elements = new Array();
						_el = str2.split("-"); 
						for (vv in _el) {
							_elements[vv] = parseFloat(_el[vv]);
						}	                
						parsedelements[hash[0]] = _elements;						
		            } else {
		                parsedelements[hash[0]] = _unescape(hash[1].substr(1,hash[1].length-2));
	
		            }
	            }
	        }
	        hash = null;
	        elements = null;
	        return parsedelements;
	    }   

    Product.prototype.onCountChange	= onCountChange;
	 Product.prototype.onColumnChange= onColumnChange;
    Product.prototype.AllIn			= AllIn;
    Product.prototype.serialize		= serialize;
	 Product.prototype.unserialize	= unserialize;
	
	

} //end class