function wp_about() {
	alert("WP Subscription JS library 1.0");
}

/** constants and enumerations */
var WP_ID_UNKNOWN = 0;

var WP_STATE_UNKNOWN = 0;
var WP_STATE_AVAILABLE = 1;
var WP_STATE_COMPLETED = 3;
var WP_STATE_ORDERING = 5;

var WP_TYPE_UNKNOWN = 0;
var WP_TYPE_PACKAGE = 2;
var WP_TYPE_FLEXIBLE = 1;

var WP_CALLBACK_PREFIX = 'wpcb_';

/** data classes */

/** class market */
function wpMarket(id, countryId, fullname) {
	this.id = id || WP_ID_UNKNOWN;
	this.countryId = countryId || WP_ID_UNKNOWN;
	this.fullname = fullname || this.name + " - " + this.country;

	this.getId = function(){ return this.id; }
	this.getCountryId = function() { return this.countryId; }
	this.getFullName = function() { return fullname; }
}

/** class cart record */
function wpCartRecord(itemId, productName, marketName, cost) {
	this.itemId = itemId || '';
	this.productName = productName || "";
	this.marketName = marketName || "";
	this.cost = cost || 0.0;

	this.getItemId = function() { return this.itemId; }
	this.getProductName = function() { return this.productName; }
	this.getMarketName = function() { return this.marketName; }
	this.getCost = function() { return this.cost; }
}

/** class cart */ 

function wpCart() {
	this.cost = 0.0;
	this.items = new Array();
	
	this.getCost = function() { return this.cost; }
	this.getSize = function() { return this.items.length; }
	this.getItem = function(index) { return this.items[index]; }
	
	this.addItem = function(item) {
		this.items.push(item);
		this.cost += item.getCost();
	}
	
	this.deleteItemAt = function(index) {
		var item = this.items.deleteAt(index);
		if ( item != undefined ) {
			this.cost -= item.getCost();
		}
	}
}

/** class subscription table record */

function wpSubscription(id, type, title, description, price) {
	this.id = id || WP_ID_UNKNOWN;
	this.title = title || '';
	this.description = description || '';
	this.price = price || 0.0;
	
	this.getId = function() { return this.id; }
	this.getTitle = function() { return this.title; }
	this.getDescription = function() { return this.description; }
	this.getPrice = function() { return this.price; }
}

function wpPackageSubscription(id, title, description, price) {
	this.subscription = wpSubscription;
	this.subscription(id, WP_TYPE_PACKAGE, title, description, price);

	this.getType = function() { return WP_TYPE_PACKAGE; }

	this.countries = new Array();

	this.addApplicapableCountry = function(countryId) {
		this.countries[countryId] = true;
	}
/*
	this.removeApplicapableCountry = function(countryId) {
		this.countries.countryId = undefined;
	}
*/	
	this.isCountryApplicapable = function(countryId) { 
		return this.countries[countryId] != undefined; 
	}
}

function wpFlexibleSubscription(id, title, description, price) {
	this.subscription = wpSubscription;
	this.subscription(id, WP_TYPE_FLEXIBLE, title, description, price);

	this.getType = function() { return WP_TYPE_FLEXIBLE; }
	
	this.countries = new Array();

	this.addApplicapableCountry = function(countryId) {
		if ( this.countries[countryId] == null ) {
			this.countries[countryId] = 1;
		} else {
			++this.countries[countryId];
		}
	}

	this.removeApplicapableCountry = function(countryId) {
		if ( this.countries[countryId] != null ) {
			--this.countries[countryId];
		}
	}
	
	this.isCountryApplicapable = function(countryId) { 
		var c = this.countries[countryId];
		return (c != null) && (c > 0); 
	}

	this.markets = new Array();
	this.deletedMarkets = new Array();

	this.getMarkets = function() { return this.markets; }
	
	this.addMarkets = function(packageId, markets) { 
		this.markets[packageId] = markets; 
		for ( var i = 0; i < markets.length; ++i ) {
			this.addApplicapableCountry(markets[i].getCountryId());
		}
	}
	
	this.deleteMarketAt = function(packageId, idx) {
		var markets = this.markets[packageId];
		if ( markets != null && idx >= 0 && idx < markets.length ) {
			var newMarkets = new Array(markets.length - 1);
			var dstIdx = 0;
			for ( var srcIdx = 0; srcIdx < markets.length; ++srcIdx ) {
				if ( srcIdx != idx ) {
					newMarkets[dstIdx++] = markets[srcIdx];
				} else {
					var delMarketsMap = this.deletedMarkets[packageId];
					if ( delMarketsMap == null ) {
						delMarketsMap = new Array();
						this.deletedMarkets[packageId] = delMarketsMap;
					}
					
					var market = markets[srcIdx];
					delMarketsMap[market.getId()] = market;
					this.removeApplicapableCountry(market.getCountryId());
				}
			}
					
			this.markets[packageId] = newMarkets;
		}
	}
	
	this.restoreMarket = function(packageId, marketId) {
		var delMarketsMap = this.deletedMarkets[packageId];
		if ( delMarketsMap != null ) {
			var market = delMarketsMap[marketId];
			if ( market != null ) {
				delMarketsMap[marketId] = null;
				
				var markets = this.markets[packageId];
				if ( markets != null ) {
					markets[markets.length] = market;
					markets.sort(function(m1, m2) { return m1.getFullName().localeCompare(m2.getFullName()); } )
				} else {
					this.addMarkets(prodId, market);
				}
				
				this.addApplicapableCountry(market.getCountryId());
			}
		}
		
	}
}

function wpAvailableSubscriptions() {
	this.entries = [];
	this.entriesIndexMapping = []; // contains mapping of external indexes to internal indexes (in entries array)
	
	this.getSubscriptionCount = function() { return this.entriesIndexMapping.length; }
	this.getSubscription = function(index) { return this.entries[this.entriesIndexMapping[index]]; }
	
	this.add = function(subscription) { 
		this.entries[this.entries.length] = subscription; 
		this.entriesIndexMapping[this.entriesIndexMapping.length] = this.entries.length - 1;
	}
	
	this.findSubscriptionIndexById = function(subId) {
		for ( var idx = 0; idx < this.entriesIndexMapping.length; ++idx ) {
			if ( this.entries[this.entriesIndexMapping[idx]].getId() == subId ) { return idx;	}
		}
		
		return -1;
	}
	
	this.deleteSubscriptionAt = function(index) {
		if ( index >= 0 && index < this.entriesIndexMapping.length ) {
			var newEntries = new Array(this.entriesIndexMapping.length - 1);
			
			destIdx = 0;
			for ( var srcIdx = 0; srcIdx < this.entriesIndexMapping.length; ++srcIdx ) {
				if ( srcIdx != index ) {
					newEntries[destIdx++] = this.entriesIndexMapping[srcIdx];
				}
			}
			
			this.entriesIndexMapping = newEntries;
		}
	}
	
	this.restoreItemById = function(itemId) {
		var mIdx = -1;
		for ( var idx = 0; idx < this.entries.length; ++idx ) {
			if ( this.entries[idx].getId() == itemId ) { mIdx = idx }
		}
		
		if ( mIdx >= 0 ) {
			// find last element in entriesIndexMapping that refers to any entry before mIdx
			
			var imIdx = this.entriesIndexMapping.length - 1;
			while ( imIdx >= 0 && this.entriesIndexMapping[imIdx] > mIdx ) {
				--imIdx;
			}
			
			// now insert restored index into next position, shifting all following to the right
			++imIdx;
			for ( var idx = this.entriesIndexMapping.length; idx > imIdx; --idx ) {
				this.entriesIndexMapping[idx] = this.entriesIndexMapping[idx - 1];
			}
			this.entriesIndexMapping[imIdx] = mIdx;
		}
	}
	
	this.restoreMarket = function(subscriptionId, packageId, marketId) {
		var subIdx = this.findSubscriptionIndexById(subscriptionId);
		if ( subIdx >= 0 ) {
			this.getSubscription(subIdx).restoreMarket(packageId, marketId)
		}
	}
}

/** data classes end */

/** control classes */

/** class subscription controller */
function wpSubscriptionController() {
	this.availableSubscriptions = new wpAvailableSubscriptions();
	this.cart = new wpCart();
	
	this.getAvailableSubscriptions = function() { return this.availableSubscriptions; }
	this.getCart = function() { return this.cart; }
	
	this.reloadSubscriptionsXml = function(xml) {
		var availSubscriptions = new wpAvailableSubscriptions();
		this.availableSubscriptions = availSubscriptions;
		
		if ( xml.childNodes.length == 1 && xml.childNodes[0].nodeName == 'subscriptions' ) {

			var subscriptionsNode = xml.childNodes[0];
			for ( var i = 0; i < subscriptionsNode.childNodes.length; ++i ) {
				var subscriptionNode = subscriptionsNode.childNodes[i];
				
				if ( subscriptionNode.nodeType == 1 && subscriptionNode.nodeName == 'subscription' ) {
					var isSetupAttrNode = subscriptionNode.attributes.getNamedItem('IsSetup');
					
					if ( isSetupAttrNode == undefined || isSetupAttrNode.nodeValue.toLowerCase() != 'no' ) {
						var isSubscrAvailable = false;

						var subscrStatus = WP_STATE_UNKNOWN;

						var typeCode = parseInt(subscriptionNode.attributes.getNamedItem('TypeNo').nodeValue);
						if ( typeCode == WP_TYPE_PACKAGE ) {
							subscrStatus = parseInt(subscriptionNode.attributes.getNamedItem('Status').nodeValue);
							isSubscrAvailable = ( subscrStatus == WP_STATE_AVAILABLE || subscrStatus == WP_STATE_ORDERING );
						} else if ( typeCode == WP_TYPE_FLEXIBLE ) {
							var availCount = parseInt(subscriptionNode.attributes.getNamedItem('StatusAvailable').nodeValue);
							isSubscrAvailable = ( availCount > 0 );
						}
						if ( isSubscrAvailable ) {
							var sId = parseInt(subscriptionNode.attributes.getNamedItem('WPSubscriptionId').nodeValue);
							var sTitle = subscriptionNode.attributes.getNamedItem('Title').nodeValue;
							var sDescription = subscriptionNode.attributes.getNamedItem('Description').nodeValue;
							var sPrice = parseFloat(subscriptionNode.attributes.getNamedItem('Cost').nodeValue);
						
							var rec = undefined;
							if ( typeCode == WP_TYPE_PACKAGE ) {
								rec = new wpPackageSubscription(sId, sTitle.escapeHTML(), sDescription.escapeHTML(), sPrice);
							} else if ( typeCode == WP_TYPE_FLEXIBLE ) {
								rec = new wpFlexibleSubscription(sId, sTitle.escapeHTML(), sDescription.escapeHTML(), sPrice)
							}
						
							for( var k = 0; k < subscriptionNode.childNodes.length ; ++k ) {
								var packageNode = subscriptionNode.childNodes[k];
								if ( packageNode.nodeType == 1 && packageNode.nodeName == 'package' ) {
									var pId = parseInt(packageNode.attributes.getNamedItem('ProductId').nodeValue);

									var marketsArr = [];
									var marketIdxToDel = [];
									
									for ( var j = 0; j < packageNode.childNodes.length ; ++j ) {
										var objNode = packageNode.childNodes[j];
										if ( objNode.nodeType == 1 && objNode.nodeName == 'object' ) {
											if ( typeCode == WP_TYPE_FLEXIBLE ) {
												var oId = parseInt(objNode.attributes.getNamedItem('MarketId').nodeValue);
												var oCountryId = parseInt(objNode.attributes.getNamedItem('CountryId').nodeValue);
												var oFullName = objNode.attributes.getNamedItem('FullName').nodeValue;
												var oStatus = parseInt(objNode.attributes.getNamedItem('Status').nodeValue);
	
												if ( oStatus == WP_STATE_AVAILABLE || oStatus == WP_STATE_ORDERING ) {
													marketsArr[marketsArr.length] = new wpMarket(oId, oCountryId, oFullName);
													if ( oStatus == WP_STATE_ORDERING ) {
														marketIdxToDel[marketIdxToDel.length] = marketsArr.length - 1;
													}
												}
											} else if ( typeCode == WP_TYPE_PACKAGE ) {
												var oCountryId = parseInt(objNode.attributes.getNamedItem('CountryId').nodeValue);
												rec.addApplicapableCountry(oCountryId);
											}
										}
									
										if ( typeCode == WP_TYPE_FLEXIBLE ) {
											marketsArr.sort(function(m1, m2) { return m1.getFullName().localeCompare(m2.getFullName()); })
									
											rec.addMarkets(pId, marketsArr);
									
											for ( var ii = marketIdxToDel.length - 1; ii >= 0; --ii ) {
												rec.deleteMarketAt(pId, marketIdxToDel[ii]);
											}
										}
									}
								}
							}

							if ( rec != undefined ) {
								availSubscriptions.add(rec);
								if ( subscrStatus == WP_STATE_ORDERING ) {
									availSubscriptions.deleteSubscriptionAt(availSubscriptions.getSubscriptionCount() - 1);
								}
							}
						}
					}
				}
			}
		}
	}
	
	this.reloadCartXml = function(xml) {
		this.cart = new wpCart();
		
		if ( xml.childNodes.length == 1 && xml.childNodes[0].nodeName == 'subscriptions' ) {
			var subscriptionsNode = xml.childNodes[0];
			for ( var i = 0; i < subscriptionsNode.childNodes.length; ++i ) {
				var cartNode = subscriptionsNode.childNodes[i];
				if ( cartNode.nodeType == 1 && cartNode.nodeName == 'cart' ) {
					for ( var j = 0; j < cartNode.childNodes.length; ++j ) {
						var itemNode = cartNode.childNodes[j];
						if ( itemNode.nodeType == 1 && itemNode.nodeName == 'item' ) {
							var iPrice = parseFloat(itemNode.attributes.getNamedItem('Cost').nodeValue);
							var iItemText = itemNode.attributes.getNamedItem('item_text').nodeValue;
							var iItemId = itemNode.attributes.getNamedItem('WPSubscriptionId').nodeValue;
							
							if ( itemNode.attributes.getNamedItem('ProductId') != null ) {
								iItemId += '_' + itemNode.attributes.getNamedItem('ProductId').nodeValue;
								
								if ( itemNode.attributes.getNamedItem('MarketId') != null ) {
									iItemId += '_' + itemNode.attributes.getNamedItem('MarketId').nodeValue;
								}
							}
							
							var iProdName = '';
							var iMarketName = '';
							var re = /^(.*)\/\/(.*)$/;
							var foundArr = re.exec(iItemText);
							if ( foundArr ) {
								iProdName = foundArr[1].replace(/^\s*/, '').replace(/\s*$/, '');
								iMarketName = foundArr[2].replace(/^\s*/, '').replace(/\s*$/, '');
							} else {
								iProdName = iItemText;
								iMarketName = 'Full Subscription';
							}
							
							this.cart.addItem(new wpCartRecord(iItemId, iProdName, iMarketName, iPrice));
						}
					}
				}
			}
		}		
	}
	
	this.addSubscriptionToCart = function(subId) {
		var idx = this.availableSubscriptions.findSubscriptionIndexById(subId);
		
		if ( idx >= 0 ) {
			var subrec = this.availableSubscriptions.getSubscription(idx);
			this.cart.addItem(new wpCartRecord('' + subId, subrec.getTitle(), "Full Subscription", subrec.getPrice()));

			this.availableSubscriptions.deleteSubscriptionAt(idx);
		}
	}
	
	this.addMarketToCart = function(subId, pkgId, marketId) {
		var idx = this.availableSubscriptions.findSubscriptionIndexById(subId);
		
		if ( idx >= 0 ) {
			var subrec = this.availableSubscriptions.getSubscription(idx);
			var pkgArr = subrec.getMarkets()[pkgId];
			if ( pkgArr != null ) {
				var market = null;
				var mIdx = 0;
				while ( mIdx < pkgArr.length && market == null ) {
					if ( pkgArr[mIdx].getId() == marketId ) {
						market = pkgArr[mIdx];
					}
					++mIdx;
				}
				
				if ( market != null ) {
					--mIdx;
					this.cart.addItem(new wpCartRecord('' + subId + '_' + pkgId + '_' + marketId, subrec.getTitle(), market.getFullName(), subrec.getPrice()));
					
					subrec.deleteMarketAt(pkgId, mIdx);
				}
			}
		}
	}
	
	this.deleteItemFromCart = function(itemId) {
		var iIdx = 0;
		while ( iIdx < this.cart.getSize() && this.cart.getItem(iIdx).getItemId() != itemId ) {
			++iIdx;
		}
		
		if ( iIdx < this.cart.getSize() ) {
			var marketName = this.cart.getItem(iIdx).getMarketName();
			
			this.cart.deleteItemAt(iIdx);
			
			var re = /^(\d+)_(\d+)_(\d+)$/;
			var foundArr = re.exec(itemId);
			if ( foundArr ) {
				var subId = parseInt(foundArr[1]);
				var prodId = parseInt(foundArr[2]);
				var marketId = parseInt(foundArr[3]);
				
				this.availableSubscriptions.restoreMarket(subId, prodId, marketId);
			} else {
				this.availableSubscriptions.restoreItemById(itemId);
			}
		}
	}
}

/** control classes end */

/** view classes */


function formatMoney(doubleValue) {
	var str = '' + Math.round(doubleValue * 100); // 10^2 - 2 digits after point
	while ( str.length < 3 ) {
		str = '0' + str;
	}
		
	splitPos = str.length - 2;
	str = str.substring(0, splitPos) + '.' + str.substr(splitPos);
	splitPos -= 3;
	while ( splitPos > 0 ) {
		str = str.substring(0, splitPos) + ',' + str.substr(splitPos);
		splitPos -= 3;
	}
	return '&#8364;' + str;
}
	
/** class cart view */ 
function wpCartView(controller, wlsRootPrefix) {
	this.controller = controller;
	this.wlsRootPrefix = wlsRootPrefix || '';
	
	this.redraw = function(parentElementId) {
		var elem = document.getElementById(parentElementId);
		var resHTML = '';
		resHTML += ' <table class="wp_cart_contents" border="0" cellspacing="0" cellpadding="0" width="100%">';
		
		var cart = controller.getCart();
		resHTML += this.renderSummary(cart);
		resHTML += this.renderSeparator();
		for ( var i = 0; i < cart.getSize(); ++i ) {
			resHTML += this.renderRecord(cart, i);
			resHTML += this.renderSeparator();
		}
		resHTML += '</table>\n';
		
		elem.innerHTML = resHTML;
	}
	
	this.renderSeparator = function() {
		return '<tr><td><hr class="wp_cart" noshade></td></tr>';
	}
	
	this.renderSummary = function(cart) {
		var res = '';
		res += ' <tr><td>';
		res += '	<table cellspacing="0" cellpadding="0" border="0" width="100%"><tr>';
		res += '		<td><img src="' + this.wlsRootPrefix + 'images/subscription.gif" border="0" alt="Submit Order"></td>';
		res += '		<td width="100%">&nbsp;</td>';
		res += '		<td align="right"><p class="wp_cart_summary">' + cart.getSize() + '&nbsp;items</p><p class="wp_cart_summary">Total:&nbsp;' + this.formatMoney(cart.getCost()) + '</p></td>';
		res += '	</tr><tr>';
		res += '		<td colspan="2" width="100%">&nbsp;</td>';
		res += '		<td align="right"><a href="#" onclick="' + WP_CALLBACK_PREFIX + 'submit_order()" onmouseover="roll.on(\'btn_checkout\'); return true;" onmouseout="roll.off(\'btn_checkout\'); return true;"><img id="btn_checkout" src="' + this.wlsRootPrefix + 'images/subscr_checkout.gif" alt="Checkout" border="0"></a></td>';
		res += '	</tr></table>';
		res += '</td></tr>';
		return res;
	}
	
	this.renderRecord = function(cart, recordIdx) {
		var rec = cart.getItem(recordIdx);
		
		var res = '';

		res += '<tr><td>';
		res += '	<input type="hidden" name="arguments[]" value="' + rec.getItemId() + '">';
		res += '	<p class="wp_cart_product">' + rec.getProductName() + '</p>';
		res	+= '	<p class="wp_cart_market">' + rec.getMarketName() + '</p>';
		res += '	<table cellspacing="0" cellpadding="0" border="0" width="100%"><tr>';
		res += '		<td><a href="javascript:" onclick="' + WP_CALLBACK_PREFIX + 'delete_cart_item(\'' + rec.getItemId() + '\')"  onmouseover="roll.on(\'btn_delete__' + rec.getItemId() + '\'); return true;" onmouseout="roll.off(\'btn_delete__' + rec.getItemId() + '\'); return true;"><img id="btn_delete__' + rec.getItemId() + '" src="' + this.wlsRootPrefix + 'images/thrashcan.gif" border="0" alt="Delete Item"></a></td>';
		res += '		<td width="100%">&nbsp;</td>';
		res += '		<td align="right"><p class="wp_cart_summary">' + this.formatMoney(rec.getCost()) + '</p></td>';
		res += '	</tr></table>';
		res += '</td></tr>';
		
		return res;
	}

	/** format currency value (double) to a ready-to-show string */
	this.formatMoney = formatMoney;
}

/** class subscription view */
function wpSubscriptionView(controller, wlsRootPrefix) {
	this.controller = controller;
	this.wlsRootPrefix = wlsRootPrefix || '';
	this.selectedSubscriptionId = WP_ID_UNKNOWN;
	this.countryFilterId = WP_ID_UNKNOWN;
	
	this.setSelectedSubscription = function(subscriptionId) {
		this.selectedSubscriptionId = subscriptionId;
	}

	this.setCountryFilter = function(countryId) {
		this.countryFilterId = countryId;
	}
	
	this.resetCountryFilter = function() {
		this.countryFilterId = WP_ID_UNKNOWN;
	}
	
	this.redraw = function(parentElementId) {
		var elem = document.getElementById(parentElementId);
		var resHTML = '';

		var availSubscrList = controller.getAvailableSubscriptions();
		
		resHTML += '<table class="wp_subscriptions_contents" border="0" cellspacing="0" cellpadding="0" width="100%">';
		var recCount = 0;
		for ( var i = 0; i < availSubscrList.getSubscriptionCount(); ++i ) {
			var record = availSubscrList.getSubscription(i);
			if ( this.countryFilterId == WP_ID_UNKNOWN || record.isCountryApplicapable(this.countryFilterId) ) {
				if ( recCount++ > 0 ) {
					resHTML += this.renderSeparator();
				}
			
				resHTML += this.renderSubscriptionRecord(availSubscrList, i);
			}
		}
		
		resHTML += '</table>';
		
		elem.innerHTML = resHTML;
	}
	
	this.renderSeparator = function() {
		return '<tr><td colspan="3" class="inner_border_v"><img src="' + this.wlsRootPrefix + 'images/s.gif" alt=" "></td></tr>';
	}
	
	this.renderSubscriptionRecord = function(subscrList, index) {
		var record = subscrList.getSubscription(index);
		var res = '';
		
		var isRecordSelected = (record.getId() == this.selectedSubscriptionId || this.countryFilterId != WP_ID_UNKNOWN);
		
		if ( isRecordSelected ) {
			res += '<tr class="selected">';
		} else {
			res += '<tr>';
		}
			
		res += '	<td width="100%">';
		res += '		<img src="' + this.wlsRootPrefix + 'Common/do_subscImage.asp?wpsubscription_id=' + record.getId() + '" align="left" class="wp_subscription_image"><p class="wp_subscription_title">' + record.getTitle() + '</p>';
		res += '		<p class="wp_subscription_description">' + record.getDescription() + '</p>';
		res += '	</td>';
		res += ' 	<td class="inner_border_h"><img src="' + this.wlsRootPrefix + 'images/s.gif" alt=" "></td>'
		res += '	<td class="buttons" align="right" valign="bottom"><p class="wp_subscription_price">' + this.formatMoney(record.getPrice()) + '</p>';
		if ( record.getType() == WP_TYPE_PACKAGE ) {
			var imgHtml = '<img id="btn_add__' + record.getId() + '" src="' + this.wlsRootPrefix + 'images/subscr_addto_btn.gif" border="0" alt="Add to Order" class="wp_subscription_button">';
			res += '<a href="javascript:" onclick="' + WP_CALLBACK_PREFIX + 'add_subscription(' + record.getId() + ')" onmouseover="roll.on(\'btn_add__' + record.getId() + '\'); return true;" onmouseout="roll.off(\'btn_add__' + record.getId() + '\'); return true;">' + imgHtml + '</a>';
		} else if ( record.getType() == WP_TYPE_FLEXIBLE ) {
			var imgHtml = '<img id="btn_select__' + record.getId() + '" src="' + this.wlsRootPrefix + 'images/subscr_select_btn.gif" border="0" alt="Select Market" class="wp_subscription_button">';
			var onClickHtml = isRecordSelected ? '' : 'onclick="' + WP_CALLBACK_PREFIX + 'expand_subscription(' + record.getId() + ')"';
			if ( isRecordSelected ) {
				res += imgHtml;
			} else {
				res += '<a href="javascript:" ' + onClickHtml + ' onmouseover="roll.on(\'btn_select__' + record.getId() + '\'); return true;" onmouseout="roll.off(\'btn_select__' + record.getId() + '\'); return true;">' + imgHtml + '</a>';
			}
		}
		res += '	</td>';
		res += '</tr>';

		
		if ( isRecordSelected && record.getType() == WP_TYPE_FLEXIBLE ) {
			res += this.renderSeparator();
			res += this.renderSubscriptionMarkets(record);
		}

		return res;
	}
	
	this.renderSubscriptionMarketsTableBody = function(subscriptionId, marketsMap) {
		var res = '';
		
		var columnsToUse = 3;
		
		var firstRow = true;

		for ( var packageId in marketsMap ) {
			if ( /^\d+$/.test(packageId) ) { // skip extra attributes (function names?)
				var markets = marketsMap[packageId];
				
				// filter by country if applicapable
				if ( this.countryFilterId != WP_ID_UNKNOWN ) {
					var filteredMarkets = new Array();
					
					for ( var i = 0 ; i < markets.length ; ++i ) {
						if ( markets[i].getCountryId() == this.countryFilterId ) {
							filteredMarkets[filteredMarkets.length] = markets[i];
						}
					}
					
					markets = filteredMarkets;
				}
				
				var marketIdx = 0;
			
				var fullRows = Math.floor(markets.length / columnsToUse);
				var columnsInLastRow = markets.length % columnsToUse;

				if ( ! firstRow ) {
					res += '<tr><td colspan="' + columnsToUse + '"><hr size="1" width="100%" noshade class="wp_package"></td></tr>';
				}
				res += '	<tr>';
				for ( var columnIdx = 0; columnIdx < columnsToUse; ++columnIdx ) {
					res += '		<td valign="top" align="left">';
					for ( var i = 0; i < fullRows; ++i ) {
						res += '<p class="wp_subscription_marketlink"><a href="javascript:" onclick="' + WP_CALLBACK_PREFIX + 'add_market(' + subscriptionId + ',' + packageId + ',\'' + markets[marketIdx].getId() + '\')" class="wp_subscription_marketlink" title="Add to order">' + markets[marketIdx++].getFullName() + '</a></p>';
					}
					if ( columnIdx < columnsInLastRow ) {
						res += '<p class="wp_subscription_marketlink"><a href="javascript:" onclick="' + WP_CALLBACK_PREFIX + 'add_market(' + subscriptionId + ',' + packageId + ',\'' + markets[marketIdx].getId() + '\')" class="wp_subscription_marketlink" title="Add to order">' + markets[marketIdx++].getFullName() + '</a></p>';
					}
					res += '</td>';
				}
				res += '	</tr>';
				firstRow = false;
			}
		}

		return res;
	}
	
	this.renderSubscriptionMarkets = function(subscr) {
		var res = '';

		res += '<tr>';
		res += '	<td width="100%" class="markets">';

		var body = this.renderSubscriptionMarketsTableBody(subscr.getId(), subscr.getMarkets());
		if ( body != '' ) {
			res += '<table border="0" cellspacing="0" cellpadding="0" width="100%">';
			res += body;
			res += '</table>';
		}

		res += '	</td>';
		res += '	<td class="inner_border_h"><img src="' + this.wlsRootPrefix + 'images/s.gif" alt=" "></td>';
		res += '	<td class="buttons" align="right" valign="top"><p class="wp_subscription_helptext">Click on a market to add it to your order</p></td>';
		res += '</tr>';

		return res;
	}
	
	this.formatMoney = formatMoney;
}

/** view classes end */

function wpMakeXmlHttp() {
	var wp_xmlhttp=false;
	try {
		wp_xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			wp_xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			wp_xmlhttp = false;
		}
	}
		
	if (!wp_xmlhttp && typeof XMLHttpRequest!='undefined') {
		wp_xmlhttp = new XMLHttpRequest();
	}

	return wp_xmlhttp;
}
/** helper functions */
function wpUpdateSubscriptionsFromServer(controller, view, cb_home) {
	var wp_xmlhttp = wpMakeXmlHttp();

	wp_xmlhttp.open("GET", cb_home + "Common/wpSupscriptionsInOut.asp?action=getSubscriptions&r="+Math.random(),true);
	wp_xmlhttp.onreadystatechange=function() {
		if ( wp_xmlhttp.readyState == 4 ) {
			controller.reloadSubscriptionsXml(wp_xmlhttp.responseXML);
			view.redraw("subscriptions_container");
		}
	}
	wp_xmlhttp.send(null);
}

function wpUpdateCartFromServer(controller, view, cb_home) {
	var wp_xmlhttp = wpMakeXmlHttp();

	wp_xmlhttp.open("GET", cb_home + "Common/wpSupscriptionsInOut.asp?action=getCart&r="+Math.random(),true);
	wp_xmlhttp.onreadystatechange=function() {
		if ( wp_xmlhttp.readyState == 4 ) {
			controller.reloadCartXml(wp_xmlhttp.responseXML);
			view.redraw("cart_container");
		}
	}
	wp_xmlhttp.send(null);
}

