ms247.isPlayerWindow = false;
ms247.MSH 			 = new Object();
ms247.Toolkit 		 = new TFSToolkit();
ms247.FlashMaster 	 = new TFSFlashHandler();
ms247.LayerHandler   = new TFSLayerHandler(shopBaseUrl + '&page=layer');
//ms247_MCSLayerBridge = new TFSLayerHandler(shopBaseUrl + '&page=layer');

function startsWith(haystack, needle) {
	return (haystack.substr(0, needle.length) == needle);
}



/***************************************************************************************************
 *  SNIPPETS ***************************************************************************************
 **************************************************************************************************/
ms247.snippets = {};
ms247.snippets.UpdateBasketIfNecessary = function() {
	if (jQuery("#minibasket").exists()) {
		ms247.snippets.Basket(true);
	}
}
ms247.snippets.Basket = function(showLoadingIndicator, loadingIndicatorHtml) {
	if (showLoadingIndicator) {
		if (loadingIndicatorHtml == '') {
			loadingIndicatorHtml = jQuery("#ajax_loader");
		}
		jQuery("#minibasket").html(loadingIndicatorHtml);
	}
	jQuery.get(shopBaseUrlAjax + "&page=ajax/cart/minibaskethtml", null, function(loadedHtml, textStatus) {
		jQuery("#minibasket").html(loadedHtml);
	}, "html");
}


/***************************************************************************************************
 *  INITIALIZATION *********************************************************************************
 **************************************************************************************************/
/*
function ms247initSearch() {
	if (jQuery("#suchebox").exists()) {
		jQuery(function() {
			//alert('Suche Autocomplete Setup!');
		    setAutoComplete("suchebox", "results", shopBaseUrlAjax + "&page=search/autocomplete&searchcrit=");
		});
	}
}
*/


function jqueryUIAutocomplete() {
	jQuery('input[name="suchebox"]').autocomplete({
		source: shopBaseUrlAjax + "&page=search/uiautocomplete",
		minLength: 2,
		cache: false,
		select: function( event, ui ) {
			window.location= shopBaseUrlAjax +"&page=search/results&searchcrit="+ui.item.value;
		}
	});
}

function ms247initRatingStars() {
	//Rating STars
	jQuery(function(){
		jQuery("#starify").children().not(":input").hide();
		jQuery(".multiField_disabled").children().not(":input").hide();
		
		// Create stars from :radio boxes
		jQuery("#starify").stars({
			cancelShow: false,
			oneVoteOnly: true,
			showTitles: true,
			callback: function(ui, type, value){
				if (value.indexOf(",") > -1) {
		    		var splitted = value.split(",");
		    		var lmid = splitted[1];
		    		var rating   = splitted[0];
		    	}
				//alert(lmid +' rated: '+ rating);
				jQuery.ajax({
			        type: 		"GET",
			        dataType: 	"json",
			        url: 		shopBaseUrlAjax + "&page=ajax/rating_update&rating="+rating+"&lmid="+lmid,
			        async: 		true, // we need to call this synchronously, to block Browser's and user's activity!
			        cache:      false,
			        success: function(result){
			    		if (result.status == 0) {
			    			//alert('rated:'+ result.rated);
			    		}
			    		
			        }
			    });
			}
		});
		jQuery("#starify").show();
		// Create stars from :radio boxes
		jQuery(".multiField_disabled").stars({
			cancelShow: false,
			oneVoteOnly: true,
			disabled: true,
			callback: function(ui, type, value){
				if (value.indexOf(",") > -1) {
		    		var splitted = value.split(",");
		    		var lmid = splitted[1];
		    		var rating   = splitted[0];
		    	}
				//alert(lmid +' rated: '+ rating);
				jQuery.ajax({
			        type: 		"GET",
			        dataType: 	"json",
			        url: 		shopBaseUrlAjax + "&page=ajax/rating_update&rating="+rating+"&lmid="+lmid,
			        async: 		true, // we need to call this synchronously, to block Browser's and user's activity!
			        cache:      false,
			        success: function(result){
			    		if (result.status == 0) {
			    			//alert('rated:'+ result.rated);
			    		}
			    		
			        }
			    });
				
			}
		});
		jQuery(".multiField_disabled").show();
	});
}

function ms247LayerAccordion(cssSelector) {
	jQuery(cssSelector + ".collapsingList dd").hide();
	jQuery(cssSelector + ".collapsingList dt.open").next().show();
	jQuery(cssSelector + ".collapsingList dt").click(function() {
		if (jQuery(this).hasClass("open")) {
			jQuery(this).removeClass("open");
			jQuery(this).next().hide();
		} else {
			jQuery(this).addClass("open");
			jQuery(this).next().show();
		}
	});
}

/***************************************************************************************************
 * DYNAMIC CONTENT HANDLING ************************************************************************
 **************************************************************************************************/
//TODO dst: check if AjaxHandler can also be a "real Object" which defines GetLoaderObject, ShowLoading as "Base Methods". But the rest must still be working the same like now!
//ms247.AjaxHandler = new Object();
ms247.AjaxHandler 							= new TFSAjaxHandlerBase();
ms247.AjaxHandler.Charts 					= new TFSAjaxHandlerCharts(); 
ms247.AjaxHandler.NewReleases 				= new TFSAjaxHandlerNewReleases(); 
ms247.AjaxHandler.Genres 					= new TFSAjaxHandlerGenres(); 
ms247.AjaxHandler.AudiobooksFrontpage 		= new TFSAjaxHandlerAudiobooksFrontpage();
ms247.AjaxHandler.AudiobooksDetailpage 		= new TFSAjaxHandlerAudiobooksDetailpage();

//TODO mp: we need to take that out when updating to 1.1
var isAudioBookPage = 'false';

function TFSAjaxHandlerBase() {
	this.GetLoaderObject = function() {
		return jQuery("#ajax_loader");
	}
	this.ShowLoading = function(settings) {
	    var containerObject = null;
	    if (settings.object != null) {
	    	containerObject = settings.object;
	    } else {
	    	containerObject = jQuery(settings.id);
	    }
		containerObject.html(this.GetLoaderObject().html());
		containerObject.show();
	}

	this.LoadHTML = function(fullurl, tabId, containerId) {
		return this.LoadHTML(fullurl, tabId, containerId, false);
	}

	this.LoadHTML = function(fullurl, tabId, containerId, sync) {
	    if (fullurl == null) return;
	    if (fullurl == "") return;
	    
	    var contentType = '';
		//alert(isAudioBookPage);
		if(isAudioBookPage == 'true'){
			contentType='audiobook';
	    	fullurl += "&content=" + contentType;
	    }
		//alert(fullurl);
	    //var tabObject 			= jQuery(tabId);
		var containerObject 	= jQuery(containerId);
	
	    // show loading...
	    ms247.AjaxHandler.ShowLoading({'object': containerObject});
	    // load content from server...

	    jQuery.ajax({
	        type:       "GET",
	        dataType:   "html",
	        url:        fullurl,
	        async:      !sync,
	        success: function(result) {
	    		//alert(result);
	    		containerObject.html(result);
	    		init247_eventHandler("#"+containerId+" ");
	        },
	        error: function (XMLHttpRequest, textStatus, errorThrown) {
	      	    this; // the options for this ajax request
	      	}
	    });
	}
	
	this.LoadOverviewAudiobooksHTML = function(containerId, limit) {
		var fullurl = shopBaseUrlAjax + '&page=audiobooks/overviewcontent';
	    if (fullurl == null) return;
	    if (fullurl == "") return;
	    
	    
	    //Add a limitation
	    if (limit != null){
	    	fullurl += "&limit=" + limit;
	    }
	    
	    var contentType = '';
		//alert(isAudioBookPage);
		if(isAudioBookPage == 'true'){
			contentType='audiobook';
	    	fullurl += "&content=" + contentType;
	    }
		//alert(fullurl);
	    	//var tabObject 			= jQuery(tabId);
		var containerObject 	= jQuery(containerId);
	
	    // show loading...
	    ms247.AjaxHandler.ShowLoading({'object': containerObject});
	    // load content from server...

	    jQuery.ajax({
	        type:       "GET",
	        dataType:   "html",
	        url:        fullurl,
	        async:      true,
	        success: function(result) {
	    		//alert(result);
	    		containerObject.html(result);
	    		init247_eventHandler("#"+containerId+" ");
	        },
	        error: function (XMLHttpRequest, textStatus, errorThrown) {
	      	    this; // the options for this ajax request
	      	}
	    });
	}
}

function TFSAjaxHandlerCharts() {
	this.URLs = new Object();
	this.URLs["tab-hoerbuch"] 		= "&page=ajax/chartstab&lmtype=audiobook&view=audiobook";
	this.URLs["tab-autoren"] 		= "&page=ajax/chartstab&lmtype=audiobook&view=artist";
	this.URLs["tab-sprecher2"] 		= "&page=ajax/chartstab&lmtype=audiobook&view=speaker";
	this.URLs["tab-manuelle1"] 		= "&page=ajax/chartstab&lmtype=audiobook&view=category1";
	this.URLs["tab-manuelle2"] 		= "&page=ajax/chartstab&lmtype=audiobook&view=category2";
	this.URLs["tab-albums"] 		= "&page=ajax/chartstab&lmtype=album&view=albums";
	this.URLs["tab-tracks"] 		= "&page=ajax/chartstab&lmtype=track&view=tracks";
	this.URLs["tab-videos"] 		= "&page=ajax/chartstab&lmtype=video&view=videos";
	this.URLs["tab-interpreten"] 	= "&page=ajax/chartstab&view=artists";
	this.URLs["tab-manucategory"] 	= "&page=ajax/chartstab&view=category";
	
	this.LoadTab = function(tabId, tabHandler) {
		if (this.URLs[tabId] != null) {
			ms247.AjaxHandler.LoadHTML(appendPageContextIfNecessary(shopBaseUrlAjax + this.URLs[tabId]), "#" + tabId, "#box-" + tabId);
	    	tabHandler.addLoadedTab(tabId);
	    	return true;
	    }
		return false;
	}
}

function TFSAjaxHandlerNewReleases() {
	this.URLs = new Object();
	this.URLs["tab-diesewoche"] 	= "&page=ajax/newlmtab&view=current";
	this.URLs["tab-letztewoche"] 	= "&page=ajax/newlmtab&view=last";
	this.URLs["tab-vor2wochen"] 	= "&page=ajax/newlmtab&view=2weeksago";
	this.URLs["tab-vor3wochen"] 	= "&page=ajax/newlmtab&view=3weeksago";
	this.URLs["tab-vorschau"] 		= "&page=ajax/newlmtab&view=preview";
	
	this.URLs["tab-ab-diesewoche"] 	= "&page=ajax/newlmtab&view=ab_current";
	this.URLs["tab-ab-letztewoche"] = "&page=ajax/newlmtab&view=ab_last";
	this.URLs["tab-ab-vor2wochen"] 	= "&page=ajax/newlmtab&view=ab_2weeksago";
	this.URLs["tab-ab-vor3wochen"] 	= "&page=ajax/newlmtab&view=ab_3weeksago";
	this.URLs["tab-ab-vorschau"] 	= "&page=ajax/newlmtab&view=ab_preview";

	this.LoadTab = function(tabId, tabHandler) {
		if (this.URLs[tabId] != null) {
			ms247.AjaxHandler.LoadHTML(appendPageContextIfNecessary(shopBaseUrlAjax + this.URLs[tabId]), "#" + tabId, "#box-" + tabId);
	    	tabHandler.addLoadedTab(tabId);
	    	return true;
	    }
		return false;
	}
}

function TFSAjaxHandlerGenres() {
	this.URLs = new Object();
	this.URLs["tab-topalben"] 			= "&page=ajax/genretab&lmtype=album&view=albums";
	this.URLs["tab-toptracks"] 			= "&page=ajax/genretab&lmtype=track&view=tracks";
	this.URLs["tab-topvideos"] 			= "&page=ajax/genretab&lmtype=video&view=videos";
	//this.URLs["tab-tophoerbuch"] 		= "&page=ajax/genretab&lmtype=audiobook&view=audiobook";
	//this.URLs["tab-topautoren"] 		= "&page=ajax/genretab&lmtype=audiobook&view=artists";
	this.URLs["tab-topinterpereten"] 	= "&page=ajax/genretab&view=artists";
	this.URLs["tab-klassiker"] 			= "&page=ajax/genretab&view=classic";
	this.URLs["tab-empfehlungen"] 		= "&page=ajax/genretab&view=recomm";
    
	this.LoadTab = function(tabId, tabHandler) {
		if (this.URLs[tabId] != null) {
			//alert(tabId);
			//alert(this.URLs[tabId]);
			ms247.AjaxHandler.LoadHTML(appendPageContextIfNecessary(shopBaseUrlAjax + this.URLs[tabId] + "&genre=" + jQuery("#genreId").text()), "#" + tabId, "#box-" + tabId);
	    	tabHandler.addLoadedTab(tabId);
	    	return true;
	    }
		return false;
	}
}


function TFSAjaxHandlerAudiobooksFrontpage() {

	this.URLs = new Object();
	this.URLs["tab-tophoerbuch"] 		= "&page=ajax/genretab&lmtype=audiobook&view=audiobook&content=audiobook";
	this.URLs["tab-topautoren"] 		= "&page=ajax/genretab&lmtype=audiobook&view=artists&content=audiobook";
	this.URLs["tab-sprecher2"] 		= "&page=ajax/chartstab&lmtype=audiobook&view=speaker";
	this.URLs["tab-manuelle1"] 		= "&page=ajax/chartstab&lmtype=audiobook&view=category1";
	this.URLs["tab-manuelle2"] 		= "&page=ajax/chartstab&lmtype=audiobook&view=category2";
    
	this.LoadTab = function(tabId, tabHandler) {
		if (this.URLs[tabId] != null) {
			//alert(tabId);
			//alert(this.URLs[tabId]);
			ms247.AjaxHandler.LoadHTML(appendPageContextIfNecessary(shopBaseUrlAjax + this.URLs[tabId] + "&genre=" + jQuery("#genreId").text()), "#" + tabId, "#box-" + tabId);
	    	tabHandler.addLoadedTab(tabId);
	    	return true;
	    }
		return false;
	}
}

function TFSAjaxHandlerAudiobooksDetailpage() {

	this.URLs = new Object();
	//this.URLs["tab-inhalt"] 			= "&page=ajax/chartstab&lmtype=audiobook&view=content";
	this.URLs["tab-kapitel"] 			= "&page=ajax/chartstab&lmtype=artist&view=artists";
	//this.URLs["tab-autor"] 				= "&page=ajax/allesvon&artistid=";
	this.URLs["tab-sprecher"] 			= "&page=ajax/chartstab&lmtype=speaker&view=speakers";

	this.LoadTab = function(tabId, tabHandler) {
		if (this.URLs[tabId] != null) {
			//alert(tabId);
			//alert(this.URLs[tabId]);
			ms247.AjaxHandler.LoadHTML(appendPageContextIfNecessary(shopBaseUrlAjax + this.URLs[tabId]), "#" + tabId, "#box-" + tabId);
	    	tabHandler.addLoadedTab(tabId);
	    	return true;
	    }
		return false;
	}
}


ms247.AjaxHandler.LoadArtistReleases = function(limitDesc, tabId, containerId, lmtype) {
	if (limitDesc == null) return;
    if (limitDesc == "") return;
    var fullurl = shopBaseUrlAjax + "&page=ajax/allesvon&artistid=" + limitDesc;
    if(lmtype != ""){
    	fullurl = fullurl + "&lmtype=" + lmtype;
    }
    
	ms247.AjaxHandler.LoadHTML(fullurl, tabId, containerId);
}
ms247.AjaxHandler.LoadEdchoice = function(edchoiceID, tabId, containerId) {
	if (edchoiceID == null) return;
	if (edchoiceID == "") return;
	ms247.AjaxHandler.LoadHTML(shopBaseUrlAjax + "&page=ajax/edchoicetab&id=" + edchoiceID, tabId, containerId);
}
ms247.AjaxHandler.LoadMyDownloads = function(containerId) {
	var lmtype = "all"
	if (containerId == "#box-tab-audiobooks"){
		lmtype = "audiobook";
	}
	ms247.AjaxHandler.LoadHTML(shopBaseUrlAjax + "&page=ajax/my/downloads&lmtype="+lmtype, "", containerId, true);
}


// ACTION EVENTHANDLING /-//////////////////////////////////////////////////////////////////////////
ms247.AjaxHandler.HandleShoppingActionAsync = true;
ms247.AjaxHandler.ShopCart 			= new TFSShopCartEventHandling();
ms247.AjaxHandler.Wishlist 			= new TFSWishlistEventHandling();
ms247.AjaxHandler.PreOrderSelection = new TFSPreOrderSelectionEventHandling();

function TFSShopCartEventHandling() {
	this.Add = function(updateid, mouse_event, settings) {
		if (updateid == null) return;
		if (updateid == "") return;

		if (settings == null) {
			settings = defaultSettings;
		}

		jQuery.ajax({
	        type: 		"POST",
	        dataType: 	"json",
	        url: 		shopBaseUrlAjax + "&page=ajax/cart/update",
	        data:       "type=add&updateid=" + updateid,
	        async: 		ms247.AjaxHandler.HandleShoppingActionAsync,
	        success: function(result){
	    		if (result.status == 0) {
	    			ms247.SSOClientMCS.updateShopCartCount(result.newProductCount);
	    			TooltipHelper.show247Tooltip("#shopcart_add_ok", mouse_event, settings);
	    			ms247.snippets.UpdateBasketIfNecessary();
	    			callback_execute(mouse_event, settings);
	    		} else {
	    			TooltipHelper.show247Tooltip("#general_action_error", mouse_event, defaultErrorTooltipSettings);
	    		}
	        },
		    error: function(request, textStatus, errorThrown) {
	        	TooltipHelper.show247Tooltip("#general_action_error", mouse_event, defaultErrorTooltipSettings);
		    }
	    });
	}

	this.Remove = function(updateid, mouse_event, settings) {
		if (updateid == null) return null;
		if (updateid == "") return null;
	
		if (settings == null) {
			settings = defaultSettings;
		}

		jQuery.ajax({
	        type: 		"POST",
	        dataType: 	"json",
	        url: 		shopBaseUrlAjax,
	        data:       "page=ajax/cart/update&type=remove&updateid="+updateid,
	        async: 		ms247.AjaxHandler.HandleShoppingActionAsync,
	        success: function(result) {
				if (result.status == 0) {
					ms247.SSOClientMCS.updateShopCartCount(result.newProductCount, ms247.CallBackHandler.ShopCartCountUpdatedInSSO);
					callback_execute(mouse_event, settings);
				} else {
					TooltipHelper.show247Tooltip("#general_action_error", mouse_event, defaultErrorTooltipSettings);
				}
	        }
	    });
	}

	this.MoveToWishlist = function(cartupdateid, wishlistupdateid, mouse_event, settings) {
		if (cartupdateid == null) return null;
		if (cartupdateid == "") return null;
		if (wishlistupdateid == null) return null;
		if (wishlistupdateid == "") return null;
	
		// 1. add to wishlist
		if (settings == null) {
			settings = defaultSettings;
		}
	
		// add callback to execute next step (remove from cart)
		settings.callback 		= "ms247.CallBackHandler.RemoveFromCart";
		settings.cartupdateid 	= cartupdateid;
		//settings.distanceX      = 0;
	
		ms247.AjaxHandler.Wishlist.Add(wishlistupdateid, mouse_event, settings);
	}
}

function TFSWishlistEventHandling() {
	this.Add = function(updateid, mouse_event, settings) {
		if (settings == null) {
			settings = defaultSettings;
		}

		jQuery.ajax({
	        type: 		"POST",
	        dataType: 	"json",
	        url: 		shopBaseUrlAjax + "&page=ajax/wishlist/update",
	        data:		"type=add&updateid=" + updateid,
	        async: 		ms247.AjaxHandler.HandleShoppingActionAsync,
	        success: function(result){
		    	if (result.status == 0) {
		    		//alert("OK. Der Artikel befindet sich nun auf ihrer Merkliste.");
		    		TooltipHelper.show247Tooltip("#wishlist_add_ok", mouse_event, settings);
		    		callback_execute(mouse_event, settings);
		    	} else {
		    		TooltipHelper.show247Tooltip("#general_action_error", mouse_event, defaultErrorTooltipSettings);
		    	}
		    },
		    error: function(request, textStatus, errorThrown) {
		    	TooltipHelper.show247Tooltip("#general_action_error", mouse_event, defaultErrorTooltipSettings);
		    }
	    });
	}
	this.Remove = function(updateid, mouse_event, settings) {
		if (updateid == null) return null;
		if (updateid == "") return null;

		if (settings == null) {
			settings = defaultSettings;
		}

		// leaving this callback set ends in a loop - happens if triggered by "ms247.AjaxHandler.Wishlist.MoveToShopCart"
		if (settings.callback == "ms247.CallBackHandler.RemoveFromWishlist") {
			settings.callback = "";
		}
	    jQuery.ajax({
	        type: 		"POST",
	        dataType: 	"json",
	        url: 		shopBaseUrlAjax + "&page=ajax/wishlist/update",
	        data:       "type=remove&updateid=" + updateid,
	        async: 		ms247.AjaxHandler.HandleShoppingActionAsync,
	        success: function(result) {
	    		ms247.CallBackHandler.RemovedFromWishlist(mouse_event, settings);
				callback_execute(mouse_event, settings);
		    },
		    error: function(request, textStatus, errorThrown) {
		    	TooltipHelper.show247Tooltip("#general_action_error", mouse_event, defaultErrorTooltipSettings);
		    }
	    });
	}
	this.MoveToShopCart = function(SelectionUpdateid, cartupdateid, mouse_event, settings) {
		if (SelectionUpdateid == null) return null;
		if (SelectionUpdateid == "") return null;
		if (cartupdateid == null) return null;
		if (cartupdateid == "") return null;
	
		if (settings == null) {
			settings = defaultSettings;
		}
		settings.wishlistUpdateId = SelectionUpdateid;
		if (settings.callback == null) {
			settings.callback = "ms247.CallBackHandler.RemoveFromWishlist";
		}
		ms247.AjaxHandler.ShopCart.Add(cartupdateid, mouse_event, settings);
		return false;
	}
}

function TFSPreOrderSelectionEventHandling() {
	this.Add = function(updateid, mouse_event, settings) {
		if (updateid == null) return null;
		if (updateid == "")   return null;

		if (settings == null) {
			settings = defaultSettings;
		}
		settings.distanceX -= 80;
		settings.distanceY += 80;

		jQuery.ajax({
	        type: 		"POST",
	        dataType: 	"json",
	        url: 		shopBaseUrlAjax + "&page=ajax/preorderselection/update",
	        data:       "type=add&updateid=" + updateid,
	        async: 		ms247.AjaxHandler.HandleShoppingActionAsync,
	        success: function(result) {
		    	if (result.status == 0) {
		    		TooltipHelper.show247Tooltip("#preorder_add_ok", mouse_event, settings);
		    	} else {
		    		TooltipHelper.show247Tooltip("#general_action_error", mouse_event, defaultErrorTooltipSettings);
		    	}
				return false;
		    },
		    error: function(request, textStatus, errorThrown) {
		    	TooltipHelper.show247Tooltip("#general_action_error", mouse_event, defaultErrorTooltipSettings);
		    }
	    });
		return false;
	}
	this.Remove = function(updateid, mouse_event, settings) {
		if (updateid == null) return null;
		if (updateid == "")   return null;

		if (settings == null) {
			settings = defaultSettings;
		}

	    jQuery.ajax({
	        type: 		"POST",
	        dataType: 	"json",
	        url: 		shopBaseUrlAjax + "&page=ajax/preorderselection/update",
	        data:       "type=remove&updateid=" + updateid,
	        async: 		ms247.AjaxHandler.HandleShoppingActionAsync,
	        success: function(result) {
	    		ms247.CallBackHandler.RemovedFromPreOrderSelection(mouse_event, settings);
				return false;
		    },
		    error: function(request, textStatus, errorThrown) {
		    	ms247.CallBackHandler.RemovedFromPreOrderSelection(mouse_event, settings);
		    	return false;
		    }
	    });
		return false;
	}
	this.MoveToWishlist = function(preOrdersSelectionUpdateid, wishlistupdateid, mouse_event, settings) {
		if (preOrdersSelectionUpdateid == null) return null;
		if (preOrdersSelectionUpdateid == "") return null;
		if (wishlistupdateid == null) return null;
		if (wishlistupdateid == "") return null;
	
		// 1. add to wishlist
		if (settings == null) {
			settings = defaultSettings;
		}
		if (settings.callback == null) {
			settings.preOrdersSelectionUpdateid = preOrdersSelectionUpdateid;
			settings.callback = "ms247.CallBackHandler.RemoveFromPreOrderSelection";
		}
		ms247.AjaxHandler.Wishlist.Add(wishlistupdateid, mouse_event, settings);
	}
	this.MoveToCart = function(preOrdersSelectionUpdateid, cartupdateid, mouse_event, settings) {
		if (preOrdersSelectionUpdateid == null) return null;
		if (preOrdersSelectionUpdateid == "") return null;
		if (cartupdateid == null) return null;
		if (cartupdateid == "") return null;

		if (settings == null) {
			settings = defaultSettings;
		}

		jQuery.ajax({
	        type: 		"GET",
	        dataType: 	"json",
	        url: 		shopBaseUrlAjax + "&page=ajax/cart/update&type=add&updateid="+cartupdateid,
	        async: 		ms247.AjaxHandler.HandleShoppingActionAsync,
	        success: function(result){
	    		if (result.status == 0) {
	    			TooltipHelper.show247Tooltip("#shopcart_add_ok", mouse_event, settings);
	    			ms247.SSOClientMCS.updateShopCartCount(result.newProductCount);
	    			ms247.AjaxHandler.PreOrderSelection.Remove(preOrdersSelectionUpdateid, mouse_event, settings);
	    			return false;
	    		} else {
	    			TooltipHelper.show247Tooltip("#general_action_error", mouse_event, defaultErrorTooltipSettings);
	    		}
		    },
		    error: function(request, textStatus, errorThrown) {
		    	TooltipHelper.show247Tooltip("#general_action_error", mouse_event, defaultErrorTooltipSettings);
		    }
	    });
		return false;
	}
}

/***************************************************************************************************
 *  PAGING  ****************************************************************************************
 **************************************************************************************************/
function changePageSize(containerId, formId) {
	if (formId == "") {
		formId = "#change_pagesize";
	}
    var urlParameters = buildURLForPageSizeSwitch(formId);
    urlParameters += "&pg=1"; // always jump to the first page...

    if (containerId == "") {
    	// simply build a URL and reload the whole page
		var form_action = jQuery(formId).attr("action");
		if (form_action == "") return; // avoid redirecting to empty or invalid url
	    location.href = form_action + urlParameters;
    } else {
    	// we're inside a tab and shall change the page size using ajax
	    ms247.AjaxHandler.ShowLoading({'id': containerId});
		if (shopBaseUrlAjax == "") return; // avoid redirecting to empty or invalid url
	    GetHTMLIntoBlock(shopBaseUrlAjax + urlParameters, containerId);
    }
}
function changeGenre(formId, isAudiobook) {
	var form_action = jQuery(formId).attr("action");
	if (form_action == "") return; // avoid redirecting to empty or invalid url
	var page = "genre";
	var content = "";
	if (isAudiobook == "true"){
		page = "audiobooks/genre";
		var content = "&content=audiobook";
	}
    location.href = form_action + "&page="+page+"&genre=" + jQuery(formId+ " select[name='genre']").val()+content;
}

function changeLMType(containerId, formId) {
	changePageSize(containerId, formId);
}
function GetHTMLIntoBlock(fullUrlString, containerId) {
	if (fullUrlString.indexOf("search/results")>-1) { // if search page make sure no ts is added /MB
		GetHTMLIntoBlockCached(fullUrlString,containerId);
		return false;
	}
	
	jQuery.get(fullUrlString, function(response) {
    	jQuery(containerId).html(response);
		init247_eventHandler("#"+containerId+" ");
    }, "html");
}

function GetHTMLIntoBlockCached(fullUrlString, containerId) {
	jQuery.ajax({
        type: 		"GET",
        dataType: 	"html",
        url: 		fullUrlString,
        async: 		true, 
        cache:      true,
        success: function(result){
    		jQuery(containerId).html(result);
    		init247_eventHandler("#"+containerId+" ");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
      	}
    });
}

function buildURLForPageSizeSwitch(formId) {
    var urlParameters = "";

    // Patch formId if necessary...
    if (!startsWith(formId, "#") && !startsWith(formId, ".")) {
    	formId = "#" + formId;
    }
    // append all input fields and dropdowns...
    jQuery(formId).find("input").each(function() {
		urlParameters += "&" + jQuery(this).attr("name") + "=" + jQuery(this).val();
    });
    jQuery(formId).find("select").each(function() {
		urlParameters += "&" + jQuery(this).attr("name") + "=" + jQuery(this).val();
    });

    return appendPageContextIfNecessary(urlParameters);
}
function appendPageContextIfNecessary(urlParameters) {
    // if there's a context defined append it to the url, too...
    if (jQuery("#pgcontext").exists()) {
    	if (urlParameters.indexOf("&context") == -1) {
    		urlParameters += "&context=" + jQuery("#pgcontext").text();
    	}
    }
    return urlParameters;
}
function tabJumpTo(urlprefix, pagenum, containerId) {
    if (TooltipHelper.currTooltip != null) TooltipHelper.hideTooltip();
    if (containerId == null) {
    	containerId = "#box-tab-all-from";
    }

    ms247.AjaxHandler.ShowLoading({'id': containerId});
    var urlForSnippet = appendPageContextIfNecessary(shopBaseUrlAjax + "&page=" + urlprefix + "&pg=" + pagenum);
    //alert("AudiobookPage : " + isAudioBookPage);
    if(isAudioBookPage == 'true'){
		contentType='audiobook';
		urlForSnippet += "&content=" + contentType;
    }
    //alert('tabJumpTo:'+ urlForSnippet);
    GetHTMLIntoBlock(urlForSnippet, containerId);
    return false;
}

function tabJumpToSearch(urlprefix, pagenum, containerId, newCrit) {
    if (TooltipHelper.currTooltip != null) TooltipHelper.hideTooltip();
    if (containerId == null) {
    	containerId = "#box-tab-all-from";
    }

    ms247.AjaxHandler.ShowLoading({'id': containerId});
    var urlForSnippet = shopBaseUrlAjax + "&page=" + urlprefix + "&pg=" + pagenum + "&searchcrit=" + newCrit;

    if(isAudioBookPage == 'true'){
		contentType='audiobook';
		urlForSnippet += "&content=" + contentType;
    }
    //alert('tabJumpToSearch:'+ urlForSnippet);
    GetHTMLIntoBlock(urlForSnippet, containerId);
    return false;
}

/***************************************************************************************************
 *  GENERAL HELPERS ********************************************************************************
 **************************************************************************************************/
/* helper used to get paging for page-changes work with same logic as the tab-handlers */
function gotoPage() {
	return true;
}


/***************************************************************************************************
 * LAYER HANDLING **********************************************************************************
 **************************************************************************************************/
function TFSLayerHandler(layerProviderUrl) {
	// LAYER IDs
	this.MUSIC_TERMS 				= { type: 'tfs', id: 'TFS_terms_and_conditions' };
	this.MUSIC_PRIVACY_STATEMENT 	= { type: 'tfs', id: 'TFS_data_privacy_protection' };
	this.MUSIC_FAQ					= { type: 'tfs', id: 'TFS_faq' };
	this.MCS_HELP					= { type: 'mcs', id: 'overview' };
	this.MCS_TERMS					= { type: 'mcs', id: 'terms' };
	this.CONTACT					= { type: 'mcs', id: 'contact' };

	this.GotoSite = function(destination) {
		if (destination == 'kontakt' || destination == 'contact') {
			return this.OpenLayer(this.CONTACT);
		}
		if (destination == 'hilfe') {
			return this.OpenLayer(this.MCS_HELP);
		}
		if (destination == 'TOS' || destination == 'terms') {
			return this.OpenLayer(this.MCS_TERMS);
		}
		if (destination == 'giftcardinfo') {
			location.href = 'http://'+ms247.SSOClientMCS.ssoFrontendServername+'/webapp/wcs/stores/servlet/MultiChannelRedirect?destination=mygiftcard';
			//openPopup('http://mastershop.novomind.com/webapp/wcs/stores/servlet/MultiChannelRedirectMediaUS?destination=mygiftcard');
			return true;
		}
		if (destination == 'visacardinfo') {
			// this is a special upload we have to wait for
			return false;
		}
		
		if (destination == 'tfs_terms_and_conditions') {
			return this.OpenLayer(this.MUSIC_TERMS);
		}
		if (destination == 'data_privacy_protection' || destination == 'tfs_data_privacy_protection') {
			return this.OpenLayer(this.MUSIC_PRIVACY_STATEMENT);
		}
		if (destination == 'faq' || destination == 'tfs_faq') {
			return this.OpenLayer(this.MUSIC_FAQ);
		}
		if (destination == 'voucherinfo') {
			alert("24-7 TODO");
		}
		
		if (typeof destination == 'object') {
			return this.OpenLayer(destination);
		}
		return false;
	}
	
	this.TFSLayerProvider = {
		providerUrl: layerProviderUrl
	}

	this.OpenLayer = function(layer) {
		var layerProvider = layer.type == 'tfs' ? this.TFSLayerProvider : null;
		var layerCallback = function() { ms247LayerAccordion('#layer .content'); };
		multiChannel.openLayer(layer.id, new Array(), layerCallback, layerProvider );
		return false;
	}
} // TFSLayerHandler()

function gotoSite(destination, settings) {
	return ms247.LayerHandler.GotoSite(destination);
}


/***************************************************************************************************
 * FLASH HANDLING **********************************************************************************
 **************************************************************************************************/
function TFSFlashHandler() {
	this.flashVersion = "9.0.0";

	this.embedCoverFlow = function(containerId, width, height, xmlFilename) {
	    var flashvars = {};
	    if (xmlFilename.indexOf(".xml") == -1) {
	    	xmlFilename += ".xml";
	    }
	    flashvars.xmlpath       = publicdir + "xml/" + xmlFilename; // XML dump file to load
		flashvars.priceprefix 	= ms247.Settings.FlashPriceImagePrefix;
		flashvars.pricesuffix 	= ms247.Settings.FlashPriceImageSuffix;
		//flashvars.debug 		= "1";
	    //flashvars.navtextback   = "";
	    //flashvars.navtextforward= "";

	    var params = {};
	    //params.allowScriptAccess = "sameDomain";
	    //params.bgcolor           = "#ffffff";
	    //params.quality           = "high";
	    params.wmode			 = "opaque";

	    var attributes = {};
	    swfobject.embedSWF(publicdir + "swf/MediamarktCoverflow.swf", containerId, width, height, this.flashVersion, publicdir + "swf/expressInstall.swf", flashvars, params, attributes);
	}
	
	this.embedTeaserFlash = function(replaceId, width, height, xmlFilename) {
	    var flashvars = {};
	    if (xmlFilename.indexOf(".xml") == -1) {
	    	xmlFilename += ".xml";
	    }
	    //alert(publicdir);
	    //alert("http://test.247ms.com/hostshops/247/type_c/sites/saturn-downloadde2453623120137/public/xml/" + xmlFilename);
	    flashvars.xmlConfigPath       = publicdir + 'xml/'+ xmlFilename; // XML config file to load
	    flashvars.xmlCategoryPath       = publicdir + 'xml/'; // path to XML file to load
	    //alert(flashvars.xmlpath);
	    //flashvars.catname       = xmlFilename; // XML dump file to load
		//flashvars.priceprefix 	= ms247.Settings.FlashPriceImagePrefix;
		//flashvars.pricesuffix 	= ms247.Settings.FlashPriceImageSuffix;
		//flashvars.debug 		= "1";
	    //flashvars.navtextback   = "";
	    //flashvars.navtextforward= "";

	    var params = {};
	    //params.allowScriptAccess = "sameDomain";
	    //params.bgcolor           = "#ffffff";
	    //params.quality           = "high";
	    params.wmode			 = "transparent";
	    
	    var d = new Date();
	    var t = d.getTime();
	    
	    var attributes = {};
	    swfobject.embedSWF(publicdir + "swf/Saturn_dl_shop_teaser2010.swf?nocache="+t, replaceId, width, height, ms247.FlashMaster.flashVersion, publicdir + "swf/expressInstall.swf", flashvars, params, attributes);
	}
	
	this.embedFlashstage = function(containerId, width, height, buttonText) {
        var flashvars = {};
        var timestamp = this.getLinkTimestamp();
        flashvars.xmlpath           = publicdir + "xml/flashstage_frontpage.xml?"+timestamp;
        flashvars.xmlFixCategory    = publicdir + "xml/flashstage_fixCategory.xml?"+timestamp;
        flashvars.imgprefix_small   = publicdir + "img/flashstage/small/";
        flashvars.imgprefix_big     = publicdir + "img/flashstage/big/";
        flashvars.buttontext        = buttonText;
		flashvars.priceprefix 		= ms247.Settings.FlashPriceImagePrefix;
		flashvars.pricesuffix 		= ms247.Settings.FlashPriceImageSuffix;

        var params      = {};
        params.wmode			 = "opaque";

        var attributes  = {};
        swfobject.embedSWF(publicdir + "swf/MediamarktDownloadTeaser.swf?"+timestamp, containerId, width, height, this.flashVersion, publicdir + "swf/expressInstall.swf", flashvars, params, attributes);
	}

	this.getLinkTimestamp = function() {
		return (new Date()).getUTCMilliseconds();
	}

	// DEPRECATED:
	this.embedFrontpageCoverFlow = function(containerId, width, height, frontpageButtonText) {
		this.embedFlashstage(containerId, width, height, frontpageButtonText);
	}

	this.embedMusicPlayer = function(productid, containerId) {
		if (containerId == null) {
			containerId = "playerObject";
		}
	    var flashvars       = {};
		flashvars.jsonPath  = shopBaseUrlAjax;
		flashvars.page      = "ajax/playerobject";
		flashvars.id        = productid;
		flashvars.debugMode = "true";
		//alert(flashvars.jsonPath + "\n" + flashvars.page + "\n" + flashvars.id);
		//return;

	    var params          = {};
	    params.bgcolor      = "#000000";

	    var attributes      = {};
	    attributes.id       = "audio_player";

	    //alert(publicdir + "swf/247.AudioPlayer.swf" + "\n" + containerId + "\n" + ms247.Settings.FlashMusicPlayerWidth + "\n" + ms247.Settings.FlashMusicPlayerHeight + "\n" + this.flashVersion + "\n" + publicdir + "swf/expressInstall.swf" + "\n" + flashvars + "\n" + params + "\n" + attributes);
	    swfobject.embedSWF(publicdir + "swf/247.AudioPlayer.swf", containerId, ms247.Settings.FlashMusicPlayerWidth, ms247.Settings.FlashMusicPlayerHeight, this.flashVersion, publicdir + "swf/expressInstall.swf", flashvars, params, attributes);
	}

	this.embedVideoPlayer = function(productid, containerId) {
		// This is currently no flash player, due to different video format (WMV):
		jQuery.ajax({
	        type: 		"GET",
	        dataType: 	"html",
	        url: 		shopBaseUrlAjax + "ajax/videoplayerobject&lmid="+lmid,
	        async: 		true, // we need to call this synchronously, to block Browser's and user's activity!
	        cache:      false,
	        success: function(result){
				//$('#247_videoplayer').html(result);
    			//$(this).openVideoplayer('#video_player');
	        }
	    });
	}
} // TFSFlashHandler()


// OPEN POPUP FOR FLASH PLAYER /////////////////////////////////////////////////////////////////////
var popupMusicPlayer = null;

function openMusicPlayer(productid) {
	popupMusicPlayer = window.open(shopBaseUrl + "&page=player_popup&id=" + productid, "player", "width=755,height=490,dependent=yes,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no");
	if (popupMusicPlayer != null) {
		popupMusicPlayer.focus();
	}
}


// CALLBACK FROM FLASH TO OPEN PRODUCT DETAIL //////////////////////////////////////////////////////
function jumpto(productid) {
	var productdatainput = productid;

	// detect page and id to call
	var productpage = "redirect_to_product"; // fallback that will redirect server-side
	var productid   = productdatainput;
	if (productid.indexOf(",") > -1) {
		var splitted = productid.split(",");
		productpage = splitted[1];
		productid   = splitted[0];
	}

	// and go...
	var fullurl = shopBaseUrl + "&page=" + productpage.toLowerCase() + "&id=" + productid;
	// PLAYER CALL?
	if (ms247.isPlayerWindow) {
		fullurl = fullurl + "&addtocart=true"; // from Player we add products directly to cart
	}
	if (window.opener) {
    	// calling from inside popup
    	window.opener.location.href = fullurl;
    } else if (document.title.indexOf("Player") > -1) {
        window.open(fullurl); // player popup, but shop window already closed => reopen a new one
     } else {
    	// caller seems to not be inside a popup => open url in a new window?
    	//window.open(fullurl);
    	parent.location.href = fullurl;
    }
}


/***************************************************************************************************
 * CALLBACK HANDLING *******************************************************************************
 **************************************************************************************************/
function TFSCallBackHandler() {
	this.RemoveFromCart = function(mouse_event, settings) {
		// 2. remove from cart
		var cartupdateid = settings.cartupdateid;

		// add callback to execute next step (reload page)
		settings.callback = "ms247.CallBackHandler.RemovedFromCart";

		ms247.AjaxHandler.ShopCart.Remove(cartupdateid, mouse_event, settings);
	};

	this.RemovedFromCart = function(mouse_event, settings) {
		TimedReload(2000);
	};

	this.RemoveFromWishlist = function(mouse_event, settings) {
		ms247.AjaxHandler.Wishlist.Remove(settings.wishlistUpdateId, mouse_event, settings);
	};
	this.RemovedFromWishlist = function(mouse_event, settings) {
		TimedReload(2000);
	};

	this.RemoveFromPreOrderSelection = function(mouse_event, settings) {
		// 2. remove from prereleases list
		ms247.AjaxHandler.PreOrderSelection.Remove(settings.preOrdersSelectionUpdateid, mouse_event, settings);
	};
	this.RemovedFromPreOrderSelection = function(mouse_event, settings) {
		TimedReload(2000);
	};

	this.ShopCartCountUpdatedInSSO = function() {
		window.location.reload();
	};

	// INVOKING METHOD:
	this.Execute = function(mouse_event, settings) {
		if (settings == null) {
			return;
		}
		if (settings.callback == "" || settings.callback == null) {
			return;
		}

		// check if valid callback function defined
		if (typeof window[settings.callback] == 'function') {
			window[settings.callback](mouse_event, settings);
		} else {
			// split into parts...
			var parts = settings.callback.split(".");
			if (typeof window[parts[0]] == 'object') {
				if (typeof window[parts[0]][parts[1]] == 'function') {
					window[parts[0]][parts[1]](mouse_event, settings);
				} else if (typeof window[parts[0]][parts[1]] == 'object') {
					window[parts[0]][parts[1]][parts[2]](mouse_event, settings);
				}
			}
		}
	};
} // TFSCallBackHandler()
ms247.CallBackHandler = new TFSCallBackHandler();

function callback_execute(mouse_event, settings) {
	ms247.CallBackHandler.Execute(mouse_event, settings);
}

function TimedReload(millis) {
	window.setTimeout(function() { window.location.reload(); }, millis);
}

//used for callbacks where we want to do nothing...
function callbackVoid() {
	return true;
}


// PAGELOAD TRIGGERS ///////////////////////////////////////////////////////////////////////////////
function callback_getObjects(eventSourceElementId) {
	var eventSourceObject = jQuery("#" + eventSourceElementId);
    // check if this element exists on the current page
	if (eventSourceObject == null) {
		// callbacks may point to a different page / state of the page => avoid null refs.
		return;
	}

	if (ms247.Toolkit.hasElemPrefix(eventSourceElementId)) { // is list view, not product detail
    	// scroll to list entry
    	//location.href = "#" + eventSourceElementId;
    	// select the link "add to wishlist" (which is a child of the list entry)
    	eventSourceObject = jQuery(".a247_addToSelection", eventSourceObject); 
    }

    var pos = eventSourceObject.offset();
	var settings;
	if (ms247.isIE) {
		settings = {usePageNotEventOffset: true, pageX: pos.left + 20, pageY: pos.top, distanceX: 20, distanceY: pos.top - 65 };
	} else {
		settings = {usePageNotEventOffset: true, pageX: pos.left + 20, pageY: pos.top, distanceX: 20, distanceY: pos.top - 65 };
	}
	return { settingsObj: settings, eventSourceObj: eventSourceObject }
}

function callback_pageLoad_AddToWishlist(eventSourceElementId) {
	window.setTimeout(function() {
		var obj = callback_getObjects(eventSourceElementId);
		product_addtowishlist(obj.eventSourceObj, null, obj.settingsObj);
	}, 2000);
}
function callback_pageLoad_AddToPreOrderWishlist(eventSourceElementId) {
	window.setTimeout(function() {
		var obj = callback_getObjects(eventSourceElementId);
		product_addtopreorderwishlist(obj.eventSourceObj, null, obj.settingsObj);
	}, 2000);
}
function callback_pageLoad_AddToCart(eventSourceElementId) {
	window.setTimeout(function() {
		var obj = callback_getObjects(eventSourceElementId);
		product_addtocart(obj.eventSourceObj, null, obj.settingsObj);
	}, 2000);
}
ms247.lightboxClosingCallback = function() {
	ms247.SSOClientMCS.resetLoginReturnCallback();
}

/**/
function TFSToolkit() {
	this.elemPrefix    = "elem_";

	this.hasElemPrefix = function(elemId) {
		return startsWith(elemId, this.elemPrefix);
	}
	this.removeElemPrefix = function(elemId) {
		// remove elem prefix if elemId starts with that
		if (this.hasElemPrefix(elemId)) {
			return elemId.substr(this.elemPrefix.length);
		}
		return elemId;
	}

	// URL Handling
	this.CorrectHTTPSecureStateIfNecessary = function(pageState) {
		if (!pageState.PageIsViewedHTTPSecure && pageState.PageMustBeViewedHTTPSecure) {
			location.href = this.ChangeHTTPtoHTTPS(location.href);
		}
	}
	this.ChangeHTTPtoHTTPS = function(urlGiven) {
		if (urlGiven.indexOf("http:") != -1) {
			return "https" + urlGiven.substr(4);
		}
		return urlGiven;
	}
	this.BuildURLForPaging = function(formId, urlPrefix) {
	    var urlStringFull = urlPrefix;
	    if (!startsWith(formId, "#") && !startsWith(formId, ".")) {
	    	formId = "#" + formId;
	    }

		jQuery(formId).find("input").each(function() {
	    	urlStringFull += "&" + jQuery(this).attr("name") + "=" + jQuery(this).val();
	    });
	    jQuery(formId).find("select").each(function() {
	    	urlStringFull += "&" + jQuery(this).attr("name") + "=" + jQuery(this).val();
	    });
	    urlStringFull += "&pg=1"; // always jump to the first page...
	    // if there's a context defined append it to the url, too...
	    if (jQuery("#pgcontext").exists()) {
	    	urlStringFull += "&context=" + jQuery("#pgcontext").text();
	    }

	    return urlStringFull;
	}
}

function PageState(currentPageShouldBeViewedHTTPSecure) {
	// DEFAULT VALUES
		// User must land on HTTPs if he is browsing myaccount or checkout pages
	this.HTTPSecureForCheckoutMyAccount = true;
		// User must land on HTTPS if he is logged in.
	this.HTTPSecureAfterLogin 			= false;

	// CONSTRUCTOR
	this.PageIsViewedHTTPSecure 		= (location.href.substring(0,5).toLowerCase() == "https");
	this.PageMustBeViewedHTTPSecure  	= currentPageShouldBeViewedHTTPSecure;
	ms247.Toolkit.CorrectHTTPSecureStateIfNecessary(this);
}



/** TAB HANDLER
 **************************************************************************************************/
ms247.TabHandler = new TFSTabHandler();

function TFSTabHandler() {
	this.tabsLoaded = new Array();

	this.addLoadedTab = function(tabId) {
		if (this.isTabLoaded(tabId)) {
			return true;
		}
		this.tabsLoaded.push(tabId);
		return false;
	};

	this.isTabLoaded = function(tabId) {
		return (this.tabsLoaded.join(",").indexOf(tabId) != -1);
	};

	this.switchToTab = function(tabId) {
		if (!this.isTabLoaded(tabId)) {
		    if (tabId == "tab-trackliste") {
		    	// gets automatically and always loaded by the detail page
		    	return false;
		    }else if (tabId == "tab-videoinfo") {
		    	// gets automatically and always loaded by the detail page
		    	return false;
		    } else if (tabId == "tab-allesvon") {
		    	ms247.AjaxHandler.LoadArtistReleases(jQuery("#product_artist_id").text(), "#" + tabId, "#box-" + tabId, jQuery("#tabview").text());
		    } else if (tabId == "tab-autor") {
		    	//author tab
		    	ms247.AjaxHandler.LoadArtistReleases(jQuery("#product_artist_id").text(), "#" + tabId, "#box-" + tabId);
		    } else if(tabId == "tab-kapitel"){
	    		// gets automatically and always loaded by the detail page
		    	return false;
	    	}
		    /**frontpage / charts **/
	    	if (ms247.AjaxHandler.Charts.LoadTab(tabId, this)) {
			    return false;
	    	} else 
		    /**newlm **/
	    	if (ms247.AjaxHandler.NewReleases.LoadTab(tabId, this)) {
			    return false;
	    	}
		    /**genre **/
	    	if (ms247.AjaxHandler.Genres.LoadTab(tabId, this)) {
	    		return false;
	    	}
	    	/**audiobook frontpage **/
	    	if (ms247.AjaxHandler.AudiobooksFrontpage.LoadTab(tabId, this)) {
	    		return false;
	    	}
	    	/**audiobook detailpage **/
	    	if (ms247.AjaxHandler.AudiobooksDetailpage.LoadTab(tabId, this)) {
	    		return false;
	    	}
	    	
	    	
	    	
	    	
	    	return false;
		}
	};

	this.switchToActiveTabs = function(parentBlockSelector) {
		//alert(parentBlockSelector);
		jQuery(parentBlockSelector+" .tab-list li.active").each(function() {
			//alert(jQuery(this).attr("id"));
			ms247.TabHandler.switchToTab(jQuery(this).attr("id"));
		});
	};
}; // TFSTabHandler()


/** HELPER FUNCTIONS
 **************************************************************************************************/
function product_addtocart(jQueryObj, event, settings) {
	var $ids     = jQueryObj.children(".a247_addToCartData");
	var updateid = $ids.text();
	if (updateid == null || updateid == "" || updateid == "," || updateid == ",;") {
		TooltipHelper.show247Tooltip("#general_action_error", event, defaultErrorTooltipSettings);
		return false;
	}
	ms247.AjaxHandler.ShopCart.Add(updateid, event, settings);
	return false;
}

function product_addtowishlist(jQueryObj, event, settings) {
	if (!ms247.SSOClientMCS.userMayAccessWishlist(jQueryObj)) {
		return false;
	}

	var $ids     = jQueryObj.children(".a247_addToSelectionData");
	var updateid = $ids.text();
	if (updateid == null || updateid == "") {
		TooltipHelper.show247Tooltip("#general_action_error", event, settings);
	}
	ms247.AjaxHandler.Wishlist.Add(updateid, event, settings);
	return false;
}

function product_addtopreorderwishlist(jQueryObj, event, settings) {
	if (!ms247.SSOClientMCS.userMayAccessWishlist(jQueryObj)) {
		return false;
	}
	
	var $ids     = jQueryObj.children(".a247_addToSelectionData");
	var updateid = $ids.text();
	if (updateid == null || updateid == "") {
		TooltipHelper.show247Tooltip("#general_action_error", event, settings);
	}
	ms247.AjaxHandler.PreOrderSelection.Add(updateid, event, settings);
	return false;
}


/** BUYTOGETHER - BLOCK OF 3 ITEMS THAT ARE FREQUENTLY BOUGHT TOGETHER
 **************************************************************************************************/
/**
 * author: DST
 * Handle selection of products, update the total price and settings nececssary to handle shopcart.
 */
function TFSBoughtTogetherHandler(parentidstring, usePriceImage, idTextPrice) {
	this.parentidstring = "#often-bought-together";
	this.usePriceImage  = false;
	this.idTextPrice    = "#buy-together-textprice";

	this.updateCart = function(event) {
		var updateid = "";
		jQuery(this.parentidstring + " input:checked").each(function() {
			updateid += jQuery(this).attr("name"); // updatecart string
		});
		if (updateid == "" || updateid == ";") return; // TODO: was soll passieren jetzt? Kein Artikel fuer WK da...
		if (updateid.substring(0,1)==";") updateid=updateid.substring(1);
		ms247.AjaxHandler.ShopCart.Add(updateid, event);
	};
	this.roundPrice = function(price_sum) {
		return price_sum.toFixed(2);
	};
	
	this.ReadSelectedProducts = function() {
		var price_sum = 0.00;
		var num_products_selected = 0;
		jQuery(this.parentidstring + " input:checked").each(function() {
			var price = parseFloat(jQuery(this).val());
			price_sum += price;
			num_products_selected++;
		});

		return { 
			numProductsSelected: num_products_selected,
			totalPrice: this.roundPrice(price_sum)
		}
	};
	this.updatePrice = function() {
		// get the prices of all currently checked products:
		var selectedProducts = this.ReadSelectedProducts();
		// we do not want users to deselect all products: minimum is 1 product selected
		if (selectedProducts.numProductsSelected < 1) {
			return false;
		}

		var price_sum 				= selectedProducts.totalPrice;
		var num_products_selected 	= selectedProducts.numProductsSelected;

		///////// TEXT - ONLY DISPLAY
		var price_text_old  = "";
		var priceimg_src	= "";
		var priceimg_newsrc = "";
		var price_text_new  = "";

		if (this.usePriceImage) {
			// get old price image url
			priceimg_src	= jQuery(this.parentidstring + " .price-box .price img").attr("src");
			// replace only the filename for price image with the new one
			priceimg_newsrc = priceimg_src.substring(0, priceimg_src.indexOf("/va")+3) + price_sum + priceimg_src.substring(priceimg_src.indexOf("/sl"))

			price_text_old  = jQuery(this.parentidstring + " .price-box .price img").attr("alt");
		} else {
			price_text_old  = jQuery("#buy-together-textprice").text();
		}
		
		///////// PRICEIMAGE DISPLAY
		var splitted        = price_text_old.split(" ");
		if (splitted.length < 2) {
			splitted[0] = "¤"; // &euro;
			splitted[1] = price_sum;
		} else {
			if (!isNaN(splitted[0])) {
				//alert(splitted[0] + " - price first");
				splitted[0] = price_sum;
			}
			if (!isNaN(splitted[1])) {
				//alert(splitted[1] + " - price second");
				splitted[1] = price_sum;
			}
		}
		price_text_new = splitted.join(" ");

		// place link for client
		if (this.usePriceImage) {
			jQuery(this.parentidstring + " .price-box .price img").attr("src", priceimg_newsrc).attr("alt", priceimg_newalt);
		} else {
			jQuery(this.idTextPrice).text(price_text_new);
		}
	};

	// CONSTRUCTOR ////
	this.parentidstring		= parentidstring;
	this.usePriceImage 		= usePriceImage;
	this.idTextPrice		= idTextPrice;

	// add event handler to the "wird oft zusammen gekauft" checkboxes so the sum will get updated
	// when the customers changes a checkbox's state.
	/*jQuery(this.parentidstring + " input").click(function() {
		return this.updatePrice();
	});

	jQuery(this.parentidstring + " .a247_addToCartTogether").click(function(e) {
		this.updateCart(e);
		return false;
	});*/
	// /CONSTRUCTOR ////
}; // TFSBoughtTogetherHandler()




/** GENRES             
 **************************************************************************************************/
function navigateToSelectedGenre(genre) {
	if (genre == null) {
		genre = jQuery("#GenreSelection select option:selected").val();
	}
	if (genre == null) return false;
	if (genre == "") return false;
	var view = jQuery("#GenreSelection input[name='view']").val();
	window.location.href = shopBaseUrl + "&page=genres&genre=" + genre + "&view="+view;
}



/** SSO CLIENT
 **************************************************************************************************/
function SSOClientMCS(basketPage, providerId, ssoFrontendServername) {
	this.ssoProviderId         = "";
    this.basketUrl             = "";
    this.backlinkCallbackURL   = "";
    this.successCallbackURL    = "";
    this.ssoFrontendServername = "";

	this.getCurrentUrlForSSOCallback = function() {
		// defined parmeter names that may be contained in URLs sent to SSO as callback URLs
		var parmsWhitelist = new Array();
		parmsWhitelist["file"]     = true;
		parmsWhitelist["page"]     = true;
		parmsWhitelist["id"]       = true;
		parmsWhitelist["artistid"] = true;
		parmsWhitelist["view"]     = true;
		parmsWhitelist["genre"]    = true;
		parmsWhitelist["pg"]       = true;
		parmsWhitelist["pgsize"]   = true;
		parmsWhitelist["lmtype"]   = true;

		// read Query String from URL
		var href;
		if (location.search.indexOf("#") > -1) {
			href = location.search.substring(0, location.search.indexOf("#"));
		} else {
			href = location.search;
		}
		if (href == "") {
			return location.href;
		} else {
			if (href.substr(0,1) == "?") {
				href = href.substr(1);
			}
		}
	
		var newhref   = "";

		var hrefsplit = href.split("&");
		//console.log("href=", href);
		//console.log("num of parms", hrefsplit.length);
		for (var part = 0; part < hrefsplit.length; part++) {
			var parm      = hrefsplit[part];
			var parmparts = parm.split("=");
	
			// 
			var parmName  = parmparts[0];
			var parmVal   = parmparts[1];
			//console.log("parmName: ", parmName, "parmVal: ", parmVal);
	
			// is parm valid for a callback url?
			if (parmsWhitelist[parmName] == true) {
				newhref = newhref += parm + "&";
			}
		}
		if (newhref == null) {
			return "";
		}
		if (newhref == "") {
			return "";
		}
		newhref = location.href.substr(0, location.href.indexOf("?")) + "?" + newhref.substring(0, newhref.length - 1);
		//console.log("newhref built: ", newhref);
		return newhref;
	};

	this.setBacklinkCallbackURL = function(backlinkURL) { // URL to send to SSO as callback after successful registration/login
		if (backlinkURL == "") {
			backlinkURL = shopBaseUrl + "&page=frontpage";
		}
		this.backlinkCallbackURL = backlinkURL;
	};
	this.setBacklinkCallbackPage = function(abortPage) { // Page to send to SSO as callback after successful registration/login
		if (abortPage == "") {
			abortPage = "frontpage";
		}
		this.setBacklinkCallbackURL(shopBaseUrl + "&page=" + abortPage.split("|").join("&"));
	};

	this.setSuccessCallbackURL = function(successUrl) { // URL to send to SSO as callback after successful registration/login
		if (successUrl == "") {
			successUrl = shopBaseUrl + "&page=frontpage";
		}
		this.successCallbackURL = successUrl;
	};
	this.setSuccessCallbackPage = function(successPage) { // Page to send to SSO as callback after successful registration/login
		if (successPage == "") {
			successPage = "frontpage";
		}
		this.setSuccessCallbackURL(shopBaseUrl + "&page=" + successPage.split("|").join("&"));
	};

	this.redirectToLogin = function() {
		var backlinkurl = this.backlinkCallbackURL;
		var successurl  = this.successCallbackURL;
		if (backlinkurl == null || backlinkurl == "") {
			backlinkurl = this.getCurrentUrlForSSOCallback(); // location.href //shopBaseUrl + "frontpage";
		}
		if (successurl == null || successurl == "") {
			successurl = this.getCurrentUrlForSSOCallback(); // location.href
		}
		if (ms247.HTTPSecureAfterLogin) {
			if (successurl.indexOf("http:") != -1) {
				successurl = ms247.Toolkit.ChangeHTTPtoHTTPS(successurl);
			}
		}
		if (ms247.HTTPSecureForCheckoutMyAccount) {
			if (successurl.indexOf("http:") != -1) {
				if (successurl.indexOf("page=checkout") != -1) {
					successurl = ms247.Toolkit.ChangeHTTPtoHTTPS(successurl);
				}
				if (successurl.indexOf("page=myaccount") != -1) {
					successurl = ms247.Toolkit.ChangeHTTPtoHTTPS(successurl);
				}
			}
		}
		successurl    = successurl + this.loginreturncallback;
		location.href = ssoLoginUrl + "?tpOrigin=" + encodeURIComponent(this.ssoProviderId) + "&redirectURL=" + encodeURIComponent(successurl) + "&backURL=" + encodeURIComponent(backlinkurl);
	};

	this.updateShopCartCount = function(newProductCount, callback) {
		if (callback == null) {
			callback = callbackVoid;
		}
    	//alert(callback);

	    if (newProductCount == null) {
			jQuery.ajax({
		        type: 		"GET",
		        dataType: 	"json",
		        url: 		shopBaseUrlAjax + "&page=ajax/cart/productcount",
		        //data:   	"lmid=" + lmid + "&rating=" + rating,
		        async: 		false, // we need to call this synchronously, to block Browser's and user's activity!
		        cache:      false,
		        success: function(result) {
					//jQuery("#basket-holder #basket .a247_cartCount").html(jQuery.trim(result.count));
		    		multiChannel.sso.refreshBasket(this.ssoProviderId, result.count, this.basketUrl, callback);
		        }
		    });
	    } else {
	    	multiChannel.sso.refreshBasket(this.ssoProviderId, newProductCount, this.basketUrl, callback);
    	}
	};

	this.mustLoginFirst = function(additionalParams) {
		// => register additional parms for the callback after user returned logged in from SSO
		this.setLoginReturnCallback(additionalParams);
		// => closing lightbox - Layer resets parms by calling lightboxClosingCallback 
		lightbox("#mustloginfirst-holder .mustloginfirst-box", ".mustloginfirst-inner");
	};

	this.isUserLoggedIn = function() {
		return tfsUserLoggedIn;
	};

	// Callback after login/registration returned user to musicdownload... 
	this.loginreturncallback = "";
	this.setLoginReturnCallback = function(callbackParms) {
		if (callbackParms == null) {
			return;
		}
		this.loginreturncallback = callbackParms;
	};
	this.resetLoginReturnCallback = function() {
		this.loginreturncallback = "";
	};


	this.userMayAccessWishlist = function(elementObject) {
		if (this.isUserLoggedIn()) {
			return true;
		} else {
			var productElemId = "";
			if (elementObject != null) {
				var layerCount = 0;
				while (!elementObject.hasClass("a247ListElem") && (elementObject.parent() != null) && (++layerCount < 5)) {
					elementObject = elementObject.parent();
				}
				if (elementObject != null) {
					if (elementObject.hasClass("a247ListElem")) {
						productElemId = ms247.Toolkit.removeElemPrefix(elementObject.attr('id'));
					}
				}
			}
			
			if (productElemId == "" || productElemId == null) {
				// it is not (yet) possible to call addtowl on callback (we're missing the elements Id)
				this.mustLoginFirst('&addtowl=true');
			} else {
				this.mustLoginFirst('&addtowl=true&wishlistproductid=' + productElemId);
			}
			return false;
		}
	}
	this.userMayAccessPreOrderWishlist = function(elementObject) {
		if (this.isUserLoggedIn()) {
			return true;
		} else {
			var productElemId = "";
			if (elementObject != null) {
				var layerCount = 0;
				// big lists:
				//elementObject  = elementObject.parent().parent().parent();
				// checkout_basket:
				//elementObject  = elementObject.parent().parent().parent().parent();
				while (!elementObject.hasClass("a247ListElem") && (elementObject.parent() != null) && (++layerCount < 5)) {
					elementObject = elementObject.parent();
				}
				if (elementObject != null) {
					if (elementObject.hasClass("a247ListElem")) {
						productElemId = ms247.Toolkit.removeElemPrefix(elementObject.attr('id'));
					}
				}
			}
			if (productElemId == "" || productElemId == null) {
				// it is not (yet) possible to call addtowl on callback (we're missing the elements Id)
				this.mustLoginFirst('&addtopowl=true');
			} else {
				this.mustLoginFirst('&addtopowl=true&wishlistproductid=' + productElemId);
			}
			return false;
		}
	}


    // CONSTRUCTOR
	this.basketUrl 	  		   = shopBaseUrlSecure + "&page=" + basketPage;
	this.ssoProviderId 		   = providerId;
	this.ssoFrontendServername = ssoFrontendServername;
	// unless overridden later use current url as sso callback...
	if (location.href.indexOf("#") > -1) {
		this.setSuccessCallbackURL(this.getCurrentUrlForSSOCallback()); //location.href.substring(0, location.href.indexOf("#"))
	} else {
		this.setSuccessCallbackURL(this.getCurrentUrlForSSOCallback());
	}
    // /CONSTRUCTOR
}; // SSOClientMCS


/** MYACCOUNT AREA
 **************************************************************************************************/
function initMyAccountHandler() {
	jQuery(".printonly").hide();
}



/** ACTION EVENT HANDLERS
 **************************************************************************************************/
var initialized 	= "";

function init247_eventHandler(parentBlockSelector) {
	if (parentBlockSelector == null) {
		parentBlockSelector = "";
	}
	if (startsWith(parentBlockSelector, "##")) {
		parentBlockSelector = parentBlockSelector.substr(1);
	}

	// CHECK IF ALREADY INITIALIZED FOR THIS BLOCK....
	var arrayBlockSelectorIndex = "_root_";
	if (parentBlockSelector != "") {
		arrayBlockSelectorIndex = parentBlockSelector;
	}
	if (initialized.indexOf("|"+arrayBlockSelectorIndex+",") > -1) {
		//alert(arrayBlockSelectorIndex + " already initialized...");
		return;
	}

	// Add the EventHandlers...
	jQuery(parentBlockSelector+".a247_prelisten").click(function() {
		var $ids     = jQuery(this).children(".a247_prelistenData");
		var productid = $ids.text();
		openMusicPlayer(productid);
		return false;
	});
	
	jQuery(parentBlockSelector+".a247_preview").click(function() {
		var $ids     = jQuery(this).children(".a247_previewData");
		var productid = $ids.text();
		var content = "Hier ist der Content";
		//alert(productid);
		if (productid.indexOf(",") > -1) {
    		var splitted = productid.split(",");
    		var lmtype = splitted[1];
    		var lmid   = splitted[0];
    	}
		jQuery.ajax({
	        type: 		"GET",
	        dataType: 	"html",
	        url: 		shopBaseUrlAjax + "&page=ajax/videoplayerobject",
	        data:   	"id=" + lmid,
	        async: 		false, // we need to call this synchronously, to block Browser's and user's activity!
	        cache:      false,
	        success: function(result) {
				content = result;
				//alert(content);
	        }
	    });
		jQuery.fancybox(
				content,
					{
			        		'autoDimensions'	: true,
						'width'         	: 'auto',
						'height'        	: 'auto',
						'transitionIn'		: 'fade',
						'transitionOut'		: 'none'
					}
				);


				//lightbox('#popup_container', content);
				return false;
		});
	
	/** BASKET **/
	init247_Handlers_Basket(parentBlockSelector);

	/** WISHLIST **/
	init247_Handlers_Wishlist(parentBlockSelector);

	/** PREORDERS **/
	init247_Handlers_PreOrders(parentBlockSelector);

	/** TOOLTIPS **/
	jQuery(parentBlockSelector+".tt-click").tooltip({
        'tipEvent': 'click',
        'distanceY': 1
    });

    jQuery(parentBlockSelector+".tt-hover").tooltip();

    /** HOTFIX [Novomind topic] **/
	if (parentBlockSelector == "") {
		multiChannel.setNavigationInit('download');
	}

	/** ADD EVENT HANDLER FOR SEARCH FORM INPUT **/
	jQuery(parentBlockSelector+" #SimpleSearchForm input.a247_SearchInput").focus(function() {
		var defaultText = jQuery("#a247_SearchDefaultText").text();
		if (jQuery(this).val() == defaultText) {
			jQuery(this).val("");
		}
	}).blur(function() {
		var defaultText = jQuery("#a247_SearchDefaultText").text();
		if (jQuery(this).val() == "") {
			jQuery(this).val(defaultText);
		}
	});
	jQuery(parentBlockSelector+" #SimpleSearchForm .icon_finden").click(function() {
		jQuery(parentBlockSelector+" #SimpleSearchForm").submit();
	});

	/** LOAD ACTIVE TABS' CONTENTS **/
	ms247.TabHandler.switchToActiveTabs(parentBlockSelector);

	/** MY ACCOUNT - DOWNLOADS **/
	jQuery(parentBlockSelector+" .a247_AcquireRedownload").click(function() {
		if (jQuery(".a247_selectableReDlItem:checked").length > 0) {
			var allLMlist = "";
			jQuery(".a247_selectableReDlItem:checked").each(function() { allLMlist += jQuery(this).val(); });
			jQuery("#lmlist").val(allLMlist);
			jQuery("#redownloads_acquire").submit();
		} else {
			alert("Bitte waehlen Sie mindestens ein Produkt aus!"); // Es wurden keine Produkte ausgewählt!
		}
		return false;
	});
}


function init247_Handlers_Basket(parentBlockSelector) {
	jQuery(parentBlockSelector+".a247_addToCart").click(function(e) {
		product_addtocart(jQuery(this), e); // { distanceX: -140, distanceY: -75 }
		return false;
	});

	jQuery(parentBlockSelector+".a247_removeFromCart").click(function(e) {
		var $ids     = jQuery(this).children(".a247_removeFromCartData");
		var updateid = $ids.text();
		ms247.AjaxHandler.ShopCart.Remove(updateid, e);
		return false;
	});
	jQuery(parentBlockSelector+".a247_moveFromCartToWishlist").click(function(e) {
		if (!ms247.SSOClientMCS.userMayAccessWishlist(jQuery(this))) {
			return false;
		}
		var $ids1 	= jQuery(this).children(".a247_removeFromCartData");
		var $ids2 	= jQuery(this).children(".a247_addToSelectionData");
		var cartupdateid     = $ids1.text();
		var wishlistupdateid = $ids2.text();
		ms247.AjaxHandler.ShopCart.MoveToWishlist(cartupdateid, wishlistupdateid, e);
		return false;
	});
}
function init247_Handlers_Wishlist(parentBlockSelector) {
	jQuery(parentBlockSelector+".a247_addToWishlist").click(function(e) {
		product_addtowishlist(jQuery(this), e); // { distanceX: -140, distanceY: -75 }??
		return false;
	});
	jQuery(parentBlockSelector+".a247_addToSelection").click(function(e) {
		product_addtowishlist(jQuery(this), e); // { distanceX: -140, distanceY: -75 }??
		return false;
	});
	jQuery(parentBlockSelector+".a247_removeFromWishlist").click(function(e) {
		if (!ms247.SSOClientMCS.userMayAccessWishlist(jQuery(this))) {
			return false;
		}
		var $ids     = jQuery(this).children(".a247_removeFromWishlistData");
		var updateid = $ids.text();
		ms247.AjaxHandler.Wishlist.Remove(updateid, e);
		return false;
	});
	jQuery(parentBlockSelector+".a247_moveFromWishlistToCart").click(function(e) {
		if (!ms247.SSOClientMCS.userMayAccessWishlist(jQuery(this))) {
			return false;
		}
		var $ids1   = jQuery(this).children(".a247_removeFromWishlistData");
		var $ids2 	= jQuery(this).children(".a247_addToCartData");
		var wishlistupdateid    = $ids1.text();
		var cartupdateid 		= $ids2.text();
		ms247.AjaxHandler.Wishlist.MoveToShopCart(wishlistupdateid, cartupdateid, e);
		return false;
	});
}
function init247_Handlers_PreOrders(parentBlockSelector) {
	jQuery(parentBlockSelector+".a247_addToPreOrderSelection").click(function(event) {
		if (!ms247.SSOClientMCS.userMayAccessWishlist(jQuery(this))) {
			return false;
		}

		var $ids     = jQuery(this).children(".a247_addToSelectionData");
		var updateid = $ids.text();
		if (updateid == null || updateid == "") {
			TooltipHelper.show247Tooltip("#general_action_error", event, defaultErrorTooltipSettings);
		}
		ms247.AjaxHandler.PreOrderSelection.Add(updateid, event, settings);
		return false;
	});
	jQuery(parentBlockSelector+".a247_removeFromPreOrderSelection").click(function(event) {
		if (!ms247.SSOClientMCS.userMayAccessWishlist(jQuery(this))) {
			return false;
		}
		var $ids     = jQuery(this).children(".a247_removeFromPreOrderSelectionData");
		var updateid = $ids.text();
		ms247.AjaxHandler.PreOrderSelection.Remove(updateid, event);
		return false;
	});
	jQuery(parentBlockSelector+".a247_moveFromPreOrderSelectionToCart").click(function(e) {
		if (!ms247.SSOClientMCS.userMayAccessWishlist(jQuery(this))) {
			return false;
		}
		var $ids1 	= jQuery(this).children(".a247_removeFromPreOrderSelectionData");
		var $ids2 	= jQuery(this).children(".a247_addToCartData");
		var preorderselectionupdateid     = $ids1.text();
		var cartupdateid = $ids2.text();
		ms247.AjaxHandler.PreOrderSelection.MoveToCart(preorderselectionupdateid, cartupdateid, e);
		return false;
	});
	jQuery(parentBlockSelector+".a247_moveFromPreOrderSelectionToWishlist").click(function(e) {
		if (!ms247.SSOClientMCS.userMayAccessWishlist(jQuery(this))) {
			return false;
		}
		var $ids1 	= jQuery(this).children(".a247_removeFromPreOrderSelectionData");
		var $ids2 	= jQuery(this).children(".a247_addToSelectionData");
		var preorderselectionupdateid     = $ids1.text();
		var wishlistupdateid = $ids2.text();
		ms247.AjaxHandler.PreOrderSelection.MoveToWishlist(preorderselectionupdateid, wishlistupdateid, e);
		return false;
	});
}

function init247() {
	//init247_eventHandler(""); // root eventhandler for loaded page
	//ms247.BuyTogether = new TFSBoughtTogetherHandler("#often-bought-together", false, "#buy-together-textprice");
	// Genre Selector
	jQuery(".selectGenre.autoloadOnSelection").change(function(event) {
		var view    = "";
		var pageUrl = shopBaseUrl + "&page="+jQuery(this).attr('name')+"&genre=" + jQuery(this).attr('value') + "&view=" + view;;
		window.location.href = pageUrl;
	});
	ms247initRatingStars();
	//ms247initSearch();
	jqueryUIAutocomplete();
	init247_eventHandler("");
	// init lefttab navi toggling
	jQuery('#contentbox-left .cat-box .lefttab-navi-toggle-subnavi-music .toggleThis').click(function() {
		//jQuery(this).parent().next().slideToggle('fast');
		//jQuery('#contentbox-left .cat-box .lefttab-navi-toggle-subnavi-audiobooks .toggleThis').parent().next().slideToggle('fast');
		var pageUrl = shopBaseUrl;
		window.location.href = pageUrl;
		return false;
	});
	jQuery('#contentbox-left .cat-box .lefttab-navi-toggle-subnavi-audiobooks .toggleThis').click(function() {
		//jQuery(this).parent().next().slideToggle('fast');
		//jQuery('#contentbox-left .cat-box .lefttab-navi-toggle-subnavi-music .toggleThis').parent().next().slideToggle('fast');
		var pageUrl = shopBaseUrl + "&page=audiobooks/frontpage";
		window.location.href = pageUrl;
		return false;
	});
	jQuery('#contentbox-left .cat-box .lefttab-navi-toggle-subnavi a').click(function() {
		jQuery(this).parent().next().toggle();
		return false;
	});
	// hide sub-navis which should be hidden by default
	jQuery('#contentbox-left .cat-box .lefttab-navi-default-hidden').hide();
}

//for initial search results
function getResults(){
    var searchCrit = jQuery('#suchebox').val();
    var SearchCritEncoded = escape(searchCrit);
    var searchURL  = shopBaseUrl + '&page=search/results&searchcrit=' + SearchCritEncoded;
    self.location.href = searchURL;
    //tabJumpToSearch(searchURL, '1', '#all_results', searchCrit);   
}

// for search results
function getNewResults(){
    var searchURL  = 'search/results&xsl=search/ajax_results';
    var searchCrit = jQuery('#suchebox').val();
    var SearchCritEncoded = escape(searchCrit);
    tabJumpToSearch(searchURL, '1', '#all_results', SearchCritEncoded);   
}

//for search results
function getNewResultsAudiobooks(){
    var searchURL  = 'search/results&xsl=search/ajax_results&content=audiobook';
    var searchCrit = jQuery('#suchebox').val(); 
    tabJumpToSearch(searchURL, '1', '#all_results', searchCrit);   
}

