arithneaJSObject = {};
var debug = false;
/* replace a parameter value in url; if the parameter is not available in the url, it will be added */
arithneaJSObject.replaceUrlParam = function(url, name, value) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(url);
    if (results == null)
		if (url.indexOf("?") > -1 )
			return url + "&" + name + "=" + value;
		else
			return url + "?" + name + "=" + value;
    else {
        return url.replace(results[0], results[0].replace(/=(.*)/, '=' + value));
    }
};

/* get parameter value of the given name from an url */
arithneaJSObject.getParameterValue = function( url, name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
		return "";
	else
		return results[1];
}
arithneaJSObject.format = function(number, round, sep, thSep, currency, position){
	number = Math.round( number * Math.pow(10, round) ) / Math.pow(10, round);
	str_number = number + "";
	arr_int = str_number.split(".");
	if(!arr_int[0]) arr_int[0] = "0";
	if(!arr_int[1]) arr_int[1] = "";
	if(arr_int[1].length < round){
		decimalPlaces = arr_int[1];
		for(var i=arr_int[1].length+1; i <= round; i++){
			decimalPlaces += "0";
		}
		arr_int[1] = decimalPlaces;
	}
	// add thousands group marker
	if(thSep != "" && arr_int[0].length > 3){
		integerPlaces = arr_int[0];
		arr_int[0] = "";
		for(var j = 3, len = integerPlaces.length; j < len; j+=3){
			Part = integerPlaces.slice(integerPlaces.length - j, integerPlaces.length - j + 3);
			arr_int[0] = thSep + Part +  arr_int[0] + "";
		}
		str_first = integerPlaces.substr(0, (integerPlaces.length % 3 == 0)?3:(integerPlaces.length % 3));
		arr_int[0] = str_first + arr_int[0];
	}
	// add curreny
	if  (currency != undefined){
		if (position == "START"){
			return currency + " " + arr_int[0]+sep + arr_int[1];
		}
		return arr_int[0] + sep + arr_int[1] + " " + currency;
	}

	return arr_int[0] + sep + arr_int[1]
	



}
/* ### CART Region v1.9 BEGIN ### */
arithneaJSObject.cart = function(){
	/* hard configured constants */
	this.config = {
		client: "",
		LANG: "",
		cookieName: "hornbach_cart",
		currency:{
			sign: "RON",
			signPosition: "END", /* START or END */
			delimiter: ",",
			thSeperator: ".",
			round: 2,
			salesTax: 24 
		},
		templates: {
			btnWishlist: "<b>Introduceți &#238;n lista dorită</b>",
			btnWishlistAdded: "<b>Introdus &#238;n lista dorită</b>",
			smallList: "<a class='button right' href='${url}'><b>Lista dorită (${count})</b></a>",
			list: "<form id='cartListForm' action='#' method='post'><!--<h1>Lista dorită:</h1>--><br />\n\
				<table id='cartItemsListing'>\n\
					<thead>\n\
						<tr>\n\
							<th class=\"image\">Articol</th>\n\
							<th class=\"description\">Caracteristici</th>\n\
							<th class=\"unit-price\">Preț pe bucată</th>\n\
							<th class=\"number\">Număr</th>\n\
							<th class=\"total-price\">Total</th>\n\
							<th class=\"delete\">&#160;</th>\n\
						</tr>\n\
					</thead>\n\
					<tbody>\n\
						${items}\n\
					</tbody>\n\
				</table>\n\
				<br />\n\
				<table id='cartItemsSummary'>\n\
					<tr>\n\
						<td width=\"100%\"><span class=\"label\">Preț total:</span></td>\n\
						<td>\n\
							<p class='price'>\n\
								<b>${totalPrice}</b><br/>\n\
								Preț cu TVA\n\
							</p>\n\
						</td>\n\
					</tr>\n\
				</table>\n\
			</form>\n\
			<div class='btn_leiste' style='float:right'>\n\
				<div class='btn_any'>\n\
					<ul>\n\
						<li class='print'><a href='javascript:window.print();' title='Link: Tipărire articole'>Tipărire articole</a></li>\n\
					</ul>\n\
				</div>\n\
			</div>",
			row: "	<tr>\n\
						<td class=\"image\">\n\
							<img alt='a' src='${imageUrl}' width='80' />\n\
						</td>\n\
						<td id='inner_cont' class='description copy' width=\"100%\">\n\
							<a href='${articleUrl}'>${name}</a><br />\n\
							<span class=\"itemNumber\">Art.-Nr. ${articleNumber}</span><br />\n\
							${attributes}\n\
						</td>\n\
						<td class=\"unit-price\">\n\
							<p class='price'><b>${singlePrice}</b>${packaging}<br/>\n\
							Preț cu TVA</p>\n\
						</td>\n\
						<td class=\"number\">Cantitate: <input size='3' name='${id}' type='text' class='number' value='${count}'/><button style='padding:0 3px; border:0px; background:transparent' type='submit'><img src='/cms/media/_technik/images_2/shared/icon_refresh.gif' alt='Actualizare'/></button></td>\n\
						<td class=\"total-price\"><p class='price'><b>${totalPrice}</b><br/>Preț cu TVA</p></td>\n\
						<td class=\"delete\"><a href='#' class='cart-remove' rel='${id}'><img src='/cms/media/_technik/images_2/shared/icon_trash.gif' alt='Ștergeți articolul' /></a></td>\n\
					</tr>"
		},
		listingDivId: "cartList",
		listingSmallDivId: "cart",
		btnWishlistId:	"addList${id}",
		btnWishlistClass: "wishlist",
		Url: "/cms/ro/ro/produkte_ro/merkliste_ro.html",
		
		JSONItemURL: "--will be set by init--",
		initialized: false
	};

	/* items of the cart*/
	this.items = {}

	/* check if item is already in List */
	this.isItemInList = function(id, items){
		if (items != undefined && items.length > 0){
			for (i=0,  len = items.length; i < len; i++){
				if (items[i]['id'] == id){
					return true;
				}
			}
		}
		return false;
	}
	

	this.addToList = function(data){
		var cart = arithneaJSObject.cartInstance.getInstance(),
		items = cart.getItems();

		if (cart.isItemInList(data.id, items)){
		//console.log('not added');
		}else{
			if (items == undefined){
				items = new Array();
			}
			var myAnzahl = 1;
			myAnzahl = jQuery('#myanzahl').val();
			if (myAnzahl > 0){
				data["count"] = myAnzahl;
			}else{
				//data["count"] = 1;
				var transferID = data.id;	
				var transferURLID = data.urlID;
				data = { id: transferID, urlID: transferURLID, count: 1 };
			}
			items.push(data);
		}
		cart.storeCart(items);
	}

	this.removeFromList = function(id){
		var items = this.getItems();
		if (items != undefined && items.length > 0){
			for (i=0, len = items.length; i < len; i++){
				if (items[i] != undefined && items[i]['id'] == id){
					items.splice(i,1);
				}
			}
		}
		this.storeCart(items);
	}

	/*initaizes the Cart  */
	this.init = function(params){
		this.config = jQuery.extend(true, {}, this.config, params);
		// set params to config
		var id = params.JSONItemID;
		if(id.length < 2){
			id: "${artikelMandantID}";
		}
		this.config.JSONItemURL = params.JSONItemURLPrefix+params.JSONItemURL+id+params.JSONItemURLSuffix;
		
		
		// initialize cookie
		jQuery.Jookie.Initialise(this.config.cookieName, -1);
		
		// reload the cart
		this.reloadCart();
	}

	/* adds an item to the cart, sets itemCount to 1 */
	this.addItemToCart = function(itemID){
		this.getItemJSONURL(itemID);
	}

	/* removes an item from the cart */
	this.removeItemFromCart = function(itemID){
		this.removeFromList(itemID);
	}

	/**/
	this.changeItemCountToValue = function(itemID, value, storeInSession, reloadCart){
		var items = this.getItems();
		if (items != undefined && items.length > 0){
			for (i=0, len = items.length; i < len; i++){
				if (items[i] != undefined && items[i]['id'] == itemID){
					if (value > 0){
						items[i].count = parseInt(value);
					}else{
						items.splice(i,1);
					}
				}
			}
		}
		this.storeCart(items, storeInSession, reloadCart);
	}


	/* creates and manipulates the dom to change this.listingDIVID.innerHTML the view the card */
	this.listCart = function(){
		var cartObj = {
			totalPrice: 0,
			totalTaxPrice: 0,
			items: ""
		};
		var items = this.getItems();
		if (jQuery("#" + this.config.listingDivId).length > 0){
			if (items != undefined){
				/* async is much more komplex and not needed with the minimal amount of data in the JSON files */
				jQuery.ajaxSetup( {async: false} );
				for (var i=0, len = items.length; i < len; i++){
					var itemURLid = items[i].urlID;
					var ajaxitem = this.getItemJSONURLtoShow(itemURLid);
					var item = JSON.parse(ajaxitem.responseText);
					item.singlePrice = item.price;
					item.totalPrice = item.price * items[i].count;
					item.taxPrice = 0;
					item.count = items[i].count;
					if (this.config.currency.salesTax > 0){
						item.taxPrice = item.totalPrice / (100 + this.config.currency.salesTax) * this.config.currency.salesTax;
					}
					cartObj.totalPrice += item.totalPrice;
					cartObj.totalTaxPrice += item.taxPrice;
					cartObj.items += this.tmplArray(this.config.templates.row, item);
					if(debug == true){
						console.log("---listCart---");
						console.log("ajaxitem: "+ajaxitem);
						console.log("item: "+item);
						console.log("item.price: "+item.price);
						console.log("items.count: "+items[i].count);
						console.log("items.totalPrice: "+items[i].totalPrice);
					}
				}
				jQuery.ajaxSetup( {async: true} );
			}
			
			try {
				jQuery("#" + this.config.listingDivId).html( this.tmplArray(this.config.templates.list, cartObj) );
			} catch (e) {
				alert(this.config.listingDivId + ' not found!');
			}
			
			jQuery(".cart-remove").click(function(){
				arithneaJSObject.cartInstance.getInstance().removeItemFromCart(jQuery(this).attr('rel'));
				return false;
			});
			jQuery('.btn_any').css('display','none');
			
			jQuery("#cartListForm").submit(function(){
			
				jQuery("#cartListForm .number").each(function(i){
					var cart = arithneaJSObject.cartInstance.getInstance();
					if (jQuery(this).val()){
						if (i  <  (jQuery("#cartListForm .number").length - 1) ){
							cart.changeItemCountToValue(jQuery(this).attr("name"), jQuery(this).val(), false, false);
						}else{
							cart.changeItemCountToValue(jQuery(this).attr("name"), jQuery(this).val(), true, true);
						}
					}
				});
				return false;
			});
		}
	}

	/* change Label for wishlist button */
	this.changeLabels = function(){
		var items = this.getItems();
		jQuery("." + this.config.btnWishlistClass).html( this.config.templates.btnWishlist );
		if (items != undefined){
			for (var i=0, len = items.length; i < len; i++){
				jQuery("#" + this.tmpl(this.config.btnWishlistId, "id", items[i].id) ).html( this.config.templates.btnWishlistAdded );
				if (jQuery("#" + this.tmpl(this.config.btnWishlistId, "id", items[i].id)) != undefined) {
					//jQuery('#myanzahl').css('display', 'none');
					//jQuery('#myanzahlLabel').css('display', 'none');
				}
			}
		}
	}

	/* lists the small cart*/
	this.listSmallCart = function(){
		var items = this.getItems();
		var marker = {
			count: 0,
			url: this.config.Url
		};
		if (items != undefined){
			marker.count = items.length;
		}

		jQuery("#" + this.config.listingSmallDivId).html(this.tmplArray(this.config.templates["smallList"], marker));

	}

	/* list the cart and the small cart */
	this.reloadCart = function(){
		this.changeLabels();
		this.listCart();
		this.listSmallCart();
	}

	/* reads the current saved session-cart, for session review visit of page*/
	this.readCartFromSession = function(){
		var g = jQuery.Jookie.Get("hornbach_cart", "cartList");
		//var g = jQuery.Jookie.Get("hornbach_cart", "cartList");
		//g = unescape(g);
		return g;
	}

	/* stores the items of the card in session and reloads the cart*/
	this.storeCart = function(items, storeInSession, reloadCart){

		var storeCart = true,
		reload = true;
		if (reloadCart != undefined){
			reload = reloadCart;
		}
		if (storeInSession != undefined){
			storeCart = storeInSession;
		}
		this.items = items;
		if (storeCart){
			//itemsEncoded = encode(items);
			//jQuery.Jookie.Set("hornbach_cart", "cartList", itemsEncoded);
			jQuery.Jookie.Set("hornbach_cart", "cartList", items);
		}
		if (reload){
			this.reloadCart();
		}
	}

	this.getItemJSONURL = function(itemID){
		var id = params.JSONItemID;
		if(id.length < 2){
				id = itemID;
		}
		this.config.JSONItemURL = params.JSONItemURLPrefix+params.JSONItemURL+id+params.JSONItemURLSuffix;
		tmpl = this.tmpl(this.config.JSONItemURL, "itemId", itemID);
		jQuery.getJSON(tmpl, null, this.addToList);
	}
	
	this.getItemJSONURLtoShow = function(itemID){
		this.config.JSONItemURL = params.JSONItemURLPrefix+params.JSONItemURL+itemID+params.JSONItemURLSuffix;
		tmpl = this.tmpl(this.config.JSONItemURL, "itemId", itemID);
		if(debug == true){
			console.log("---getItemJSONURLtoShow---");
			console.log("itemID: "+itemID);
			console.log("jsonurl: "+this.config.JSONItemURL);
			console.log("id: "+itemID);
		}		
		return jQuery.getJSON(tmpl, null);
	}

	this.getItems = function(){
		if (!this.config.initialized){
			this.items = this.readCartFromSession();
			this.config.initialized = true;
		}
		return this.items;
	}

	/* save the JSON item properties to the persistent object var.itemProperties */
	this.storeItemProperties = function(itemID){
		JSON = getItemJSONURL(itemID);
	}

	/* small template function */
	this.tmpl = function (text, key, value){
		if (value == undefined){
			value = "";
		}
		if (text == undefined){
			text = "";
		}

		if (key.search(/Price$/) != -1){
			value = arithneaJSObject.format(value, 
				this.config.currency.round,
				this.config.currency.delimiter,
				this.config.currency.thSeperator,
				this.config.currency.sign,
				this.config.currency.signPosition
				)
		}

		return text.replace("\$\{" + key + "\}", value);
	}

	/*template funtion for arrays and objects*/
	this.tmplArray = function(text, list){
		search = /\$\{(\w+?)\}/g;
		replacedText = text;
		while (results = search.exec(text)){ //
			replacedText = this.tmpl(	replacedText,
				results[1],
				list[results[1]]);
		}
		return replacedText;
	}
}


arithneaJSObject.cartInstance = function(){
	this.instance;
};

arithneaJSObject.cartInstance.getInstance = function(){
	if (this.instance == undefined){
		this.instance = new arithneaJSObject.cart();
	}
	return this.instance;
}
/* ### CART Region v1.9 END ### */

