var mp3_playingId = '';
function mp3player_startPlay(playerID) {
	if ('' != mp3_playingId && mp3_playingId != playerID) {

		var pl = getFlashMovieObject(mp3_playingId);
		pl.mp3player_stopPlay();
	}
	mp3_playingId = playerID;
}

function getFlashMovieObject(movieName)
{
	if (window.document[movieName])
	{
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet") == -1)
	{
		if (document.embeds && document.embeds[movieName])
			return document.embeds[movieName];
	}
	else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
	{
		return document.getElementById(movieName);
	}
}

var InputSelector = Class.create();
InputSelector.prototype = {
	initialize: function(fakeOuter, fakeInner, realInput, listOfValues, selectedListOfValues,
						 popup, view,
						 url, form, formOuter) {


		this.top = 1;
		this.bottom = 0.4;
		this.max = 11;
		this.isCheckAllButtonVisible = true;
		this.version = "InputSelector"

		this.fakeOuter = fakeOuter
		this.fakeInner = fakeInner
		this.realInput = realInput
		this.listOfValues = listOfValues
		this.selectedListOfValues = $H(selectedListOfValues)
		this.popupInputs = $A()

		this.popup = popup || this.createPopupContainer(0, 200);
		this.popupIframe = this.createPopupIframeContainer(0, 200);
		this.popupAutoListener()

		this.doAjax = true;
		this.view = view || {width: 150, count: 1};

		this.searchUrl = url;
		this.form = form;
		this.formOuter = formOuter;

		this.setUpListeners()

		this.startHTML = this.fakeInner.innerHTML;

		this.createDebug();

		this.drawSelectorInput();

	},

	setUpListeners: function() {
		this.fakeOuter.observe('click', function() {
			if (this.popup.getStyle("display") == "none") {
				if (this.doAjax) {
					this.createWaitingEffect(this.top, this.bottom);
					this.createAjaxQuery();
				} else {
					this.drawPopUpElement(this.fakeOuter, this.view);
					this.drawSelectorInput();
				}
			} else {
				this.popup.hide()
			}

		}.bindAsEventListener(this));

	},
	drawSelectorInput: function() {

		var s = "";
		var keys = this.selectedListOfValues.keys()
		this.realInput.value = "";
		for (var i = 0; i < keys.length; i++) {
			s += this.selectedListOfValues.get(keys[i]) + ", "
			this.realInput.value += keys[i] + ","
		}

		this.fakeInner.setAttribute("title", s)

		if (s.length > this.max) {
			s = s.substr(0, this.max) + " ..."
		} else if (s == "") {
			s = this.startHTML
		}
		this.fakeInner.innerHTML = s;


	},
	createAjaxQuery: function() {
		new Ajax.Request(this.searchUrl['url'] + this.searchUrl['param_prefix'] + this.searchUrl['param_value'], {
			onComplete: function(transport) {
				this.doAjax = false;
				this.listOfValues = $H(transport.responseText.evalJSON());

				this.drawPopUpElement(this.fakeOuter, this.view);
				this.createAfterFinishEffect(this.bottom, this.top);
				this.drawSelectorInput();

			}.bindAsEventListener(this)
		})
	},
	createWaitingEffect: function(top, bottom) {
		this.toggleLoading(true)
		new Effect.Opacity(this.formOuter, {from: top, to: bottom, duration: 0.2});

	},
	createAfterFinishEffect: function(from, to) {
		new Effect.Opacity(this.formOuter, {from: from, to: to, duration: 0.2})
		this.toggleLoading(false)
	},
	toggleLoading: function(isVisible) {
		if (this.loader == null) {
			this.loader = new Element('img',
			{
				src:"/images/ajax-loader.gif",
                className: "searchLoader"
			});
			this.formOuter.appendChild(this.loader);
		}

		if (isVisible)
			this.loader.show()
		else
			this.loader.hide()
	},
	rowListener : function(element) {
	}.bindAsEventListener(this),

	setUpOnUpdateListener: function(onUpdateListener) {
		this.onUpdateListener = onUpdateListener;
	},
	createPopupContainer: function(x, y) {
		var element = new Element('div',
		{
			style:'display:none;' +
				  'z-index:1001;' +
				  'position:absolute;' +
				  'left:' + x + "px;" +
				  'top:' + y + "px;"
		});
		document.body.appendChild(element);
		element.addClassName('search_elem_over');

		return element;
	},
	createPopupIframeContainer: function(x, y) {

		var element = new Element('iframe',
		{
			style:'position:absolute; ' +
				  'z-index:1000;' +
				  'display:none;' +
				  'padding:0;margin:0;' +
				  'background:white;' +
				  'left:' + x + "px;" +
				  'top:' + y + "px;" +
				  'border:0',
			src: "/flash/blank.html"
		});
		document.body.appendChild(element);

		return element;
	},

	setSelectedList: function() {

		this.popupInputs = $A(this.popup.select("input"))

		this.popupInputs.each(function(element) {
			if (element.checked) {
				this.selectedListOfValues.set(element.value, this.listOfValues.get(element.value))
				this.drawItemListText(element.value, "disabled");
			} else {
				this.selectedListOfValues.unset(element.value)
				if (element.disabled)
					this.drawItemListText(element.value, "disabled", true);
				else
					this.drawItemListText(element.value, "disabled");
			}
		}.bindAsEventListener(this))
		this.drawSelectorInput()
	},
	clearSelections: function() {
		this.selectedListOfValues = $H();
		this.drawSelectorInput();
	},

	drawItemListText : function(id, obj, needSet) {
		if (needSet) {
			$("span_" + id).addClassName(obj);
		} else {
			$("span_" + id).removeClassName(obj);
		}


	}   ,

	drawPopUpElement: function(parentInput, view) {

		view['count'] = view['count'] || 1;
		view['width'] = view['width'] || 220;
		this.popup.setStyle({
			width: (view['count'] * view['width'] + 2) + "px"
		})


		var s = ""
		s += this.drawMenu();
		s += "<div class='inner_over'> ";
		s += this.drawInputList(view);
		s += "<div class='clearing'> </div>"
		s += "</div>"

		this.popup.hide();
		this.popupIframe.hide();
		this.popup.update(s)
		this.setMenuListener();

		this.popupInputs = $A(this.popup.select("input"));

		this.popupInputs.each(function(element) {
			element.observe('click', function() {
				this.rowListener(element);
				this.setSelectedList()
			}.bindAsEventListener(this))
		}.bindAsEventListener(this))

		var parent_coords = this.getOffset($(parentInput));
		var parent_height = $(parentInput).getHeight();

		this.popup.setStyle({
			top: (parent_coords['top'] + parent_height + 2) + "px",
			left: (parent_coords['left'] + 1) + "px"
		})
		this.popupIframe.setStyle({
			top: (parent_coords['top'] + parent_height + 2) + "px",
			left: (parent_coords['left'] + 1) + "px",

			width: (view['count'] * view['width'] + 2) + "px" ,
			height : (this.popup.getHeight() + 2) + "px"
		})

		Effect.BlindDown(this.popup);
		Effect.BlindDown(this.popupIframe);
    },

    getOffset: function(element){
        var valueT = 0, valueL = 0;
        do {
            if (element.id != "header" && element.id != "global"){
                valueT += element.offsetTop || 0;
            }
            valueL += element.offsetLeft || 0;
            element = element.offsetParent;
        } while (element);
        return Element._returnOffset(valueL, valueT);
    },

	drawMenu : function() {
		this.menu_template = 'selector_template_menu';
		this.menu = $(this.menu_template)
		var s = this.menu.innerHTML
		return s;

	},
	setMenuListener : function() {

		var isCheckAll = this.isCheckAllButtonVisible

		var menu = this.popup.select(".bordered_bottom")[0]

		var close = $(menu.select(".close")[0])
		close.observe('click', function() {
			this.popup.hide();
			this.popupIframe.hide();
		}.bindAsEventListener(this))

		var uncheck = $(menu.select(".none")[0])
		uncheck.observe('click', function() {
			this.uncheckAllAdditionalListener();
			this.uncheckAllListener();
			this.setSelectedList()
		}.bindAsEventListener(this))

		var check = $(menu.select(".all")[0])

		check.setStyle({display: (isCheckAll) ? '' : 'none'})

		check.observe('click', function() {
			this.checkAllListener();
			this.setSelectedList()
		}.bindAsEventListener(this))

	},

	uncheckAllListener: function() {
		this.selectedListOfValues = $H()
		this.drawSelectorInput();

		this.popupInputs.each(function(item) {
			item.checked = false;
			item.disabled = false;
		})
	},
	uncheckAllAdditionalListener: function() {
	},


	checkAllListener: function() {
		this.selectedListOfValues = this.listOfValues
		this.drawSelectorInput();

		this.popupInputs.each(function(item) {
			item.checked = true;
			item.disabled = false;
		})
	},
	drawInputList: function(view) {
		var s = ""


		var tmp = ""
		var tmp1 = ""

		$A(this.listOfValues).each(function(item) {
			tmp = ""
			tmp1 = ""
			s += "<span class='item'>"

			if (this.selectedListOfValues.get(item.key)) {
				tmp = " checked='checked' "
			} else if (this.setDisabled(item.key)) {
				tmp += " disabled='true' ";
				tmp1 = " class='disabled'"
			}
			s += "<input type='checkbox' value='" + item.key + "'" + tmp + " name='" + item.value + "_" + item.key + "'/> "
			s += "<span" + tmp1 + " id=\"span_" + item.key + "\">"
			s += item.value
			s += "</span>"
			s += "</span>"
		}.bindAsEventListener(this))

		return s;
	},


	setDisabled: function(value) {
		return false;
	},
	isAllUnChecked: function() {
		return true;
	},

	popupAutoListener : function() {
		this.popupListening()
		this.windowListening()
	},
	windowListening: function() {
		Event.observe(document.body, 'click', function(event) {
			event.cancelBubble = false;
			this.popup.hide()
			this.popupIframe.hide()
		}.bindAsEventListener(this))
	},
	popupListening: function() {
		Event.observe(this.popup, 'click', function(event) {
			event.cancelBubble = true;
		}.bindAsEventListener(this))
	},
	showVersion: function() {
		window.alert(this.version)
	}  ,
	createDebug: function() {
		this.status = new Element('div',
		{
			style:'position:absolute; z-index:1290;padding:0;margin:0;' +
				  'background:orange;border:0; color:#fff; font-weight:bold;top:0;left:0'
		});
		document.body.appendChild(this.status);
		this.status.update("")
	}

}

var ProductAndCategorySearchSelector = Class.create();

ProductAndCategorySearchSelector.prototype = {
	initialize: function(searchUrl, linked, product_values, category_values, selected) {

		this.linked = $H(linked);

		this.searchUrl = searchUrl;

		this.currentProduct = $H(selected['product']).keys()[0] || 1;


		this.createDebug()
		this.products = $H();
		this.categories = $H();
		this.selectedProducts = $H(selected['product']) || $H();
		this.selectedCategories = $H(selected['category']) || $H();

		this.linked.each(function(item) {
			this.categories.set(item.value, $H());
		}.bind(this))


		this.params = {
			category: "?value=categories&id=",
			product: "?value=products"
		}


		this.productSelector = new InputSelector($(product_values.outer_id), $(product_values.inner_id),
				$(product_values.outer_id).select('input')[0],
				this.products, this.selectedProducts, null, {count: 1, width:220},

		{
			url:this.searchUrl ,
			param_prefix: this.params.product ,
			param_value:""
		}
				, $(product_values.inner_form), $(product_values.outer_form)
				)
		this.productSelector.rowListener = this.rowListener
		this.productSelector.setDisabled = this.setDisabled
		this.productSelector.isAllUnChecked = this.isAllUnChecked
		this.productSelector.uncheckAllAdditionalListener = this.uncheckAllAdditionalListener
		this.productSelector.isCheckAllButtonVisible = false;

		this.categorySelector = new InputSelector($(category_values.outer_id), $(category_values.inner_id),
				$(category_values.outer_id).select('input')[0],
				this.categories.get(this.linked.get(this.currentProduct)), this.selectedCategories, null, {count: 4, width:160},
		{
			url:this.searchUrl ,
			param_prefix: this.params.category ,
			param_value:this.currentProduct
		}
				, $(category_values.inner_form), $(category_values.outer_form)
				)


		this.productSelector.categories = this.categories;

		this.productSelector.linked = this.linked;
		this.productSelector.categorySelector = this.categorySelector;


		this.productSelector.baseProduct = "1";
		this.productSelector.baseCategoryOfProduct = this.linked.get(this.productSelector.baseProduct);

		this.productSelector.selectedProduct = this.currentProduct;
		this.productSelector.selectedCategoryOfProduct = this.linked.get(this.currentProduct);

	},
	uncheckAllAdditionalListener: function() {
		//this.categories.set(this.selectedProduct, this.categorySelector.listOfValues)

		this.selectedProduct = this.baseProduct
		this.selectedCategoryOfProduct = this.baseCategoryOfProduct;

		var equal = this.categorySelector.listOfValues.keys().length == this.categories.get(this.selectedCategoryOfProduct).keys().length

		if (equal)
			for (var i = 0; i < this.categorySelector.listOfValues.keys(); i++) {
				var key = this.categorySelector.listOfValues.keys()[i]
				equal = this.categorySelector.listOfValues.get(key) == this.categories.get(this.selectedCategoryOfProduct).get(key)
				if (!equal) break;
			}

		this.categorySelector.searchUrl['param_value'] = this.selectedProduct;
		this.categorySelector.listOfValues = this.categories.get(this.selectedCategoryOfProduct)
		if (!equal) {
			this.categorySelector.uncheckAllListener();
		}

	},

	setDisabled: function(value) {

		if (this.selectedListOfValues.keys().length > 0) {
			return !(this.linked.get(value) == this.linked.get(this.selectedProduct))

		} else return false;

	},

	isAllUnChecked: function() {
		var exist = true;
		for (var i = 0; i < this.popupInputs.length; i++) {
			if (this.popupInputs[i].checked) {
				exist = false;
				break;
			}
		}
		return exist;
	},

	rowListener : function(element) {

		//put loaded list to hash from "memory"
		var memoryProduct = this.selectedCategoryOfProduct;
		this.categories.set(memoryProduct, this.categorySelector.listOfValues)

		this.selectedProduct = element.value;
		this.selectedCategoryOfProduct = this.linked.get(this.selectedProduct);


		if (this.isAllUnChecked()) {
			//default state
			for (var i = 0; i < this.popupInputs.length; i++) {
				this.popupInputs[i].disabled = false;
			}
			this.selectedProduct = this.baseProduct
			this.selectedCategoryOfProduct = this.baseCategoryOfProduct;

		} else {
			//disable products with unlinked categories
			for (var i = 0; i < this.popupInputs.length; i++) {
				this.popupInputs[i].disabled = this.linked.get(this.popupInputs[i].value) != this.linked.get(this.selectedProduct);
			}
		}
		//set up params
		this.categorySelector.searchUrl['param_value'] = this.selectedProduct;


		this.categorySelector.doAjax = this.categories.get(this.selectedCategoryOfProduct).keys().length == 0;
		this.categorySelector.listOfValues = this.categories.get(this.selectedCategoryOfProduct)

		if (memoryProduct != this.selectedProduct) {
			this.categorySelector.uncheckAllListener();
		}
	}
	,
	createDebug: function() {
		this.status = new Element('div',
		{
			style:'position:absolute; z-index:1290;padding:0;margin:0;' +
				  'background:orange;border:0; color:#fff; top:0;left:0'
		});
		document.body.appendChild(this.status);
		this.status.update("")
	}
	,

	createPopupContainer: function(x, y) {
		var element = new Element('div',
		{
			style:'display:none;' +
				  'position:absolute;' +
				  'left:' + x + "px;" +
				  'top:' + y + "px;"
		});
		document.body.appendChild(element);
		element.addClassName('search_elem_over');
		return element;
	}
}

var HeaderProductAndCategorySearchSelector = Class.create(ProductAndCategorySearchSelector);
var AdvansedProductAndCategorySearchSelector = Class.create(ProductAndCategorySearchSelector);

var AuthorSearchSelector = Class.create();
AuthorSearchSelector.prototype = {

	initialize: function(searchUrl, selectedAuthors, author_values) {
		this.authors = $H();
		this.searchUrl = searchUrl;
		this.selectedAuthors = $H(selectedAuthors) || $H();
		this.authorSelector = new InputSelector($(author_values.outer_id), $(author_values.inner_id),
				$(author_values.outer_id).select('input')[0],
				this.authors, this.selectedAuthors, null, {count: 4, width: 160},
		{
			url:this.searchUrl ,
			param_prefix: "?value=authors" ,
			param_value:""
		}
				, $(author_values.inner_form), $(author_values.outer_form)
				)

	}
}

var LeftCategoryToggle = Class.create();
LeftCategoryToggle.prototype = {
	initialize: function(products, options, debug) {

		this.debug = debug

		if (this.debug || true) {
			this.createDebug();
		}


		this.products = products;

		this.options = Object.extend(this.prepareElementsIdsNames(), options);

		this.product = {};
		this.no_empty = {};
		this.toggle = {};
		this.toggleAll = {};

		$A(this.products).each(function(workProductNumber) {
			this.prepareAllListsForProduct(workProductNumber)
		}.bind(this))
		$A(this.products).each(function(workProductNumber) {
			this.attachObservers(workProductNumber)
		}.bind(this))

		this.setupAllGroups();
	},
	setupAllGroups: function() {
		if (this.options.currentProduct != "") {
			setCookie("left_product_" + this.options.currentProduct, "all")
		}
	} ,
	createDebug: function() {
		this.status = new Element('div',
		{
			style:'position:absolute; z-index:1290;padding:0;margin:0;background:orange;border:0; ' +
				  'color:#fff; font-weight:bold;top:0;'
		});
		document.body.appendChild(this.status);
		this.status.update("")
	} ,

	putDebug: function(s) {
		$(this.status).update($(this.status).innerHTML + s)
	} ,

	prepareElementsIdsNames: function() {
		return {
			currentProduct : "",
			productGroup: {
				prefix: "product",
				suffix: "_group"
			},
			noEmptyGroup: {
				prefix: "no_empty_product",
				suffix: "_group"
			},
			toggleAll: {
				prefix: "product",
				open_suffix: "_open_all",
				close_suffix: "_close_all"
			},
			toggle: {
				prefix: "product",
				open_suffix: "_open",
				close_suffix: "_close"
			}
		}
	},

	prepareAllListsForProduct: function(workProductNumber) {
		this.product[workProductNumber] = $(this.options.productGroup['prefix'] + workProductNumber + this.options.productGroup['suffix'])

		this.toggle[workProductNumber] = {}
		this.toggleAll[workProductNumber] = {}

		try {
			this.no_empty[workProductNumber] = $(this.options.noEmptyGroup['prefix'] + workProductNumber + this.options.noEmptyGroup['suffix'])

			this.toggle[workProductNumber]["close"] = $(this.options.toggle['prefix'] + workProductNumber + this.options.toggle['close_suffix'])
			this.toggle[workProductNumber]["open"] = $(this.options.toggle['prefix'] + workProductNumber + this.options.toggle['open_suffix'])

		} catch(e) {

		}

		if (this.debug) {
			this.putDebug(workProductNumber)
		}

		this.toggleAll[workProductNumber]['close'] = $(this.options.toggleAll['prefix'] + workProductNumber + this.options.toggleAll['close_suffix'])
		this.toggleAll[workProductNumber]['open'] = $(this.options.toggleAll['prefix'] + workProductNumber + this.options.toggleAll['open_suffix'])
	},


	attachObservers: function(work_product_number) {
		this.attachObserversForTopToggleButton(work_product_number);
		this.attachObserversForBottomToggleButton(work_product_number);
	},

	attachObserversForTopToggleButton: function(work_product_number) {

		this.toggleAll[work_product_number]["close"].observe('click', function() {

			Effect.BlindUp(this.product[work_product_number], {duration:0.2})

			this.toggleAll[work_product_number]["close"].hide();
			this.toggleAll[work_product_number]["open"].show();

			try {
				this.toggle[work_product_number]["open"].hide();
				this.toggle[work_product_number]["close"].hide();
			} catch(e) {
			}


			setCookie("left_product_" + work_product_number, "none")

		}.bind(this))

		this.toggleAll[work_product_number]["open"].observe('click', function() {


			if (this.product[work_product_number].getStyle("display") == "none") {
				try {
					this.no_empty[work_product_number].show();
					this.toggle[work_product_number]["close"].show();
				} catch(e) {
				}
				Effect.BlindDown(this.product[work_product_number], {duration:0.2});

			} else {
				try {
					if (this.no_empty[work_product_number].getStyle("display") == "none") {
						this.toggle[work_product_number]["close"].show();
						Effect.BlindDown(this.no_empty[work_product_number], {duration:0.2});
					}
				} catch(e) {
				}

			}


			this.toggleAll[work_product_number]["open"].hide();
			this.toggleAll[work_product_number]["close"].show();

			try {
				this.toggle[work_product_number]["open"].hide();
				this.toggle[work_product_number]["close"].show();
			} catch(e) {
			}

			setCookie("left_product_" + work_product_number, "all")

		}.bind(this))
	},

	attachObserversForBottomToggleButton: function(work_product_number) {

		try {
			this.toggle[work_product_number]["close"].observe('click', function() {
				Effect.BlindUp(this.no_empty[work_product_number], {duration:0.2})
//				this.toggle[work_product_number]["open"].show();
				this.toggle[work_product_number]["close"].hide();


				this.toggleAll[work_product_number]["close"].hide();
				this.toggleAll[work_product_number]["open"].show();

				setCookie("left_product_" + work_product_number, "", -1)

			}.bind(this))

			this.toggle[work_product_number]["open"].observe('click', function() {

				Effect.BlindDown(this.no_empty[work_product_number], {duration:0.2});
				this.toggle[work_product_number]["open"].hide();
				this.toggle[work_product_number]["close"].show();

				this.toggleAll[work_product_number]["open"].hide();
				this.toggleAll[work_product_number]["close"].show();

				setCookie("left_product_" + work_product_number, "all")
			}.bind(this))
		} catch(e) {
		}
	}

}

var LanguageToggle = Class.create();
LanguageToggle.prototype = {
	initialize: function(toggle_button, lang_list, lang_corners, debug) {

		this.debug = debug
		if (this.debug) {
			this.createDebug();
		}

		this.buttonBuy = $(toggle_button)
		this.list = $(lang_list)
		this.corners = $(lang_corners)

		$(this.list).setStyle({display: "none"})

		if (this.debug) {
			this.putDebug($(this.list).style.display)
		}

		this.attachObservers()

	},
	createDebug: function() {
		this.status = new Element('div',
		{
			style:'position:absolute; z-index:1290;padding:0;margin:0;' +
				  'background:orange;border:0; color:#fff; font-weight:bold;top:0;'
		});
		document.body.appendChild(this.status);
		this.status.update(" ")
	} ,
	putDebug: function(s) {
		$(this.status).update($(this.status).innerHTML + s)
	} ,

	attachObservers: function() {
		this.attachObserverToButton()
		this.attachObserverToBody()
	},

	attachObserverToBody: function() {
		Event.observe(document.body, 'click', function(event) {
			event.cancelBubble = false;
			this.closeList()
		}.bindAsEventListener(this))
	},

	attachObserverToButton: function() {
		if ($(this.list).childElements().length > 0) {
			$(this.buttonBuy).observe('click', function(event) {
				if (this.list.getStyle("display") == "none") {
					this.openList()
				} else {
					this.closeList()
				}
			}.bindAsEventListener(this))
		}
	},
	openList : function() {
		this.corners.hide()
		Effect.SlideDown(this.list, {duration:0.2})
	},
	closeList : function() {
		this.list.hide()
		this.corners.show()
	}

}

var ItemTooltipList = Class.create({

	initialize: function(items1, items2, host) {
		this.items = $$("." + items1)
		this.descriptionItems = $$("." + items2)
		this.host = host || ""
        var id = 0;
		$A(this.items).each(function(item) {
			this.setBigPreview(item, id);
            id++;
		}.bind(this))


		$A(this.descriptionItems).each(function(item) {
			this.setAjaxPreview(item)
		}.bind(this))

	},
	setAjaxPreview: function(item) {
		var loading = "<img src='/images/groupview-loader.gif'/> Loading ..."
		new ToolTip(item, loading, {className : "darktip"}, this.host + '/jsonPopup.jhtml?type=groupview&viewId=' + item.getAttribute("viewid"))

	},
	setBigPreview: function(item, id) {
		try {
			var data = item.getAttribute("name").evalJSON();
			var fullInnerHTML = '';
			var line;

			fullInnerHTML += "<p class='bold align_center' style='width:" + data[0] + "px'>" + data[2] + " #" + data[3] + "</p>";

			fullInnerHTML += "<div class='loading_preview' id='line_" + id + "-" +data[3] + "'>Loading...<br/><div class='loading_out'><div class='loading_in' style='width:50px;'> </div></div></div>";

			fullInnerHTML += "<div class='align_center'  style='width:" + data[0] + "px;height:" + data[1] + "px;'><img onload=\"clearInt()\" src='" + data[4] + "' alt='" + data[5] + "' title='" + data[6] + "'/></div>";


			var tooltip = new ToolTip(item, fullInnerHTML, {className : "image_preview", delay:2000});
			tooltip.onStartAction = function() {
				loader('loading_in', 'loading_out', "line_" + id + "-" + data[3]);
			}
			tooltip.onOutAction = function() {
				clearInt();
			}
		} catch(e) {

		}
	}
})

var inner_loading;
var outer_loading;
var full_loading;
var timer;

function loader(in_id, out_id, full) {
	try {
		full_loading = $(full)
		inner_loading = $$("#" + full + " ." + in_id)[0];
		outer_loading = $$("#" + full + " ." + out_id)[0];

		full_loading.style.display = "";
		timer = setInterval("move()", 30);
	} catch(e) {

	}
}
function move() {
	try {
		if (inner_loading.offsetLeft >= outer_loading.clientWidth) {
			inner_loading.style.left = "-" + inner_loading.getStyle("width")
		} else {
			inner_loading.style.left = (inner_loading.offsetLeft + 6) + "px"
		}
	} catch(e) {
	}
}
function clearInt() {
	try {
		full_loading.style.display = "none";
		inner_loading.style.left = "-" + inner_loading.style.width;
		clearInterval(timer);
	} catch(e) {
	}
}


var DownloadList = Class.create({
	initialize: function(messages, column, url, template, autoRefresh) {
		this.messages = $H(messages)
		this.autoRefresh = autoRefresh
		this.doTooltips();


		this.url = url;
		this.template = new Template(template.innerHTML, /(^|.|\r|\n)(\#\s*(\w+)\s*#)/);
		this.forAjaxItems = $$("." + column);
		this.timer = {}

		this.doAjax();
	}	   ,

	doTooltips: function() {
		this.messages.each(function(type) {
			var className = "." + type.key
			this.items = $$(className)
			var text = $(type.value).innerHTML
			$A(this.items).each(function(item) {
				new ToolTip(item, text, {className : "darktip"});
			}.bind(this))
		}.bind(this))
	}  ,

	doAjax : function() {
		var timeInMili = 1000 * this.autoRefresh;
		this.timer = setInterval(function() {
			this.doAjaxItems()
		}.bind(this), timeInMili)

	},

	doAjaxItems : function() {
		var ids = new Array();
		var index = 0;

		$A(this.forAjaxItems).each(function(item) {
			ids[index++] =  item.id;
		}.bind(this))

		if (ids.length > 0) {
			new Ajax.Request(this.url, {
				method: 'post',
				parameters:{"ids" : ids.toJSON()},
				onComplete: function(transport) {
					this.onCompleteItems(transport.responseText.evalJSON())
				}.bindAsEventListener(this)
			})
		}
	}   ,

	onCompleteItems : function(data) {
		$A(data).each(function(item) {
			var s = "";
			item['closePassword'] = ""

			if (item['error'] != null) {
				Window.location = "/";
			} else {
				if (item['archivePassword'] == null || item['archivePassword'] == "" || item['archivePassword'] == "empty") {
					item['closePassword'] = "display_none"
				}
				s = this.template.evaluate(item);
				$(item["id"]).update(s);
			}
		}.bind(this))
	}
})

var TransactionStatusRefresher = Class.create({
	initialize: function(operationId, timeout, url, status) {
		this.operationId = operationId;
		this.timeout = timeout;
		this.status =  status;
		this.url = url;
		this.timer = {};
		this.startTimer();
	},
	startTimer : function() {
		var timeInMili = 1000 * this.timeout;
      	this.timer = setInterval(function() {
			this.onTimer();
		}.bind(this), timeInMili);
	},
    setInitialText:function(status){
        if ((status == "Purchases Approved" || status == "Subscription") && $("orderInfoText")){
            this.setVisibleElement(false, "orderInfoText");
        }
    },
	onTimer : function() {
		new Ajax.Request(this.url, {
			method: 'post',
			parameters:{"operationId" : this.operationId, "status" : this.status} ,
			onComplete: function(transport) {
				this.onRequest(transport.responseText.evalJSON());
			}.bindAsEventListener(this)
		});
	},
	onRequest: function(data) {
        if (data['error'] != null) {
            window.location = "/";
        } else {
            if (data["status"] != this.status) {
                this.status = data["status"];
                this.setInitialText(this.status);
                if (data["view"] != null) {
                    $(this.operationId).update(data["view"]);
                }
                if (data["topText"] != null) {
                    $("topText").update(data["topText"]);
                }
                if (data["bottomText"] != null) {
                    $("bottomText").update(data["bottomText"]);
                }
                fix_height_for_ie6('finances_transact_block');
            }
            if ((data["isContinue"] != null) && (data["isContinue"] == "false")) {
                clearInterval(this.timer);
            }
        }
    },
    setVisibleElement: function(visible, elementId) {
        if (visible) {
            document.getElementById(elementId).style.display = 'block';
        } else {
            document.getElementById(elementId).style.display = 'none';
        }
    }
});

var ComplectationList = Class.create({
	initialize: function(url, prefix, list, total, balance, balanceAfter, purchaseLink, list_outer) {
		this.prefixUrl = url
		this.prefix = prefix
		this.list = $$("." + list)
		this.total = (total == "") ? total : $(total)
		this.balance = (balance == "") ? balance : $(balance)
		this.balanceAfter = (balanceAfter == "") ? balanceAfter: $(balanceAfter)
        this.purchaseLink = (purchaseLink == "") ? purchaseLink: $(purchaseLink)
        this.outer = $(list_outer)

		$A(this.list).each(function(item) {
			item.onclick = function() {
				this.waitingEffect()
				this.remove(item.title)
				return false;
			}.bindAsEventListener(this)
		}.bind(this))


	},
	waitingEffect: function() {

		new Effect.Opacity(this.outer, {from: 1.0, to: 0.2, duration: 0.2});

		if (this.loader == null) {
			this.loader = new Element('img',
			{
				src:"/images/ajax-loader.gif",
				style:'position:absolute; top:50%;left:50%; display:block;margin-left:-25px;margin-top:-12px;'
			});
			this.outer.appendChild(this.loader);
		}
		this.loader.show()
	}   ,
	remove : function(item) {
		new Ajax.Request(this.prefixUrl + item + ".html", {
			onComplete: function(transport) {
				this.onRemoveComplete(transport.responseText, item)
				this.endEffect()
			}.bindAsEventListener(this),
			onFailure: function() {
				this.endEffect()
			}.bindAsEventListener(this)
		})
	} ,
	onRemoveComplete : function(result, item) {

		if (result.empty()) {
			window.location.reload()
		} else {
			try {
				var json = result.evalJSON(true);
				if (this.total) {
					this.total.update(json.total);
				}
				if (this.balance) {
					this.balance.update(json.balance);
				}
				if (this.balanceAfter) {
					this.balanceAfter.update(json.balanceAfter);
				}
                if (this.purchaseLink) {
                    this.purchaseLink.href = json.purchaseLink;
                }
            } catch(e) {

            }

			$(this.prefix + item).remove()
		}


	} ,
	endEffect : function() {
		this.loader.hide()
		new Effect.Opacity(this.outer, {from: 0.2, to: 1, duration: 0.2});

	}

})


var PriceTable = Class.create({
	initialize: function(outer, block, radios, list, url, trId) {
		this.outer = outer;
	if (!$(this.outer)) {
		return;
	}
		this.block = $(block);

		this.popupList = $$("." + list)

		this.url = url;


		this.trs = $A($(this.outer).select("tr"));
		this.trs = this.trs.without(this.trs[0]);
		this.radios = Form.getInputs($(this.outer), 'radio', radios);

		this.popupListener()
		this.rowListener()
	}  ,

	popupListener : function() {
		$A(this.popupList).each(function(item) {
			var loading = "<img src='/images/groupview-loader.gif'/> Loading ..."
			new ToolTip(item, loading, {className : "darktip"}, this.url + '?viewId=' + item.getAttribute("viewid"))
		}.bindAsEventListener(this))
	} ,

	rowListener : function() {

		for (var i = 0; i < this.trs.length; i++) {
			var item = this.trs[i];
			item.observe('click', function(item) {

				item.select("input")[0].checked = true;

				var position = $A(this.trs).indexOf(item);
				var index = 0;
				this.trs.each(function(tr) {
					var fw = "selected-price"

					if (index == position) {
						$(tr).addClassName(fw)
					} else {
						$(tr).removeClassName(fw)
					}

					index++;
				})
				fix_height_for_ie6(this.block)
			}.bind(this, item))


		}
	} ,

	getRadioValue : function(radios) {
		try {
			return radios.find(function(radio) {
				return radio.checked;
			}).value
		} catch(e) {

		}
		return null;
	}

})

function emailChecking(email) {
    //See module XmlRpcSerials, class EmailParser for details

//    var regEMail = /^[a-zA-Z0-9-_\.&\'*+/=?^{}~]+\@([a-zA-Z0-9-_]+\.)+[a-zA-Z]+$/;
    var regEMail = /^[\w\-\'\~\_\.\*\/=\^\{\}\?\+\!\#\$\%\&\`\|]+[\@][\w\_\.\-]+[\.][\w]{2,6}$/i;

    if ((email == '') || (email.length > 100) || (regEMail.exec(email) == null) || (email.substr(email.lastIndexOf('@') + 1, 1) == '.')) {
        return false;
    }

    var name = email.substring(0, email.indexOf('@'));

    if ((email.indexOf('..') > 0) || (name[0] == '.') || (name[name.length - 1] == '.')) {
        return false;
    }

    return true;
}

function onClickPreSubscribe() {
	try {
		var input = $('subscribeFormEmail');
		var error = {};
		error['invalid'] = $('subscribeFormEmailInvalid');
		error['empty'] = $('subscribeFormEmailEmpty');

		if (input.value.empty()) {
			error['empty'].style.display = ""
			error['invalid'].style.display = "none"
		} else
			if (emailChecking(input.value)) {
				error['empty'].style.display = "none"
				error['invalid'].style.display = "none"
				$('subscribeForm').submit();
			} else {
				error['invalid'].style.display = ""
				error['empty'].style.display = "none"
			}


		fix_height_for_ie6('subscribeFormBlock')
		return false;
	} catch(e) {

	}

}
function onClickSubscribe() {
	try {
		var checkbox = $('confirmCheckBox');
		var submit = $('onClickSubscribeSubmit');

		var checked = false;
		var checkedStr = '<img src="/images/check.gif" style="margin-top:-1px;"/>';

		try {
			checkbox.observe("click", function(event) {
				//alert(checked+" ")
				if (checked) {
					checked = false;
					checkbox.innerHTML = ""
				} else {
					checked = true;
					checkbox.innerHTML = checkedStr
					checkbox.removeClassName("error_checkbox")
				}

			})
		} catch(e) {
			alert(e)
		}

		try {
			submit.onclick = function() {
				if (checked) {
					$('subscribeForm').submit();
					return false;
				} else {
					checkbox.addClassName("error_checkbox")

				}
			}
		} catch(e) {
			alert(e)
		}


	} catch(e) {

	}

}
function getElementHeight(element){
    var elementHeight = 0;
    var elementsArray = element.childNodes;
    for (var i = 0; i < elementsArray.length; i++) {
        if (elementsArray[i].id != "left" && elementsArray[i].id != "footer" && elementsArray[i].id != "about_us_text"){
            elementHeight = elementHeight + elementsArray[i].offsetHeight;
        }
    }


    if (navigator.userAgent.indexOf("MSIE") != -1){
        if (document.getElementById("flashPlayer-membership")){
            elementHeight = elementHeight - 22;
        } else {
            elementHeight = elementHeight - 17;
        }
    }
    return elementHeight;
}

function calculateHeight(){
    if($('aboutBlock') && ($('aboutBlock').style.display = 'none')){
        var cartHeight = $('shoppingCart').offsetHeight;
        $('aboutBlock').style.display = 'block';
        $('aboutBlock').style.position = 'absolute';
        $('aboutBlock').style.top = cartHeight + 20 + 'px';
        $('aboutBlock').style.marginRight = 15 + 'px';

        var aboutHeight = $('aboutBlock').offsetHeight;
        var innerContentHeight = $('contentBlock').offsetHeight;
        var rightBlocksHeight = aboutHeight + cartHeight;
        if (innerContentHeight < rightBlocksHeight){
            $('content').style.height = rightBlocksHeight + 30 + 'px';
        } else {
            $('content').style.height = innerContentHeight + 20 + 'px';
        }

    }
}

var AjaxLoader = Class.create();
AjaxLoader.prototype = {
    initialize: function() {
        this.loader = new Element('img', {
            src:'/images/ajax-loader.gif'
        });

        this.loader_width = 400;

        this.container = new Element('div');

        this.container.className = 'ajaxloader';
        this.container.id = 'loader-container';

        this.container.appendChild(this.loader);
        this.textBlock = new Element('div');
        this.textBlock.className = 'loader-text';

        this.textBlock.innerHTML = "Loading, please wait...";
        this.container.appendChild(this.textBlock);
        document.body.appendChild(this.container);
    },

    show: function() {
        var windowOffsetX = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft || 0;
        var windowOffsetY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop || 0;

        var height = window.innerHeight  || document.documentElement.clientHeight;
        var positionY = height / 2 + windowOffsetY;

        this.container.style.top = positionY + "px";

        var width = window.innerWidth ||  document.documentElement.clientWidth;
        var positionX = (width / 2 + windowOffsetX) - this.loader_width/2;
        this.container.style.left = positionX  + "px";

        this.container.setOpacity(1);
        this.container.style.display = 'block';
    },

    hide: function(duraction) {
        if (arguments.length == 0) {
            duraction = 2;
        }
        Effect.Fade(this.container, {duration: duraction});
    }
}

var Cart = Class.create();
Cart.prototype = {
	initialize: function() {
        this.not_enough_credits_id = "not_enough_credits";
        this.loader = new AjaxLoader();
        this.itemsCount = 0;
    },

    addToCart:function(itemNumber) {
        var self = this;
        this.loader.show();
        new Ajax.Request("/cart-add-" + itemNumber + ".html", {
			method: 'post',
			onComplete: function(transport) {
                var response = transport.responseText.evalJSON();
                self.itemsCount = response.cartItemsCount;

                $(itemNumber).innerHTML = locales['added_to_cart'];
                $(itemNumber).className = "in_cart";

                var cart_list = $('cart_list');

                if(cart_list == null) {
                    $("empty_cart_note").remove();
                    self.createCartTable();
                }

                $('cart_list').getElementsByTagName("tbody")[0]
                        .appendChild(this.createCartRow(response.item));

                var total_div = $('total_cart');

                if(total_div == null) {
                    total_div = new Element("div");
                    total_div.id="total_cart";
                    total_div.className="total_cart";

                    $("cartBlock").appendChild(total_div);
                }

                total_div.innerHTML = locales['cart_message_total'].replace("{0}",response.total_in_cart);

                self.addAlertMessage(response.userMembershipState);
                self.updateDownloadButton(response);
                calculateHeight();
                this.loader.hide();
			}.bindAsEventListener(this)
		});
    },

    removeFromCart:function(itemNumber) {
        var self = this;
        this.loader.show();
        new Ajax.Request("/cart-remove-" + itemNumber + ".html", {
            method: 'post',
            onComplete: function(transport) {
                var response = transport.responseText.evalJSON();
                self.itemsCount = response.cartItemsCount;

                $(itemNumber + "-r").remove();

                var cart_list = $('cart_list');
                var elements = cart_list.getElementsByTagName("tr");

                var cart_total_message_box = $("total_cart");

                if(self.itemsCount == 0) {
                    self.clearCartList();
                } else{
                    cart_total_message_box.innerHTML = locales['cart_message_total'].replace("{0}",response.total_in_cart);
                    self.addAlertMessage(response.userMembershipState);
                }

                self.appendAddToCartButton(response.item);
                self.updateDownloadButton(response);
                calculateHeight();
                this.loader.hide();
            }.bindAsEventListener(this)
        });
    },

    updateDownloadButton:function(response) {
        var addBtn = false;
        var download_button = $("download_button");

        if(download_button == null) {
            download_button = new Element();
            download_button.setAttribute("id", "download_button");
            download_button.setAttribute("class", "button");
            download_button.setAttribute("rel", "nofollow");
            addBtn = true;
        }

        if(response.cartItemsCount != 0) {
            switch (response.userMembershipState) {
                case 'DOWNLOADS_ALLOWED': {
                    download_button.setAttribute("href", "/user_profile/buy_cart.jhtml");
                    break;
                }

                case 'NO_MEMBERSHIP': {
                    download_button.setAttribute("href", buyMembershipLink);
                    break;
                }

                case "NO_USER": {
                    download_button.setAttribute("href", loginLink);
                    download_button.onclick = function(){
                        return wac_ajax_popup(this.href, 'Log In');
                    };
                    break;
                }

                default:{
                    download_button.onclick = "";
                    download_button.setAttribute("href", "#");
                    break;
                }
            }
        }

        if(addBtn) {
           $("buttons").appendChild(download_button);
        }
    },

    addAlertMessage:function(userstate) {
        if(userstate == 'NOT_ENOUGH_DOWNLOAD_POINTS' &&
                    $(this.not_enough_credits_id) == null) {

                var message = new Element("p");
                message.id = this.not_enough_credits_id;
                message.className = "note";
                message.innerHTML = locales['not_enough_credits'];

                $("total_cart").appendChild(message);
        }
    },

    createCartTable:function() {
        var tbody = new Element("tbody");
        var cartTable = new Element("table", {
            id:"cart_list", cellspacing:"0", cellpadding:"0"
        });

        cartTable.appendChild(tbody);
        $("cartBlock").appendChild(cartTable);
    },

    createCartMessage:function(){
        var message = new Element("div", {id : "empty_cart_note"});
        message.appendChild(document.createTextNode(locales['empty_cart_note']));
        return message;
    },

    createFlashPlayer:function(item) {
        var flashPlayerId= "flashPlayer-cart-" + item.itemNumber;
        var URL = "/flash/player_small.swf?trackPath=" + item.imageSmallUrl + "&playerID=" + flashPlayerId;

        var player = new Element("object");
        player.setAttribute("id","flashPlayer-cart-" + item.itemNumber);
        player.setAttribute("width", "115");
        player.setAttribute("height", "38");
        player.setAttribute("codebase", "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0");
        player.setAttribute("classid", "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000");

        var param1 = new Element("param", {
           name: "movie",
           value: URL
        });

        var param2 = new Element("param", {
           name:"wmode", value:"transparent"
        });

        var embed = new Element("embed");
        embed.setAttribute("width", "115");
        embed.setAttribute("height", "38");
        embed.setAttribute("name", flashPlayerId);
        embed.setAttribute("wmode", "transparent");
        embed.setAttribute("swliveconnect", "true");
        embed.setAttribute("type", "application/x-shockwave-flash");
        embed.setAttribute("pluginspage", "http://www.macromedia.com/go/getflashplayer");
        embed.setAttribute("src", URL);

        player.appendChild(param1);
        player.appendChild(param2);

        if(navigator.userAgent.indexOf("MSIE") != -1) {
            return embed;
        }

        player.appendChild(embed);

        return player;
    },

    createCartRow:function(item) {
        var href = new Element("a", {href : item.url});
        var link = document.createTextNode(item.productTypeSingle + " #" + item.productNumber);
        href.appendChild(link);

        var info_item = new Element('td');
        info_item.className = "info_item";

        info_item.appendChild(href);
        info_item.appendChild(this.createFlashPlayer(item));

        var itemPrice = new Element('td');
        itemPrice.className = "price_remove";

        var divRemove = new Element('div');
        divRemove.className = "remove";

        var hrefRemove = new Element('a', {
            href : "/cart-remove-" + item.itemNumber + ".html"
        });

        hrefRemove.onclick = function() {
            cart.removeFromCart(item.itemNumber);
            return false;
        }

        var imageRemove = new Element('img', {
            src : "/images/close.jpg", alt : ""
        });

        hrefRemove.appendChild(imageRemove);
        divRemove.appendChild(hrefRemove);
        itemPrice.appendChild(divRemove);

        var itemRow = new Element('tr',{
            id: item.itemNumber + "-r"
        });
        itemRow.appendChild(info_item);

        var price_content = new Element("span");
        price_content.innerHTML = item.price + ' ' + locales['cart_credits'];
        var paragraph = new Element("p");
        paragraph.appendChild(price_content);

        itemPrice.appendChild(paragraph);
        itemRow.appendChild(itemPrice);

        return itemRow;
    },

    clearCartList:function() {
        var cart_list = $('cart_list');

        if(cart_list != null) {
            cart_list.remove();
        }

        var cart_total_message_box = $("total_cart");

        if(cart_total_message_box != null) {
            cart_total_message_box.remove();
        }

        $("cartBlock").appendChild(this.createCartMessage());

        var download_button = $("download_button");
        download_button.onclick = "";
        download_button.setAttribute("href", "#");

    },

    appendAddToCartButton:function(item) {
        var tr = $(item.itemNumber);

        if (tr == null) {
            return;
        }

        //tr.className = "";
        tr.className = "button_td";
        tr.innerHTML = "";

        var span3 = new Element('span');
        span3.onclick = function() {
            cart.addToCart(item.itemNumber);
            return false;
        }

        span3.className = "button";

        var span2 = new Element('span');
        span2.className = "button_left";

        var span1 = new Element('span');
        span1.className = "button_right";

        span3.appendChild(span2);
        span2.appendChild(span1);
        span1.appendChild(document.createTextNode(locales['add_to_cart']));

        $(item.itemNumber).appendChild(span3);
    },

    empty:function() {
        if(this.itemsCount == 0) {
            return;
        }

        var self = this;
        this.loader.show();
        new Ajax.Request("/cart_empty.jhtml", {
            method: 'post',
			onComplete: function(transport) {
                self.itemsCount = 0;
                self.loader.container.style.display = "none";
                self.clearCartList();
                var response = transport.responseText.evalJSON();
                response.each(function(item){
                    var cell = $(item.itemNumber);
                    if(cell != null) {
                        self.appendAddToCartButton(item);
                    }
                });

                var not_enough_credits = $(self.not_enough_credits_id);

                if(not_enough_credits != null) {
                    not_enough_credits.remove();
                }
                calculateHeight();
            }.bindAsEventListener(this)
        });
    }
}
