(function(window, undefined ) {
    var rs = new Object();
    rs.components = {
        page: {},
        content: {}
    };
    rs.utils = {};
    rs.page = {};
    window.RS = rs;
})(window);
// END of initialization

/**
*
*
* bxSlider: Content slider / fade / ticker using the jQuery javascript library.
*
* Author: Steven Wanderski
* Email: wandoledzep@gmail.com
* URL: http://bxslider.com
*
*
**/

jQuery.fn.bxSlider = function(options){

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Declare variables and functions
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    var defaults = {
        mode: 'slide',
        speed: 500,
        auto: false,
        auto_direction: 'left',
        pause: 2500,
        controls: true,
        prev_text: 'prev',
        next_text: 'next',
        width: jQuery(this).children().width(),
        prev_img: '/us_assets/redesign/images/bg_switch.png',
        next_img: '/us_assets/redesign/images/bg_switch.png',
        ticker_direction: 'left',
        wrapper_class: 'container'
    };

    options = jQuery.extend(defaults, options);

    if(options.mode == 'ticker'){
        options.auto = true;
    }

    var jQuerythis = jQuery(this);

    var jQueryparent_width = options.width;
    var current = 0;
    var is_working = false;
    var child_count = jQuerythis.children().size();
    var i = 0;
    var j = 0;
    var k = 0;

    function animate_next(){

        is_working = true;

        jQuerythis.animate({'left':'-' + jQueryparent_width * 2 + 'px'}, options.speed, function(){

            jQuerythis.css({'left':'-' + jQueryparent_width + 'px'}).children(':first').appendTo(jQuerythis);

            is_working = false;

        });

    }

    function animate_prev(){

        is_working = true;

        jQuerythis.animate({'left': 0}, options.speed, function(){

            jQuerythis.css({'left':'-' + jQueryparent_width + 'px'}).children(':last').insertBefore(jQuerythis.children(':first'));

            is_working = false;

        });

    }

    function fade(direction){

        if(direction == 'next'){

            var last_before_switch = child_count - 1;
            var start_over = 0;
            var incr = k + 1;

        }else if(direction == 'prev'){

            var last_before_switch = 0;
            var start_over = child_count -1;
            var incr = k - 1;

        }

        is_working = true;

        if(k == last_before_switch){

            jQuerythis.children().eq(k).fadeTo(options.speed, 0, function(){jQuery(this).hide();});
            //jQuerythis.children().eq(k).css({'left':'-9999px'});
            jQuerythis.children().eq(start_over).show().fadeTo(options.speed, 1, function(){

            is_working = false;

            k = start_over;

            });

        }else{

            jQuerythis.children().eq(k).fadeTo(options.speed, 0, function(){jQuery(this).hide();});
            //jQuerythis.children().eq(k).css({'left':'-9999px'});
            jQuerythis.children().eq(incr).show().fadeTo(options.speed, 1, function(){

            is_working = false;

            k = incr;

            });

        }

    }

    function add_controls(){

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Check if user selected images to use for next / prev
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////

        if(options.prev_img != '' || options.next_img != ''){
        	if(options.wrapper_class != 'cust-service-container'){
        		jQuerythis.parent().append('<div class="reviewsSlider" style="height:163px;background-color:#fff;left:1px;position:absolute;top:0px;width:38px;"><a class="slider_prev" href="javascript:void(0);"></a></div><div class="reviewsSlider" style="height:163px;background-color:#fff;right:0px;position:absolute;top:0px;width:40px;"><a class="slider_next" href="javascript:void(0);"></a></div>');
        	}else{
                    jQuerythis.parent().append('<div class="serviceSlider" style="background:#FFF;left:-10px;position:absolute;top:0px;height:110px;width:30px;"><a class="slider_prev" href="javascript:void(0);"></a></div><div class="serviceSlider" style="background:#FFF;right:0px;position:absolute;top:0px;height:85px;width:30px;"><a class="slider_next" href="javascript:void(0);"></a></div>');
            }
        }else{
            jQuerythis.parent().append('<a class="slider_prev" href="">' + options.prev_text + '</a><a class="slider_next" href="">' + options.next_text + '</a>');
        }

        jQuerythis.parent().find('.slider_prev').css({'float':'left', 'outline':'0'});
        jQuerythis.parent().find('.slider_next').css({'float':'right', 'outline':'0'});


        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Accomodate padding-top for controls when elements are absolutely positioned (only in fade mode)
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////

        if(options.mode == 'fade'){

            jQuerythis.parent().find('.slider_prev').css({'paddingTop' : jQuerythis.children().height()})
            jQuerythis.parent().find('.slider_next').css({'paddingTop' : jQuerythis.children().height()})

        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Actions when user clicks next / prev buttons
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////

        jQuerythis.parent().find('.slider_next').click(function(){

            if(!is_working){

                if(options.mode == 'slide'){

                    animate_next();

                    if(options.auto){

                        clearInterval(jQuery.t);

                        jQuery.t = setInterval(function(){animate_next();}, options.pause);

                    }

                }else if(options.mode == 'fade'){

                    fade('next');

                    if(options.auto){

                        clearInterval(jQuery.t);

                        jQuery.t = setInterval(function(){fade('next');}, options.pause);

                    }


                }

            }

            return false;

        });

        jQuerythis.parent().find('.slider_prev').click(function(){

            if(!is_working){

                if(options.mode == 'slide'){

                    animate_prev();

                    if(options.auto){

                        clearInterval(jQuery.t);

                        jQuery.t = setInterval(function(){animate_prev();}, options.pause);

                    }

                }else if(options.mode == 'fade'){

                    fade('prev');

                    if(options.auto){

                        clearInterval(jQuery.t);

                        jQuery.t = setInterval(function(){fade('prev');}, options.pause);

                    }

                }

            }

            return false;

        });

    }


    function ticker() {

        if(options.ticker_direction == 'left'){

            jQuerythis.animate({'left':'-' + jQueryparent_width * 2 + 'px'}, options.speed, 'linear', function(){

                jQuerythis.css({'left':'-' + jQueryparent_width + 'px'}).children(':first').appendTo(jQuerythis);

                ticker();

            });

        }else if(options.ticker_direction == 'right'){

            jQuerythis.animate({'left': 0}, options.speed, 'linear', function(){

                jQuerythis.css({'left':'-' + jQueryparent_width + 'px'}).children(':last').insertBefore(jQuerythis.children(':first'));

                ticker();

            });

        }

    }



    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Create content wrapper and set CSS
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    jQuerythis.wrap('<div class="' + options.wrapper_class + '"></div>');

    //console.log(jQuerythis.parent().css('paddingTop'));

    if(options.mode == 'slide' || options.mode == 'ticker'){
             if(options.wrapper_class == 'cust-service-container'){
        jQuerythis.parent().css({
            'overflow' : 'hidden',
            'position' : 'relative',
            'width' : '276px' //options.width + 'px'
        });
             }else{
                jQuerythis.parent().css({
                        'overflow' : 'hidden',
                        'position' : 'relative',
                        'width' : (options.width + 30) + 'px',
                        'height' : '100%'

                });
             }
        jQuerythis.css({
            'width' : '999999px',
            'position' : 'relative',
            'left' : '-' + jQueryparent_width + 'px'
        });

        jQuerythis.children().css({
            'float' : 'left',
            'width' : jQueryparent_width
        });

        if (jQuerythis.children().size() == 1) {
        	jQuerythis.children().css({'margin-left':jQueryparent_width + 'px'});
        }

        if (jQuerythis.children().size() > 1)
            jQuerythis.children(':last').insertBefore(jQuerythis.children(':first'));

    }else if(options.mode == 'fade'){

        jQuerythis.parent().css({
            'overflow' : 'hidden',
            'position' : 'relative',
            'width' : options.width + 'px'
            //'height' : jQuerythis.children().height()
        });

        if(!options.controls){
            jQuerythis.parent().css({'height' : jQuerythis.children().height()});
        }

        jQuerythis.children().css({
            'position' : 'absolute',
            'width' : jQueryparent_width,
            'listStyle' : 'none',
            'opacity' : 0,
            'display' : 'none'
        });

        jQuerythis.children(':first').css({
            'opacity' : 1,
            'display' : 'block'
        });

    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Check if user selected "auto"
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    if(!options.auto){
        if (jQuerythis.children().size() > 1) {
            add_controls();
        }
    }else{

        if(options.mode == 'ticker'){

            ticker();

        }else{

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Set a timed interval
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////

            if(options.mode == 'slide'){

                if(options.auto_direction == 'left'){

                    jQuery.t = setInterval(function(){animate_next();}, options.pause);

                }else if(options.auto_direction == 'right'){

                    jQuery.t = setInterval(function(){animate_prev();}, options.pause);

                }

            }else if(options.mode == 'fade'){

                if(options.auto_direction == 'left'){

                    jQuery.t = setInterval(function(){fade('next');}, options.pause);

                }else if(options.auto_direction == 'right'){

                    jQuery.t = setInterval(function(){fade('prev');}, options.pause);

                }

            }

            if(options.controls){

                add_controls();

            }

        }

    }

};
/**
	rsBanner functions
**/

RSUI.components.content.rsBanner = new Object();


RSUI.components.content.rsBanner.globals = {
	DEFAULT_LANGUAGE_CODE : "esp"
}


// Used to describe the rsBanner component
RSUI.components.content.rsBanner.describe = function(){
	  return "The promo banner component displays the banner with promotion offer and allows to select/change the product language";
}


// Returns the language currently set in the dropdown
RSUI.components.content.rsBanner.getLanguageInDropDown = function(){
  return $("#languageSelectText").html();
}


// Returns the language code currently set in the dropdown
RSUI.components.content.rsBanner.getLanguageCodeFromDropDown = function(){
  var language = this.getLanguageInDropDown();
  return this.resolveLanguageNameToCode(language);
}


// Returns the language name by code
// Works only with the languages in the popup
RSUI.components.content.rsBanner.resolveLanguageCodeToName = function(langCode){
    var langName = "Not Available";
	if ($("#" + langCode)) {
		langName = $("#" + langCode).html();
	}
	return langName;
}


//Returns the language code by name
//Works only with the languages in the popup - searches by the attribute
RSUI.components.content.rsBanner.resolveLanguageNameToCode = function(langName){
	var selector = "a[rslangname='"+langName+"']";
    var langCode = "N-A";
    if ($("#languagePopup").find(selector)[0]) {
    	langCode = $("#languagePopup").find(selector)[0].id;
	}
    return langCode;
}

//Returns the language code by long name
//Works only with the languages in the popup - searches by the text within link
RSUI.components.content.rsBanner.resolveLanguageLongNameToCode = function(langName){
  var selector = "a:contains('"+langName+"')";
  var langCode = "N-A";
  if ($("#languagePopup").find(selector)[0]) {
  	langCode = $("#languagePopup").find(selector)[0].id;
	}
  return langCode;
}


// Sets the language
RSUI.components.content.rsBanner.setLanguage = function(langName){
	var rsLangBannerImage = null;
	var selector = "a:contains('"+langName+"')";
	var langPopup = $("#languagePopup");
	if (langPopup != null && langPopup && langPopup.length > 0){
		var langItem = $("#languagePopup").find(selector)[0];
		if (langItem) {
			rsLangBannerImage = $(langItem).attr("rsLangBannerImage");
			$('#languageSelectText').html($(langItem).html());
			$('.languageDisplayText').html($(langItem).html());
		}
		
		if (rsLangBannerImage) {
			$('.primaryBannerArea').css("background","url('" + rsLangBannerImage + "') no-repeat scroll left top transparent");
		}
    
		// !!! INTEGRATION POINT !!!
		// Trigger ProductList function selectLanguage(code)
		var langCode = this.resolveLanguageLongNameToCode(langName);
    
        RSUI.components.content.rsBanner.onLanguageChange(langCode);
	}
};

RSUI.components.content.rsBanner.onLanguageChangeCallBackFunctions = [];

RSUI.components.content.rsBanner.onLanguageChange = function(param) {
    for (var cb in RSUI.components.content.rsBanner.onLanguageChangeCallBackFunctions) {
        if (RSUI.components.content.rsBanner.onLanguageChangeCallBackFunctions.hasOwnProperty(cb)) {
            console.log("cb: " + cb);
            try {
                RSUI.components.content.rsBanner.onLanguageChangeCallBackFunctions[cb](param)
            } catch (e) {
                console.log("RSUI.components.content.rsBanner.onLanguageChange error: " + e + " callbackId: " + cb);
            }
        }
    }
};

RSUI.components.content.rsBanner.addCallBackOnLanguageChange = function(callbackId, newCallback) {
    if (callbackId && newCallback && typeof(newCallback) == "function") {
        RSUI.components.content.rsBanner.onLanguageChangeCallBackFunctions[callbackId] = newCallback;
    } else {
        console.log("RSUI.components.content.rsBanner.addCallBackOnLanguageChange error: is not a function, id: " + callbackId);
    }
};

RSUI.components.content.rsBanner.setListeners = function(){
    // Bind action to display language poppup on click on dropdown
    $('#languageSelectText').bind('click',function(e) {
        $('#languagePopup').toggle(400);
    });
        
    
    // Bind action to hide language popup when clicked on body (outside of dropdown)
    $(document.body).bind('click',function(e) {
       if (e.target.id == 'languageSelectText') return;    // Except the actual click on dropdown

       if ($('#languagePopup').is(':visible')) {
           $('#languagePopup').hide(400);
       }
    });   
   
    // Bind action to handle selection of a language
    $("#languagePopup a").click(function () {
    	var langName = $(this).html();
		var langCode= $(this).attr('id');
		//34962 Redirection for GOBOT languages in DE
		var current_url=window.location.href;
		if(current_url.indexOf(".de")!=-1){
			if(langCode=="dan"){
				window.location.href="/daenisch-lernen";
			}else if(langCode=="dar"){
				window.location.href="/dari-lernen";
			}else if(langCode=="ind"){
				window.location.href="/indonesisch-lernen";
			}else if(langCode=="pas"){
				window.location.href="/paschtu-lernen";
			}else if(langCode=="kis"){
				window.location.href="/suaheli-lernen";
			}else if(langCode=="tha"){
				window.location.href="/thailaendisch-lernen";
			}else if(langCode=="urd"){
				window.location.href="/urdu-lernen";
			}else if(langCode=="cym"){
				window.location.href="/walisisch-lernen";
			}else{
				RSUI.components.content.rsBanner.setLanguage(langName);
			}
		}else{
			RSUI.components.content.rsBanner.setLanguage(langName);
		}        
    });
};

// Define the initial language (default or from the page URL)
RSUI.components.content.rsBanner.setInitialLanguage = function() {
	var langCode = RSUI.util.getParamFromLandingPageUrl('language');
	langCode = (langCode == "") ? RSUI.components.content.rsBanner.globals.DEFAULT_LANGUAGE_CODE : langCode;
	var langName = RSUI.components.content.rsBanner.resolveLanguageCodeToName(langCode);
	RSUI.components.content.rsBanner.setLanguage(langName);

	// Commented for the ticket 36642
    //if (((typeof(CQ) == "undefined") || (CQ.WCM.getMode() != "edit")) && RSUI.components.content.rsQuickBuyProductsList) {
    //    RSUI.components.content.rsQuickBuyProductsList.hide();
    //}
}

// Initialization of the language dropdown list on page load
$(document).ready(function(){
    //Checking the component promo bammer exists or not
	var isPromoBannerComponentExists = (jQuery("#component_rsPromoBanner").length > 0)
	if(isPromoBannerComponentExists){
		RSUI.components.content.rsBanner.setInitialLanguage();
		RSUI.components.content.rsBanner.setListeners();
	}
});


//============================
//==== COMPONENT DIALOG ======
//============================

RS.components.content.rsBanner = {}

/**
 *    Called when the user selected banner type 
 *    in component dialog
 **/

RS.components.content.rsBanner.changeType = function(obj) {

    dialog = obj.findParentByType(CQ.Dialog);
    bannerType = obj.getValue();
    comment = dialog.findById("lblComment");
    
    switch(bannerType) {
       case "SimpleOfferOnBanner":
           comment.setValue("The banner encompasses the placeholders for offer and language images, as well as the dropdown list.");
           // RS.components.content.rsBanner.switchToMode("SimpleOfferOnBanner", dialog);
           break;
       case "SimpleOfferBelowBanner":
           comment.setValue("The banner resides above the placeholders for offer and language images, as well as the dropdown list.");
           // RS.components.content.rsBanner.switchToMode("SimpleOfferBelowBanner", dialog);
           break;
       case "LanguageSensitive":
           comment.setValue("The banner and the text on it will change whenver the user selects a new language in the dropdown list.");
           // RS.components.content.rsBanner.switchToMode("LanguageSensitive", dialog);
           break;
    }

    dialog.doLayout();
}


RS.components.content.rsTermsConditions = {
    showLightbox:function(id) {
        jQuery('#facebox').removeClass("reviews");//workaround to remove class which is added in facebox.js
        jQuery.facebox({ div: id }, "rsTermsConditions");
        jQuery('#facebox').removeClass("mt");//workaround to remove class which is added in facebox.js
        $('#facebox .close_image').attr('src', '/etc/designs/rosettastone/us/images/facebox/closelabel.gif');
    }
};RS.components.content.rsRatingAndReview = {
    showReviewSlider:function(){
        $('.rsRatingAndReview .slider').each(function(){
        	$(this).bxSlider({mode: 'slide',speed: 250,wrapper_class: 'sliderContainer'});
        	
        	var self = $(this);
        	
        	var slider_prev = self.parent().find('.slider_prev');
        	var slider_next = self.parent().find('.slider_next');
        	
        	$(slider_prev).mouseover (function() {
                $(slider_prev).css({'background-position':'0 -84px'});
            });
        	$(slider_prev).mouseout (function() {
        		$(slider_prev).css({'background-position':'0 -14px'});
            });
        	$(slider_prev).mousedown (function() {
        		$(slider_prev).css({'background-position':'0 -153px'});
            });
        	$(slider_prev).mouseup (function() {
        		$(slider_prev).css({'background-position':'0 -84px'});
            });
            $(slider_next).mouseover (function() {
            	$(slider_next).css({'background-position':'-19px -84px'});
            });
            $(slider_next).mouseout (function() {
            	$(slider_next).css({'background-position':'-19px -14px'});
            });
            $(slider_next).mousedown (function() {
            	$(slider_next).css({'background-position':'-19px -153px'});
            });
            $(slider_next).mouseup (function() {
            	$(slider_next).css({'background-position':'-19px -84px'});
            });
        });
    }
};

 jQuery(document).ready(function() {
        RS.components.content.rsRatingAndReview.showReviewSlider();
 });RS.components.content.rsVideoThumbs = {

    reset: function() {
        var elem = $("#rsVideoThumbsFlash");
        elem.empty();
        elem.append('<div id="rsVideoThumbsFlashHolder"></div>');
        return elem;
    },

    attachOnClickAction: function(linkId, settingsId) {
        var elem = $("#" + settingsId);
        if (elem != null) {
            var settings = eval("(" + elem.html() + ")");
            $("#" + linkId).click(function() {
                $('div.rsVideoThumbs ul.thumbs li a.selected').removeClass('selected');
                $(this).addClass('selected');
                var defaultParams = {
                    allowFullScreen : 'true',
                    wmode: 'transparent',
                    base: 'http://www.rosettastone.com/us_assets/redesign/flash/',
                    allowscriptaccess: 'always',
                    salign: 'tl',
                    scale: 'noborder',
                    pluginurl: 'http://www.macromedia.com/go/getflashplayer'
                };
                // merge params with default values
                var mergedParams = jQuery.extend(defaultParams, settings.params);

                var parentDiv = RS.components.content.rsVideoThumbs.reset();

                swfobject.embedSWF("http://www.rosettastone.com/us_assets/redesign/flash/VideoApplication.swf",
                        "rsVideoThumbsFlashHolder", "455", "307", "9.0.28",
                        "http://www.rosettastone.com/us_assets/redesign/flash/expressInstall.swf",
                        settings.flashvars, mergedParams, settings.attributes);
                parentDiv.show(2000);
                return false;
            });
        }
    }
};

jQuery(document).ready(function() {
    RS.components.content.rsVideoThumbs.attachOnClickAction("rsVideoThumbs-select-1", "rsVideoThumbs-settings-1");
    RS.components.content.rsVideoThumbs.attachOnClickAction("rsVideoThumbs-select-2", "rsVideoThumbs-settings-2");
    RS.components.content.rsVideoThumbs.attachOnClickAction("rsVideoThumbs-select-3", "rsVideoThumbs-settings-3");
});

RS.components.content.rsInternalNavigation = {
    onMouseOver: function(listElem) {
        $(listElem).addClass("hover");
    },

    onMouseOut: function(listElem) {
        $(listElem).removeClass("hover");
    },

    onHideParent: function(checkbox) {
        if (checkbox != 'undefined') {
            var parentTabNameFields = checkbox.ownerCt.find("name", "./parentTabName");
            if (checkbox.getValue() == 'true') {
                if (parentTabNameFields != 'undefined' && parentTabNameFields.length > 0) {
                    parentTabNameFields[0].disable();
                }
            } else {
            	if (parentTabNameFields != 'undefined' && parentTabNameFields.length > 0) {
                    parentTabNameFields[0].enable();
                }
            }
        }
    },

    onHidePage: function(checkbox) {
        if (checkbox != 'undefined') {
            var tabNameFields = checkbox.ownerCt.find("name", "./tabName");
            if (checkbox.getValue() == 'true') {
                if (tabNameFields != 'undefined' && tabNameFields.length > 0) {
                	tabNameFields[0].disable();
                }
            } else {
            	if (tabNameFields != 'undefined' && tabNameFields.length > 0) {
            		tabNameFields[0].enable();
                }
            }
        }
    }

};

RS.components.content.rsInternalNavigationCorporate = {
    onMouseOver: function(listElem) {
        $(listElem).addClass("hover");
    },

    onMouseOut: function(listElem) {
        $(listElem).removeClass("hover");
    },

    onHideParent: function(checkbox) {
        if (checkbox != 'undefined') {
            var parentTabNameFields = checkbox.ownerCt.find("name", "./parentTabName");
            if (checkbox.getValue() == 'true') {
                if (parentTabNameFields != 'undefined' && parentTabNameFields.length > 0) {
                    parentTabNameFields[0].disable();
                }
            } else {
            	if (parentTabNameFields != 'undefined' && parentTabNameFields.length > 0) {
                    parentTabNameFields[0].enable();
                }
            }
        }
    },

    onHidePage: function(checkbox) {
        if (checkbox != 'undefined') {
            var tabNameFields = checkbox.ownerCt.find("name", "./tabName");
            if (checkbox.getValue() == 'true') {
                if (tabNameFields != 'undefined' && tabNameFields.length > 0) {
                	tabNameFields[0].disable();
                }
            } else {
            	if (tabNameFields != 'undefined' && tabNameFields.length > 0) {
            		tabNameFields[0].enable();
                }
            }
        }
    }

};

RS.components.content.rsHomepageBanner = {
		start: function(elementId, interval) {
			interval = interval || 4000;
			$(document).ready(function(){
				var rsHomepageBanner = $('div#' + elementId + '.rsHomepageBannerInner');
				if (rsHomepageBanner) {
					rsHomepageBanner.cycle({
						timeout:interval + 1000,
						fx: 'custom',
						animOut: {
							opacity: 0
						},
						animIn: {
							opacity: 1
						},
						cssBefore: {
							'display':'block'
						},
						cssAfter: {
							'display':'none'
						}
					});
				}
			});
		}
};
RS.components.content.rsTabbedText = {
    showTab: function(componentId, titleId) {
        var componentSelector = "#" + componentId;
        var tabSelector = "#" + titleId;
        jQuery(componentSelector + ' .tabs .tabsContent .textContainer').hide();
        jQuery(componentSelector + ' .tabs .tabsContent .imageContainer').hide();
        jQuery(componentSelector + ' .tabs .tabsContent .container').hide();
        jQuery(componentSelector + ' .tabs .tabsContent .video').hide();
        jQuery(tabSelector + "-text").show();
        jQuery(tabSelector + "-container").show();
        var oldTab = jQuery(componentSelector + ' .tabsTitles table td.active');
        var newTab = jQuery(tabSelector);
        oldTab.removeClass('active');
        oldTab.addClass('inactive');
        newTab.addClass('active');
        newTab.removeClass('inactive');
    },
    
    showVideoTab: function(componentId, titleId, videoUrl, previewImg, datasource, positionX, positionY) {
        RS.components.content.rsTabbedText.showTab(componentId, titleId);
        var videoContainer = jQuery("#" + componentId + "-videoContainer");
        videoContainer.empty();
        videoContainer.removeAttr("style");
        videoContainer.attr("style", "position:absolute; top:" + positionY + "px; left:" + positionX + "px;");
        var videoDivId = componentId + "-video";
        videoContainer.append('<div id="' + videoDivId + '"></div>');
        videoContainer.show();
        
        //var swfUrl = "http://www.rosettastone.com/content/dam/rosettastonecom/flash/VideoApplication.swf";
        var swfUrl = "/content/dam/rosettastonecom/flash/VideoApplication.swf";
        var width = "398";
        var height = "263";
        var version = "9.0.28";
        //var expressInstallSwfurl = "http://www.rosettastone.com/content/dam/rosettastonecom/flash/expressInstall.swf";
        var expressInstallSwfurl = "/content/dam/rosettastonecom/flash/expressInstall.swf";
        var flashvars = {};
        flashvars.video = videoUrl;
        flashvars.dataSource = datasource;
        flashvars.preview = previewImg;
        var params = {};
        params.allowFullScreen = "true";
        params.bgcolor = "FBF8E5";
        params.base = "/content/dam/rosettastonecom/flash";
        //params.base = "http://www.rosettastone.com/content/dam/rosettastonecom/flash/";
        params.allowscriptaccess = "always";
        params.salign = 'tl';
        params.scale = 'noborder';
        params.wmode = 'transparent';
        swfobject.embedSWF(swfUrl, videoDivId, width, height, version, expressInstallSwfurl, flashvars, params, {});
    },

    showImageTab: function(componentId, titleId) {
        RS.components.content.rsTabbedText.showTab(componentId, titleId);
        jQuery("#" + titleId + "-img").show();
    }

};                      /*
 * Javascript for the TabsContainerComponent
 */

RSUI.components.content.rsTabsContainerComponent = function(){
    
    //private attributes
    
    //Constants
    ALL_TABS_CONTENT_SELECTOR = ".tabs-container-tab-contents .tabs_content_all blockquote.tabs_content";
    ALL_TABS_HEADER_SELECTOR = ".tabs-container-tab-headers div";
    DEFAULT_ACTIVE_TAB_INDEX = "0";
    OUT_OF_VIEWPORT = 'out-of-viewport';
    BACK_IN_VIEWPORT = 'back-in-viewport';
    TAB_HEADER_DEFAULT = customClassForTabs["default"]; //.default throws some error in the backend while creating rsclientlib.js
    TAB_HEADER_HOVER = customClassForTabs["hover"];
    TAB_HEADER_ACTIVE = customClassForTabs["active"];
    TAB_HEADER_SELECTED = customClassForTabs["selected"];
    TAB_HEADER_CLASS_SET = TAB_HEADER_DEFAULT + " " + TAB_HEADER_HOVER + " " + TAB_HEADER_ACTIVE + " " + TAB_HEADER_SELECTED+" selected" ;
    
    activeTabIndex = DEFAULT_ACTIVE_TAB_INDEX;
    
    //Public Methods
    this.setActiveTabIndex = function(tabIndex){
        activeTabIndex = tabIndex;
    }

    this.addListnersForTabEvents = function(trackingObject){
        var obj = this;
        var trackingObject = trackingObject;
        var selectedTabIndex = activeTabIndex;
        
        getAllTabHeaders().click(function(){
            selectedTabIndex = getAllTabHeaders().index(this);
            obj.setActiveTabIndex(selectedTabIndex);
            obj.switchTab();
           
           if(trackingObject !== '' ){     
            trackingObject.trackTabClick(this, selectedTabIndex);
            }
        });
        
        
        getAllTabHeaders().hover(function(){
            selectedTabIndex = getAllTabHeaders().index(jQuery(jQuery(".selected")[0]).parent(ALL_TABS_HEADER_SELECTOR))
            var hoverIndex = getAllTabHeaders().index(this);
            if(selectedTabIndex != hoverIndex)
                jQuery(this).find("a").removeClass(TAB_HEADER_CLASS_SET).addClass(TAB_HEADER_HOVER);
        },
        function(){
            var hoverIndex = getAllTabHeaders().index(this);
            if(selectedTabIndex != hoverIndex)
                jQuery(this).find("a").removeClass(TAB_HEADER_CLASS_SET).addClass(TAB_HEADER_DEFAULT);
        });
         getAllTabHeaders().mousedown(function(){
            var mousedownIndex = getAllTabHeaders().index(this);
            if(selectedTabIndex != mousedownIndex)
                jQuery(this).find("a").removeClass(TAB_HEADER_CLASS_SET).addClass(TAB_HEADER_ACTIVE);
        });
    }
        
    this.onPageTabRedirect = function(){
        this.switchTab();
    }
    
    this.switchTab = function(){
        setTabHeaderSelection();
        killAllFlowplayers();
        hideAllTabContents();
        showActiveTabContent();
    }

    //Private Methods
    setTabHeaderSelection = function(){
        resetAllTabHeaders();
        setSelectedTabHeader();
    }
    killAllFlowplayers = function() {
        flowplayer("*").each(function() {
            this.stop();
        });
    }
    
    resetAllTabHeaders = function(){
        //getAllTabHeaders().removeClass(TAB_HEADER_CLASS_SET).addClass(TAB_HEADER_DEFAULT);
        getAllTabHeaders().find("a").removeClass(TAB_HEADER_CLASS_SET).addClass(TAB_HEADER_DEFAULT);
    }
    
    setSelectedTabHeader = function(){
        //getActiveTabHeader().removeClass(TAB_HEADER_CLASS_SET).addClass(TAB_HEADER_SELECTED);
        getActiveTabHeader().find("a").removeClass(TAB_HEADER_CLASS_SET).addClass("selected "+ TAB_HEADER_SELECTED);
    }
    
    hideAllTabContents = function(){
        getAllTabContents().removeClass(BACK_IN_VIEWPORT).addClass(OUT_OF_VIEWPORT);
    }
    
    getAllTabHeaders = function(){
        return jQuery(ALL_TABS_HEADER_SELECTOR);
    }

    getAllTabContents = function(){
        return jQuery(ALL_TABS_CONTENT_SELECTOR);
    }
    
    showActiveTabContent = function(){
        getActiveTabContent().addClass(BACK_IN_VIEWPORT).removeClass(OUT_OF_VIEWPORT);
    }

    getActiveTabContent = function(){
        return jQuery(jQuery(ALL_TABS_CONTENT_SELECTOR)[activeTabIndex]);
    }

    getActiveTabHeader = function(){
        return jQuery(jQuery(ALL_TABS_HEADER_SELECTOR)[activeTabIndex]);
    }

}

/*
 * Function to redirect the user to a particular tab on the catalog page based on the URL parameters.
 */
jQuery(document).ready(function(){

    (function(){
        
        getURLParameter = function(name){
            return decodeURI(
                (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
            );
        }
        
        getTabIndex = function(){
            var tabIndex = getURLParameter("tabindex");
            tabIndex = (tabIndex != "null") ? (tabIndex-1) : "0";
            return tabIndex;
        }
        
        getTrackingParams = function(){
            //return RSUI.components.content.rsTabsContainerComponentTracking.trackingInfo;
            return window.trackingInfo;
        }
        
        isTabsContainerExistsOnPage = (jQuery(".tabs-container .tabs-container-tab-contents").length > 0);
        
        if(isTabsContainerExistsOnPage && RSUI.components.content.rsTabsContainerComponent ){
            tabsComponentObject = new RSUI.components.content.rsTabsContainerComponent();
            tabsComponentObject.setActiveTabIndex(getTabIndex());
            tabsComponentObject.onPageTabRedirect();
            
             trackingInfo = getTrackingParams();
             
            if(trackingInfo.link_tracking_on_tabs !== 'false' ){                      
            trackingObject = new RSUI.components.content.rsTabsContainerComponentTracking(trackingInfo );
            }
            else{
            trackingObject = "" ;
            }
            tabsComponentObject.addListnersForTabEvents(trackingObject);
        }
        
    })();   

})/*
 * Javascript code for tracking on the tab container.
 */

RSUI.components.content.rsTabsContainerComponentTracking = function(trackingInfo){

	page_tracking = trackingInfo.page_tracking;
	tab_names = trackingInfo.tab_names;
	page_category = trackingInfo.page_category;
	evars_or_props = trackingInfo.evars_or_props;
	events = trackingInfo.events;
	link_delay = trackingInfo.link_delay;
	
	LINK_TRACKING = "LINK_TRACKING";
	PAGE_TRACKING = "PAGE_TRACKING";
	EXTENDED_TRACKING = "EXTENDED_TRACKING";
	LINK_TYPE = "o";
	tabIndex = "1";
	
	this.trackTabClick = function(object,index){
		setTabIndex(index);
		var tracking_type = getTrackingType();
		//console.log(tracking_type);
		switch(tracking_type){
			case LINK_TRACKING :
				oTrackLink(object, getTrackingName());
				break;
			case PAGE_TRACKING :
				oTrackPage(object, getTrackingName(), getPropsAndEvars(), getEvents(),getLinkDelay());
				break;
			case EXTENDED_TRACKING :
				oTrackLink(object, getTrackingName(), getPropsAndEvars(), getEvents(), LINK_TYPE, getLinkDelay());
				break;
		}
	}
	
	getTrackingType = function(){
		var is_props_or_evars_given = (evars_or_props != "");
		var is_events_given = (events != "");
		var is_type_page_tracking = (page_tracking == "true");
		var is_type_extended_tracking = (is_props_or_evars_given || is_events_given);
		if(is_type_page_tracking){
			return PAGE_TRACKING;
		}else if(is_type_extended_tracking){
			return EXTENDED_TRACKING;
		}else{
			return LINK_TRACKING;
		}
	}
	
	getTabIndex = function(){
		return tabIndex;
	}

	setTabIndex = function(index){
		tabIndex = index;
	}

	getTrackingName = function(){
		var trackingName = pageName + "/" + page_category + "/" + tab_names[getTabIndex()];
		return trackingName;
	}

	getPropsAndEvars = function(){
		return evars_or_props;
	}

	getEvents = function(){
		return events;
	}

	getLinkDelay = function(){
		return link_delay;
	}

}
RS.components.content.rsLanguageListDropdown = {
    toggleDropdown: function(dropdownContainerId) {
        $('#' + dropdownContainerId + ' .langListDropdown').toggle(50);
        if(! $('#' + dropdownContainerId + ' .langListButton').hasClass('langButtonClicked')) {
            if($('#' + dropdownContainerId + ' .langListButton').hasClass('langButtonMouseOver')){
                $('#' + dropdownContainerId + ' .langListButton').removeClass('langButtonMouseOver');
            }
            $('#' + dropdownContainerId + ' .langListButton').addClass('langButtonClicked');
        }
        else{
             $('#' + dropdownContainerId + ' .langListButton').removeClass('langButtonClicked');
        }
    },

    bindCloseAllDropdown:function() {
        // Bind action to hide language dropdowns when clicked on body
        $(document.body).bind('click', function(e) {
            if (! $(e.target).hasClass('langListButton')) {   // Except the actual click on button
                if ($('.rsLanguageListDropdown .langListDropdown').is(':visible')) {
                    $('.rsLanguageListDropdown .langListDropdown').hide(50);
                    $('.rsLanguageListDropdown .langListButton').removeClass('langButtonClicked');
                }
            }
        });
    },
    btnMouseOver : function(el) {
        if(! $('#' + el + ' .langListButton').hasClass('langButtonClicked')) {
            $('#' + el + ' .langListButton').addClass('langButtonMouseOver');
        }
    },
    btnMouseOut : function(el) {
       if(! $('#' + el + ' .langListButton').hasClass('langButtonClicked')) {
            $('#' + el + ' .langListButton').removeClass('langButtonMouseOver');
       }
    }
};

jQuery(document).ready(function() {
    var isComponentOnPage = (jQuery(".rsLanguageListDropdown").length > 0);
    if (isComponentOnPage) {
        RS.components.content.rsLanguageListDropdown.bindCloseAllDropdown();
    }
});RS.components.content.rsProductListSelector = {

    languageList : [],

    localization : {},

    productContent : {},

    displayType : {},

    hasInitialized : false,

    productEdition : "",

    appLanguage: '',

    productImgRef: "",

    productsOrder : "direct",

    LANGUAGE_TOKEN: "\\[Language\\]",

    leftArrowImageRef : "",
    leftArrowHoverImageRef : "",
    rightArrowImageRef : "",
    rightArrowHoverImageRef : "",

    componentHeight : 256,

    levelNamesList : ["L1", "L2", "L3", "L4", "L5", "S2", "S3", "S5","U1","TOT"],

    addToCartImageRef : "",

    addToCartHoverImageRef : "",

    showOnlineAccess : false,

    initModel : function(appLanguage, productContent, displayType, productEdition, productImgRef, productsOrder, leftArrowImageRef, leftArrowHoverImageRef, rightArrowImageRef, rightArrowHoverImageRef, componentHeight, addToCartImageRef, addToCartHoverImageRef, showOnlineAccess) {

        var languageServletPath = '/rosettastone/languagesList.json';
        var langResponse = CQ.HTTP.eval(CQ.HTTP.get(languageServletPath + '?globalSite=' + appLanguage));
        RS.components.content.rsProductListSelector.languageList = langResponse.languagesList;
        var localizationPath = "/content/global/localization/" + appLanguage + "/rsProductListSelector.json";
        RS.components.content.rsProductListSelector.localization = CQ.HTTP.eval(CQ.HTTP.get(localizationPath));

        if (RS.components.content.rsProductListSelector.localization == null) {
            var defaultLocalizationPath = "/content/global/localization/en_US/rsProductListSelector.json";
            RS.components.content.rsProductListSelector.localization = CQ.HTTP.eval(CQ.HTTP.get(defaultLocalizationPath));
        }

        RS.components.content.rsProductListSelector.productContent = productContent;
        RS.components.content.rsProductListSelector.displayType = displayType;
        RS.components.content.rsProductListSelector.productEdition = productEdition;
        RS.components.content.rsProductListSelector.appLanguage = appLanguage;
        RS.components.content.rsProductListSelector.productsOrder = productsOrder;

        RS.components.content.rsProductListSelector.addToCartImageRef =
            (addToCartImageRef == "") ? "/content/dam/rosettastonecom/images/mt/quickbuy/addcart_blue_s3.jpg" : addToCartImageRef;
        RS.components.content.rsProductListSelector.addToCartHoverImageRef =
            (addToCartHoverImageRef == "") ? "/content/dam/rosettastonecom/images/mt/quickbuy/addcart_green_s3.jpg" : addToCartHoverImageRef;

        RS.components.content.rsProductListSelector.productImgRef = "" == productImgRef ?
            RS.components.content.rsProductListSelector.getTextValue("productList_productImgPath") : productImgRef;

        RS.components.content.rsProductListSelector.leftArrowImageRef = "" == leftArrowImageRef ?
            RS.components.content.rsProductListSelector.getTextValue("productList_leftArrowImagePath") : leftArrowImageRef;

        RS.components.content.rsProductListSelector.leftArrowHoverImageRef = "" == leftArrowHoverImageRef ?
            RS.components.content.rsProductListSelector.getTextValue("productList_leftArrowHoverImagePath") : leftArrowHoverImageRef;

        RS.components.content.rsProductListSelector.rightArrowImageRef = "" == rightArrowImageRef ?
            RS.components.content.rsProductListSelector.getTextValue("productList_rightArrowImagePath") : rightArrowImageRef;

        RS.components.content.rsProductListSelector.rightArrowHoverImageRef = "" == rightArrowHoverImageRef ?
            RS.components.content.rsProductListSelector.getTextValue("productList_rightArrowHoverImagePath") : rightArrowHoverImageRef;

        RS.components.content.rsProductListSelector.componentHeight = componentHeight;

        RS.components.content.rsProductListSelector.hasInitialized = true;

        RS.components.content.rsProductListSelector.showOnlineAccess = showOnlineAccess;
    },

    renderProducts : function() {

        if (!RS.components.content.rsProductListSelector.hasInitialized) {
            return;
        }
        var productImgRef = RS.components.content.rsProductListSelector.productImgRef;

        var langCode = RSUI.components.page.getLanguageCodeFromDropDown();

        var lang = null;
        for (var i = 0; i < RS.components.content.rsProductListSelector.languageList.length; i++) {
            if (langCode == RS.components.content.rsProductListSelector.languageList[i].langCode) {
                lang = RS.components.content.rsProductListSelector.languageList[i];
                break;
            }
        }

        var rootDiv = $("div.productListSelector");
        rootDiv.empty();

        var levels = (lang.levels && "" != lang.levels) ? lang.levels.split(",") : [];
        if (RS.components.content.rsProductListSelector.showOnlineAccess == "true") {
            levels.push("TOT");
        }
        if ("reverse" == RS.components.content.rsProductListSelector.productsOrder) {
            levels.reverse();
        }
        if (levels.length == 0) {
            var noProductsFoundMessage = "<br /><b>No products were found for this language</b>";
            rootDiv.append(noProductsFoundMessage);
            return;
        }
        var htmlInnerText = "";
        if (RS.components.content.rsProductListSelector.displayType == "column") {
            htmlInnerText = htmlInnerText + "<div class='productContainer " + RS.components.content.rsProductListSelector.productEdition.toUpperCase() +
                " " + RS.components.content.rsProductListSelector.appLanguage.toUpperCase() + "'>\
            <div class='buffer'>\
                <div id='quick-buy'>\
                    <div style='float: right;' id='products'>\
                        <ul>";
        }
        else if (RS.components.content.rsProductListSelector.displayType == "slide") {
            htmlInnerText = htmlInnerText + "<div class='productContainer " + this.productEdition + " " + RS.components.content.rsProductListSelector.appLanguage.toUpperCase() + "'" +
                "<div style='display: block;' id='ajax-quickbuy-container'>" +
                "<div id='products'>" +
                "<div id='example3' style='padding: 10px 0pt 10px 40px; width: 999999px; position: relative; left: -269px;'>";
        }
        for (var j = 0; j < levels.length; j++) {
            var levelName = levels[j];

            if (RS.components.content.rsProductListSelector.levelNamesList.indexOf(levelName) == -1) {
                continue;
            }

            var productList_learnMore = RS.components.content.rsProductListSelector.getTextValue("productList_learnMore");
            var productList_todayOnly = RS.components.content.rsProductListSelector.getTextValue("productList_todayOnly");
            var productList_content = RS.components.content.rsProductListSelector.getTextValue("productList_content", levelName);
            var productList_alt = RS.components.content.rsProductListSelector.getTextValue("productList_alt", levelName);
            var productList_title = RS.components.content.rsProductListSelector.getTextValue("productList_title", levelName);
            var productList_link = RS.components.content.rsProductListSelector.getTextValue("productList_link", levelName);

            productList_learnMore = RS.components.content.rsProductListSelector.getTextValueFromLocalComponent("learnMoreText", productList_learnMore);
            productList_todayOnly = RS.components.content.rsProductListSelector.getTextValueFromLocalComponent("todayOnlyText", productList_todayOnly);
            productList_content = RS.components.content.rsProductListSelector.getTextValueFromLocalComponent("content_" + levelName, productList_content);
            productList_alt = RS.components.content.rsProductListSelector.getTextValueFromLocalComponent("tooltip_" + levelName, productList_alt);
            productList_title = RS.components.content.rsProductListSelector.getTextValueFromLocalComponent("title_" + levelName, productList_title);
            productList_link = RS.components.content.rsProductListSelector.getTextValueFromLocalComponent("link_" + levelName, productList_link);

            productList_learnMore = RS.components.content.rsProductListSelector.replaceLanguageToken(productList_learnMore, lang.longName);
            productList_todayOnly = RS.components.content.rsProductListSelector.replaceLanguageToken(productList_todayOnly, lang.longName);
            productList_content = RS.components.content.rsProductListSelector.replaceLanguageToken(productList_content, lang.longName);
            productList_alt = RS.components.content.rsProductListSelector.replaceLanguageToken(productList_alt, lang.longName);
            productList_title = RS.components.content.rsProductListSelector.replaceLanguageToken(productList_title, lang.longName);

            var prodimglevel = RS.components.content.rsProductListSelector.getProdImgLevel(levelName);
            var productDropDown = "";
            if (levelName == "TOT") {
                var productDropDownStyle = "padding: 2px 0; float: right; margin-right: 0; font-weight: normal;";
                if (RS.components.content.rsProductListSelector.displayType == "column") {
                    productDropDownStyle += "margin-top: -23px;";
                }
                productDropDown = "<select id='" + levelName + "' style='" + productDropDownStyle + "' id='selectTOT'><option value='03' selected='selected'>3 month access</option><option value='06'>6 month access</option></select><br>";
            }
            if (RS.components.content.rsProductListSelector.displayType == "column") {
                htmlInnerText = htmlInnerText +
                    "<li id='" + levelName + "'>\
                        <a title='" + productList_alt + "' rel='facebox' href='" + productList_link + "'><img src='" + productImgRef + "' class='prod-img tooltip' id='" + prodimglevel + "'/></a>" +
                    "<div style='float: left; width: 290px;' class='productDescription'>\
                 <strong><span class='hard'><a class='level-anchor' title='" + productList_alt + "' rel='facebox' href='" + productList_link + "'>" + productList_title + "</a></span></strong>&nbsp;&nbsp;<a title='" + productList_alt + "' rel='facebox' href='" + productList_link + "'>" + productList_learnMore + "</a><br/>\
                            " + productList_content + " <br/><br/>" + productDropDown + "\
                            <strong><span class='hard'>" + productList_todayOnly + " <span id='" + levelName + "priceDiscounted'></span></span> <span class='bright'>(Save $<span id='" + levelName + "priceDiscountAmt'></span>)</span></strong>\
                        </div>\
                        <div class='additem'>\
                            <form method='post' action='http://secure.rosettastone.com/store/cart' name='form" + levelName + "'>\
                                <input type='image' src='http://secure.rosettastone.com/us_assets/redesign/images/buttons/btn-add-to-cart-small.png' class='buynowbt' alt='Add to Cart' name='cart'/>\
                                <input type='hidden' value='' name='sku'/>\
                            </form>\
                        </div>\
                    </li>";
            }
            else if (RS.components.content.rsProductListSelector.displayType == "slide") {
                var buttonHeight = RS.components.content.rsProductListSelector.componentHeight - 35;
                var textHeight = buttonHeight - 130;

                htmlInnerText = htmlInnerText + "<div style='float: left; width: 269px; position:relative;' id='" + levelName + "' class='item-s5 productItem' >\
                      <div style='float: left; padding-bottom: 10px; width: 269px; position:relative;'>\
                          <div class='left' style='margin-right: 25px; _margin-right:0px;'>\
                            <div class='review-text' style='margin-top: -20px; margin-right: 9px; _margin-right:0px;'>\
                                 <div class='prod-cont-outer'>\
                                     <div class='prod-s3-cont' style='height: " + buttonHeight + "px'>\
                                        <h3><a class='level-anchor' title='" + productList_alt + "' rel='facebox' href='" + productList_link + "'>" + productList_title + "</a></h3>\
                                        <div class='prod-s3-cont-img' style='height: 93px'>\
                                           <a title='" + productList_alt + "' rel='facebox' href='" + productList_link + "'><img src='" + productImgRef + "' alt='" + productList_alt + "' id='" + prodimglevel + "'></a>\
                                           " + productDropDown + "<div class='prod-price'>\
                                               <strong style='width:180px;float:right'><span style='*float:left;*margin-left:-30px;' class='hard'>" + productList_todayOnly + " <span id='" + levelName + "priceDiscounted'></span></span><span class='bright'>(Save $<span id='" + levelName + "priceDiscountAmt'></span>)</span></strong>\
                                            </div> \
                                        </div>\
                                            <p style='height: " + textHeight + "px; border-left: 1px solid #cdcdcd; border-right: 1px solid #cdcdcd;'>" + productList_content + "&nbsp;<a title='" + productList_alt + "' rel='facebox' href='" + productList_link + "'>" + productList_learnMore + "</a></p>\
                                     </div>\
                                         <div class='blue-addcart'>\
                                           <form method='post' action='http://secure.rosettastone.com/store/cart' name='formL1'> \
                                              <input type='image' src='" + RS.components.content.rsProductListSelector.addToCartImageRef + "' class='cart_btn1' alt='Add to Cart' name='cart'> \
                                              <input type='hidden' value='' name='sku'> \
                                           </form> \
                                         </div> \
                                </div>\
                           </div>\
                       </div> \
                   </div>\
               </div>";
            }
        }
        if (RS.components.content.rsProductListSelector.displayType == "column") {
            htmlInnerText = htmlInnerText +
                "</ul>\
                    </div>\
                        <div style='display: none;' id='loading'><img src='http://secure.rosettastone.com/us_assets/redesign/images/newyear_10/now-loading.gif' alt='Loading...' style='margin: 50px 0px 0px 145px;'/></div>\
                        </div>\
                        </div>\
                     </div>";
        }
        else if (RS.components.content.rsProductListSelector.displayType == "slide") {
            htmlInnerText = htmlInnerText + "</div>\
                  </div>\
                  <div style='display:none; margin:auto; text-align:center; height:130px;' id='loading'><img src='http://secure.rosettastone.com/us_assets/redesign/images/newyear_10/now-loading.gif' alt='Loading...' style=''></div>\
                 </div>\
                </div>\
                <div style='clear:both'></div>";
        }
        rootDiv.append(htmlInnerText);
    },

    replaceLanguageToken : function(str, langReplacement) {
        if (str) {
            return ("" + str).replace(new RegExp(RS.components.content.rsProductListSelector.LANGUAGE_TOKEN, "g"), langReplacement);
        }
    },

    getTextValue : function (paramKey, levelName) {
        var result = null;

        if (levelName == undefined) {
            result = RS.components.content.rsProductListSelector.localization[paramKey];
        } else {
            result = RS.components.content.rsProductListSelector.localization[paramKey + "_" + levelName.toLowerCase()];
        }

        return result;
    },

    getTextValueFromLocalComponent : function (paramKey, defaultValue) {
        var content = RS.components.content.rsProductListSelector.productContent[paramKey];
        return content ? content : defaultValue;
    },

    getProdImgLevel : function(level) {
        var prodimglevel = "";
        switch (level) {
            case "L1":
            {
                prodimglevel = "prodimglevel-1";
                break;
            }
            case "L2":
            {
                prodimglevel = "prodimglevel-2";
                break;
            }
            case "L3":
            {
                prodimglevel = "prodimglevel-3";
                break;
            }
            case "L4":
            {
                prodimglevel = "prodimglevel-4";
                break;
            }
            case "L5":
            {
                prodimglevel = "prodimglevel-5";
                break;
            }
            case "S2":
            {
                prodimglevel = "prodimglevel-1-2";
                break;
            }
            case "S3":
            {
                prodimglevel = "prodimglevel-1-2-3";
                break;
            }
            case "S5":
            {
                prodimglevel = "prodimglevel-1-2-3-4-5";
                break;
            }
            case "U1":
            {
                prodimglevel = "prodimglevel-u1";
                break;
            }
            case "TOT":
            {
                prodimglevel = "prodimglevel-tot";
                break;
            }
            default:
                prodimglevel = "prodimglevel non";
        }
        return  prodimglevel;
    },

    resetProducts : function () {

        if (RS.components.content.rsProductListSelector.hasInitialized) {
            RS.components.content.rsProductListSelector.renderProducts();
        } else {
            return;
        }

        if ("slide" == RS.components.content.rsProductListSelector.displayType) {

            $('#example3').productSelectorBxSlider({mode: 'slide',speed: 250,wrapper_class: 'example2_container', width: 269,
                prev_img : RS.components.content.rsProductListSelector.leftArrowImageRef,
                next_img: RS.components.content.rsProductListSelector.rightArrowImageRef,
                button_height: RS.components.content.rsProductListSelector.componentHeight});

            if (document.getElementsByName('cart').length > 0) {
                var carts = document.getElementsByName('cart');
                for (var i = 0; i < carts.length; i++) {
                    carts[i].onmouseover = function() {
                        this.src = RS.components.content.rsProductListSelector.addToCartHoverImageRef;//"/content/dam/rosettastonecom/images/mt/quickbuy/addcart_green_s3.jpg";
                    };
                    carts[i].onmouseout = function() {
                        this.src = RS.components.content.rsProductListSelector.addToCartImageRef;//"/content/dam/rosettastonecom/images/mt/quickbuy/addcart_blue_s3.jpg";
                    };
                }
            }
            if (document.getElementById('sliderprev1') && document.getElementById('slidernext1')) {
                document.getElementById('sliderprev1').onmouseover = function() {
                    document.getElementById('sliderprev1').style.backgroundPosition = '0 -84px';
                    document.getElementById('left-img').src = RS.components.content.rsProductListSelector.leftArrowHoverImageRef;
                };
                document.getElementById('sliderprev1').onmouseout = function() {
                    document.getElementById('sliderprev1').style.backgroundPosition = '0 -14px';
                    document.getElementById('left-img').src = RS.components.content.rsProductListSelector.leftArrowImageRef;
                };
                document.getElementById('sliderprev1').onmousedown = function() {
                    document.getElementById('sliderprev1').style.backgroundPosition = '0 -153px';
                };
                document.getElementById('sliderprev1').onmouseup = function() {
                    document.getElementById('sliderprev1').style.backgroundPosition = '0 -84px';
                };
                document.getElementById('slidernext1').onmouseover = function() {
                    document.getElementById('slidernext1').style.backgroundPosition = '-19px -84px';
                    document.getElementById('right-img').src = RS.components.content.rsProductListSelector.rightArrowHoverImageRef;
                };
                document.getElementById('slidernext1').onmouseout = function() {
                    document.getElementById('slidernext1').style.backgroundPosition = '-19px -14px';
                    document.getElementById('right-img').src = RS.components.content.rsProductListSelector.rightArrowImageRef;
                };
                document.getElementById('slidernext1').onmousedown = function() {
                    document.getElementById('slidernext1').style.backgroundPosition = '-19px -153px';
                };
                document.getElementById('slidernext1').onmouseup = function() {
                    document.getElementById('slidernext1').style.backgroundPosition = '-19px -84px';
                };
            }
            if (document.getElementById('sliderprev') && document.getElementById('slidernext')) {
                document.getElementById('sliderprev').onmouseover = function() {
                    document.getElementById('sliderprev').style.backgroundPosition = '0 -84px';
                };
                document.getElementById('sliderprev').onmouseout = function() {
                    document.getElementById('sliderprev').style.backgroundPosition = '0 -14px';
                };
                document.getElementById('sliderprev').onmousedown = function() {
                    document.getElementById('sliderprev').style.backgroundPosition = '0 -153px';
                };
                document.getElementById('sliderprev').onmouseup = function() {
                    document.getElementById('sliderprev').style.backgroundPosition = '0 -84px';
                };
                document.getElementById('slidernext').onmouseover = function() {
                    document.getElementById('slidernext').style.backgroundPosition = '-19px -84px';
                };
                document.getElementById('slidernext').onmouseout = function() {
                    document.getElementById('slidernext').style.backgroundPosition = '-19px -14px';
                };
                document.getElementById('slidernext').onmousedown = function() {
                    document.getElementById('slidernext').style.backgroundPosition = '-19px -153px';
                };
                document.getElementById('slidernext').onmouseup = function() {
                    document.getElementById('slidernext').style.backgroundPosition = '-19px -84px';
                };
            }
        }
    }

};RSUI.components.content.rsProductListSelectorPrices = new Object();

RSUI.components.content.rsProductListSelectorPrices.globalContentUrl = "NOT_INITIALIZED";

RSUI.components.content.rsProductListSelectorPrices.init = function(globalContentUrl) {
    RSUI.components.content.rsProductListSelectorPrices.globalContentUrl = globalContentUrl;
};

RSUI.components.content.rsProductListSelectorPrices.globals = {
    ajax_price : {},
    firstCall : true,
    selectedLanguage : "",
    DEFAULT_LANGUAGE : "esp",
    NO_PROMO_CODE : "nopromo"
    //Such pages will send a request for a nopromo. So only the original prices would be displayed.
};

/* We should have the "describe" method for each and every component that we create. We can use it to display the description for the component somewhere inside the component or anywhere else.
 We can have it for all the objects that we create.
 */
RSUI.components.content.rsProductListSelectorPrices.describe = function() {
    return "The description for the component"
};

/*
 Getter/Setter functions for the Quick-Buy products lsit component
 */

RSUI.components.content.rsProductListSelectorPrices.getLanguageCodeForUrl = function(lang) {
    //return RSUI.globals.language_codes_for_urls.en[lang]; // this will change if store teh codes somehwere else
    //return RSUI.globals.language_codes_for_urls.de[lang]
    var siteName = RSUI.globals.sites[this.getSite()];
    return siteName.lang_code[lang];
};

RSUI.components.content.rsProductListSelectorPrices.setSelectedLanguage = function(language) {
    this.globals.selectedLanguage = language;
};

RSUI.components.content.rsProductListSelectorPrices.getSelectedLanguage = function() {
    return RSUI.components.content.rsProductListSelectorPrices.globals.selectedLanguage.toUpperCase();
};

// Assumes that a promo value will always be there for landing page
RSUI.components.content.rsProductListSelectorPrices.getPromoCode = function() {
    if (RSUI.util.getCookie("promo")) {
        window["promo"] = RSUI.util.getCookie("promo");
    }
    return ((typeof(window["promo"]) == "undefined") || (window["promo"] == "null") || (window["promo"] == "")) ?
        RSUI.components.content.rsProductListSelectorPrices.globals.NO_PROMO_CODE : window["promo"];
};

RSUI.components.content.rsProductListSelectorPrices.getVersion = function() {
    var lang = this.getSelectedLanguage().toLowerCase();
    if (jQuery.inArray(lang, RSUI.globals.v2Languages) != -1) {
        return "V2"
    } else if (jQuery.inArray(lang, RSUI.globals.v3Languages) != -1) {
        return "V3"
    } else {
        return "V4"
    }
};

// Assumes that the product list template on the right has a class set PE or HS for the container div
RSUI.components.content.rsProductListSelectorPrices.getVertical = function() {
    return (jQuery(".PE").length != 0) ? "PE" : "HS";
};

// Assumes that the product list template on the right has a class set EN or DE for the container div
RSUI.components.content.rsProductListSelectorPrices.getSite = function() {
    return (jQuery(".EN").length != 0) ? "EN" : "DE";
};

RSUI.components.content.rsProductListSelectorPrices.getSiteCode = function() {
    var siteName = RSUI.globals.sites[this.getSite()];
    return siteName.siteCode;
};

RSUI.components.content.rsProductListSelectorPrices.getSitePathForPrices = function() {
    return RSUI.components.content.rsProductListSelectorPrices.globalContentUrl + "cache/prices/";
};

RSUI.components.content.rsProductListSelectorPrices.getProductsList = function() {
    return $("div#products")
};

RSUI.components.content.rsProductListSelectorPrices.getLoadingImage = function() {
    return $("#loading")
};

RSUI.components.content.rsProductListSelectorPrices.getPriceDiff = function(actual_price, price_after_discount) {
    var site = this.getSiteCode();
    var prefix = "$".length;
    if (site == "DE_WEBSITE") {
        prefix = 6;
    }
    //replace '.' with ',' for the DE website
    var amount = actual_price.slice(prefix, actual_price.length).replace(',', '.') - price_after_discount.slice(prefix, price_after_discount.length).replace(',', '.');
    if (site == "DE_WEBSITE") {
        return (Math.round(amount * 100) / 100).toFixed(2).replace('.', ',')
    } else {
        return (Math.round(amount * 100) / 100).toFixed(2);
    }
};

RSUI.components.content.rsProductListSelectorPrices.getLangUrl = function() {
    var promo = RSUI.components.content.rsProductListSelectorPrices.getPromoCode();
    var lang = RSUI.components.content.rsProductListSelectorPrices.getSelectedLanguage();
    var edition = RSUI.components.content.rsProductListSelectorPrices.getVertical();
    var siteCode = RSUI.components.content.rsProductListSelectorPrices.getSiteCode();
    var globalContentUrl = RSUI.components.content.rsProductListSelectorPrices.globalContentUrl;
    var url = "/rosettastone/prices.json?promo=" + promo + "&langCode=" + lang + "&edition=" + edition + "&siteCode=" + siteCode + "&globalContentUrl=" + globalContentUrl;
    return encodeURI(url);
};

RSUI.components.content.rsProductListSelectorPrices.getAllLinksFromProductsList = function() {
    var links = jQuery(".productContainer a");

    for (var i = 0; i < links.length; i++) {
        var link = links[i];
        if (link.id == 'slidernext1' || link.id == 'sliderprev1') {
            links.splice(i, 1);
            i--;
        }
    }
    return links;
};

RSUI.components.content.rsProductListSelectorPrices.getPersonalV2Urls = function() {
    return "/learn-" + RSUI.components.content.rsProductListSelectorPrices.getLanguageCodeForUrl(RSUI.components.content.rsProductListSelectorPrices.getSelectedLanguage().toLowerCase());
};

RSUI.components.content.rsProductListSelectorPrices.getLanguageFromUrlString = function(url) {
    var path = url;
    var siteName = RSUI.globals.sites[RSUI.components.content.rsProductListSelectorPrices.getSite()];
    if (siteName.siteCode == "DE_WEBSITE") {
        return path.slice(path.lastIndexOf("de/") + 3, path.lastIndexOf("-lernen/"));
    }
    return path.slice(path.indexOf("-") + 1, path.lastIndexOf("/"));
};

/*
 End of Getter/Setter Functions
 */

RSUI.components.content.rsProductListSelectorPrices.showLoadingHideList = function() {
    RSUI.components.content.rsProductListSelectorPrices.getProductsList().hide();
    RSUI.components.content.rsProductListSelectorPrices.getLoadingImage().show();
};

RSUI.components.content.rsProductListSelectorPrices.hideAllProducts = function() {
    RSUI.components.content.rsProductListSelectorPrices.getProductsList().find("li,div.productItem").hide()
};

RSUI.components.content.rsProductListSelectorPrices.showAllProducts = function() {
    RSUI.components.content.rsProductListSelectorPrices.getProductsList().find("li,div.productItem").show();
};

RSUI.components.content.rsProductListSelectorPrices.hideLoadingShowList = function() {
    RSUI.components.content.rsProductListSelectorPrices.getProductsList().show();
    RSUI.components.content.rsProductListSelectorPrices.getLoadingImage().hide();
};

RSUI.components.content.rsProductListSelectorPrices.replaceLangauagePlaceHolder = function() {
    var language = RSUI.components.page.getLanguageInDropDown();
    jQuery("#qb-language").html(language + " "); // Add space to fix IE7 issue.
};

RSUI.components.content.rsProductListSelectorPrices.showProductsForLanguage = function(levelName) {
    $("div#products li#" + levelName + ",div#products div#" + levelName).show()
};

RSUI.components.content.rsProductListSelectorPrices.showDiscountedPrice = function(levelName, testPrice) {
    $("#" + levelName + "priceDiscounted").html(testPrice);
};

RSUI.components.content.rsProductListSelectorPrices.showSavedAmount = function(levelName, price, testPrice) {
    var saved_amount = RSUI.components.content.rsProductListSelectorPrices.getPriceDiff(price, testPrice);
    if (saved_amount.replace(',', '.') != 0) {
        $("#" + levelName + " span.bright").show();
        $("#" + levelName + "priceDiscountAmt").html(saved_amount);
    } else {
        $("#" + levelName + " span.bright").hide();
    }
};

RSUI.components.content.rsProductListSelectorPrices.updateProductSkus = function(levelName, sku) {
    $("#" + levelName + " input[name='sku']")[0].value = sku;
};

RSUI.components.content.rsProductListSelectorPrices.selectLanguage = function(lang) {
    if (RSUI.components.content.rsProductListSelectorPrices.globals.firstCall) {
        if (RS.components.content.rsProductListSelector && RS.components.content.rsProductListSelector.hasInitialized) {
            RS.components.content.rsProductListSelector.resetProducts();
        }
        RSUI.components.content.rsProductListSelectorPrices.makeFirstAjaxCall();
        RSUI.components.content.rsProductListSelectorPrices.globals.firstCall = false;
    } else {
        RSUI.components.content.rsProductListSelectorPrices.setSelectedLanguage(lang);
        if (RS.components.content.rsProductListSelector && RS.components.content.rsProductListSelector.hasInitialized) {
            RS.components.content.rsProductListSelector.resetProducts();
        }
        RSUI.components.content.rsProductListSelectorPrices.makeAjaxCallForProducts();
        RSUI.components.content.rsProductListSelectorPrices.replaceLangauagePlaceHolder();
    }
};

RSUI.components.content.rsProductListSelectorPrices.processProduct = function(levelName, product) {
    RSUI.components.content.rsProductListSelectorPrices.showProductsForLanguage(levelName);
    RSUI.components.content.rsProductListSelectorPrices.showDiscountedPrice(levelName, product.prices[1].testPrice);
    RSUI.components.content.rsProductListSelectorPrices.showSavedAmount(levelName, product.prices[0].price, product.prices[1].testPrice);
    RSUI.components.content.rsProductListSelectorPrices.updateProductSkus(levelName, product.sku);
};

//Complete Online Access Products
RSUI.components.content.rsProductListSelectorPrices.COAProducts = [];

RSUI.components.content.rsProductListSelectorPrices.populateProducts = function(data) {
    if (data != null && data != '') {
        var tmpEval;
        /*because eval doesnt work good with global context in IE*/
        eval("tmpEval = " + data);
        RSUI.components.content.rsProductListSelectorPrices.globals.ajax_price.items = tmpEval;
        ajax_price = RSUI.components.content.rsProductListSelectorPrices.globals.ajax_price;
        var itemsCount = ajax_price.items == undefined ? 0 : ajax_price.items.length;
        //console.log("rsProductListSelectorPrices.populateProducts ajax_price.items.count="+itemsCount);
        RSUI.components.content.rsProductListSelectorPrices.hideLoadingShowList();

        RSUI.components.content.rsProductListSelectorPrices.COAProducts = [];

        for (var i = 0; i < itemsCount; i++) {
            if ("03" == ajax_price.items[i].level || "06" == ajax_price.items[i].level) {
                RSUI.components.content.rsProductListSelectorPrices.COAProducts.push(ajax_price.items[i]);
                ajax_price.items.splice(i, 1);
                i--;
                itemsCount--;
            }
        }

        RSUI.components.content.rsProductListSelectorPrices.processCOAProduct();

        for (index = 0; index < itemsCount; index++) {
            if ($("#" + ajax_price.items[index].level).length != 0) {
                RSUI.components.content.rsProductListSelectorPrices.processProduct(ajax_price.items[index].level, ajax_price.items[index])
            }
        }

        //TODO: fix it
        RSUI.components.content.rsProductListSelectorPrices.addFaceboxFunctionality();
//        RSUI.components.content.rsProductListSelectorPrices.setLinkUrls();
    }
};

//Complete Online Access Level Names
RSUI.components.content.rsProductListSelectorPrices.COALevelName = "TOT";

//Process Complete Online Access Products
RSUI.components.content.rsProductListSelectorPrices.processCOAProduct = function() {

    var isComponentExist = 0 < $("div#products li#" + RSUI.components.content.rsProductListSelectorPrices.COALevelName + ",div#products div#" + RSUI.components.content.rsProductListSelectorPrices.COALevelName).length;

    if (RSUI.components.content.rsProductListSelectorPrices.COAProducts.length > 0 && isComponentExist) {
        var completeOnlineAccessOptions = "";
        for (var j = 0; j < RSUI.components.content.rsProductListSelectorPrices.COAProducts.length; j++) {

            var pr = RSUI.components.content.rsProductListSelectorPrices.COAProducts[j];
            var levelName = pr.level;
            var content = levelName == "03" ? "3 month access" : "6 month access";

            completeOnlineAccessOptions += '<option value="' + pr.level + '">' + content + '</option>';
        }

        var selectTag = jQuery("div#products select#" + RSUI.components.content.rsProductListSelectorPrices.COALevelName);
        selectTag.html(completeOnlineAccessOptions);
        selectTag.change(RSUI.components.content.rsProductListSelectorPrices.changeCOASelect);

        RSUI.components.content.rsProductListSelectorPrices.processProduct(RSUI.components.content.rsProductListSelectorPrices.COALevelName,
            RSUI.components.content.rsProductListSelectorPrices.COAProducts[0]);
    }
};

//Event on change COA select tag
RSUI.components.content.rsProductListSelectorPrices.changeCOASelect = function() {
    var levelName = $(this).children("option:selected").val();

    var product = null;
    //find product with levelName in array
    for (var i = 0; i < RSUI.components.content.rsProductListSelectorPrices.COAProducts.length; i++) {
        product = RSUI.components.content.rsProductListSelectorPrices.COAProducts[i];
        if (product.level == levelName) {
            break;
        }
    }

    RSUI.components.content.rsProductListSelectorPrices.processProduct(RSUI.components.content.rsProductListSelectorPrices.COALevelName, product);
};

RSUI.components.content.rsProductListSelectorPrices.addFaceboxFunctionality = function() {
    RSUI.components.content.rsProductListSelectorPrices.getAllLinksFromProductsList().unbind();
    addFaceBoxListener(); // needs to be changed after we modify productLightBox.js
};

RSUI.components.content.rsProductListSelectorPrices.removeFaceboxFunctionality = function() {
    RSUI.components.content.rsProductListSelectorPrices.getAllLinksFromProductsList().unbind();
};

RSUI.components.content.rsProductListSelectorPrices.setLinkUrlsForV2 = function() {
    var url = RSUI.components.content.rsProductListSelectorPrices.getPersonalV2Urls();
    var links = RSUI.components.content.rsProductListSelectorPrices.getAllLinksFromProductsList();
    RSUI.components.content.rsProductListSelectorPrices.removeFaceboxFunctionality();
};

RSUI.components.content.rsProductListSelectorPrices.setLinkUrlsForV3V4 = function() {
    var links = RSUI.components.content.rsProductListSelectorPrices.getAllLinksFromProductsList();
    var obj = this;
    RSUI.components.content.rsProductListSelectorPrices.addFaceboxFunctionality();
};

RSUI.components.content.rsProductListSelectorPrices.setHomeSchoolLinkUrls = function() {
    var stringToBeReplaced;
    var repalcement;
    var links = RSUI.components.content.rsProductListSelectorPrices.getAllLinksFromProductsList();
    var language = RSUI.components.content.rsProductListSelectorPrices.getSelectedLanguage().toLowerCase();
    var obj = this;
    links.each(function() {
        stringToBeReplaced = obj.getLanguageFromUrlString(RSUI.components.content.rsProductListSelectorPrices.href);
        repalcement = obj.getLanguageCodeForUrl(language);
        RSUI.components.content.rsProductListSelectorPrices.href = RSUI.components.content.rsProductListSelectorPrices.href.replace(stringToBeReplaced, repalcement)
    })
};

RSUI.components.content.rsProductListSelectorPrices.setDELinkUrls = function() {
    RSUI.components.content.rsProductListSelectorPrices.setHomeSchoolLinkUrls();
};

RSUI.components.content.rsProductListSelectorPrices.setLinkUrls = function() {
    var isHomeSchool = (RSUI.components.content.rsProductListSelectorPrices.getVertical() == "HS");
    var siteName = RSUI.globals.sites[RSUI.components.content.rsProductListSelectorPrices.getSite()];
    if (siteName.siteCode == "DE_WEBSITE") {
        RSUI.components.content.rsProductListSelectorPrices.setDELinkUrls();
        RSUI.components.content.rsProductListSelectorPrices.removeFaceboxFunctionality();
    } else if (isHomeSchool) {
        RSUI.components.content.rsProductListSelectorPrices.setHomeSchoolLinkUrls();
        RSUI.components.content.rsProductListSelectorPrices.removeFaceboxFunctionality();
    } else {
        var version = RSUI.components.content.rsProductListSelectorPrices.getVersion();
        if (version == "V3" || version == "V4") {
            RSUI.components.content.rsProductListSelectorPrices.setLinkUrlsForV3V4();
        } else if (version == "V2") {
            RSUI.components.content.rsProductListSelectorPrices.setLinkUrlsForV2();
        }
    }
};

RSUI.components.content.rsProductListSelectorPrices.makeAjaxCallForProducts = function() {

    var promoCode = RSUI.components.content.rsProductListSelectorPrices.getPromoCode();
    RSUI.components.content.rsProductListSelectorPrices.hideAllProducts();
    RSUI.components.content.rsProductListSelectorPrices.showLoadingHideList();
    RSUI.components.content.rsProductListSelectorPrices.showAllProducts();
    var obj = this;
    jQuery.ajax({
        url:obj.getLangUrl(),
        success: function(data) {
            //console.log("Fetching prices successful.")
            obj.populateProducts(data);
        },
        error:function(e) {
            console.log("An error occured while fetching prices.");
        }
    });
};


RSUI.components.content.rsProductListSelectorPrices.makeFirstAjaxCall = function() {
    var language = RSUI.util.getParamFromLandingPageUrl('language');
    language = (language == "") ? RSUI.components.page.getLanguageCodeFromDropDown() : language;
    language = (language == "") ? RSUI.components.content.rsProductListSelectorPrices.globals.DEFAULT_LANGUAGE : language;
    RSUI.components.content.rsProductListSelectorPrices.setSelectedLanguage(language);
    RSUI.components.content.rsProductListSelectorPrices.makeAjaxCallForProducts();
    // next line should be avoided by changing the template.
    if (jQuery(".productDescription:contains('[Language]')").length > 0) {
        jQuery(".productDescription:contains('[Language]')").html(jQuery(".productDescription:contains('[Language]')").html().replace("[Language]", '<span id="qb-language"></span>'))
    }
    RSUI.components.content.rsProductListSelectorPrices.replaceLangauagePlaceHolder();
};

RSUI.components.content.rsProductListSelectorPrices.getMainLayer = function() {
    return $("div.productListSelector");
};

RSUI.components.content.rsProductListSelectorPrices.hide = function() {
    RSUI.components.content.rsProductListSelectorPrices.getMainLayer().hide();
};

RSUI.components.content.rsProductListSelectorPrices.show = function() {
    RSUI.components.content.rsProductListSelectorPrices.getMainLayer().show(1000);
};
RS.components.content.rsLightBoxLink = {

// field id's used in the rsLinkDialog.js
    paramNames : {
        widthId : "lbWidthId",
        useLightBoxId : "useLightBoxId",
        linkAttributeName : "lightBoxLink",
        hrefId: "href",
        lightBoxCheckboxId : "lightBoxCheckboxId",
        fixedHeightId : "fixedHeightId",
        displayTitleId : "displayTitleId",
        titleId : "titleId",

        heightTypeRadioGroupId : "heightTypeRadioGroupId",
        heightAutoRadioId: "heightAutoRadioId",
        heightFixedRadioId : "heightFixedRadioId",

        toolTipId : "toolTipId",
        isVideoId : "isVideoId",
        screenMasColorId: "screenMasColorId",
        screenMasOpacity: "screenMasOpacity",
        themesId: "themesId",

        speedTypeRadioGroupId: "speedTypeRadioGroupId",
        speedSlowRadioId : "speedSlowRadioId",
        speedNormalRadioId : "speedNormalRadioId",
        speedFastRadioId : "speedFastRadioId",

        positionYId : "positionYId",
        positionXId : "positionXId",
        ccsClassId : "ccsClassId",

        positionRadioGroupId : "positionRadioGroupId",
        positionScrollRadioId : "positionScrollRadioId",
        positionFixedRadioId : "positionFixedRadioId"
    },

    THEME_TYPE : { basic: "basic", facebox : "facebox"},
    LB_OVERLAY_DIV_CLASS : "lightBoxOverlay",

//    privet
    getValueFromAttribute : function (element, attrKey, defaultValue) {
        if (defaultValue == undefined) {
            defaultValue = "";
        }

        var value = $(element).attr(attrKey);
        if (value == undefined || value.length == 0) {
            value = defaultValue;
        }

        return value;
    },

//    private
    getBackgroundImage : function(themeType) {
        var backgroundImage = "";
        if (themeType == RS.components.content.rsLightBoxLink.THEME_TYPE.basic) {
            backgroundImage = "/etc/designs/rosettastone/images/components/content/rsLightBoxLink/transparent.png";
        } else if (themeType == RS.components.content.rsLightBoxLink.THEME_TYPE.facebox) {
            backgroundImage = "/etc/designs/rosettastone/images/components/content/rsLightBoxLink/transparent2.png";
        }
        return backgroundImage

    },

//    private
    isInt : function(x) {
        var y = parseInt(x);
        if (isNaN(y)) return false;
        return x.toString() == y.toString();
    },

//    private
    getSpeedValue: function(speedParam) {
        switch (speedParam) {
            case RS.components.content.rsLightBoxLink.paramNames.speedFastRadioId:
                return "fast";
            case RS.components.content.rsLightBoxLink.paramNames.speedNormalRadioId:
                return "normal";
            case RS.components.content.rsLightBoxLink.paramNames.speedSlowRadioId:
                return "slow";
            default:
                return null;
        }
    },

//    private
    addOverlayDiv : function (index, theme) {

        if ($("div." + RS.components.content.rsLightBoxLink.LB_OVERLAY_DIV_CLASS + "[lb_num=" + index + "]").length == 0) {

            var backgroundImage = RS.components.content.rsLightBoxLink.getBackgroundImage(theme);

            if (theme == RS.components.content.rsLightBoxLink.THEME_TYPE.basic) {
                $("body").append(
                    '<div lb_num="' + index + '" class="' + RS.components.content.rsLightBoxLink.LB_OVERLAY_DIV_CLASS + '" style="display: none; padding: 40px; background-image: url(' + backgroundImage + ');"> \
                         <p class="title"></p> \
                         <div class="contentWrap"></div>   \
                    </div>');
            } else if (theme == RS.components.content.rsLightBoxLink.THEME_TYPE.facebox) {
                $("body").append(
                    '<div lb_num="' + index + '" class="' + RS.components.content.rsLightBoxLink.LB_OVERLAY_DIV_CLASS + '" style="display: none; padding: 40px; background-image: url(' + backgroundImage + ');"> \
                            <div id="lightBox" class=""> \
                            <div class="popup"> \
                            <table>          \
                                <tbody>       \
                                    <tr>           \
                                        <td class="tl"></td> \
                                        <td class="b"></td> \
                                        <td class="tr"></td> \
                                    </tr> \
                                    <tr> \
                                        <td class="b"></td>\
                                        <td class="body">\
                                            <div class="footer" style="display: block; "> \
                                            <p class="heading"><p class="title"></p></p> \
                                                <a href="#image" class="close" style="background-image: none; top: 10px; margin-left: -75px;"> \
                                                <img src="/content/dam/rosettastone_shared/images/facebox/closelabel.gif" title="close" class="close_image"></a></div><div class="content" style="display: block; "> \
                                                <div class="contentWrap"></div> \
                                            </div> \
                                        </td> \
                                        <td class="b"></td> \
                                    </tr> \
                                    <tr> \
                                        <td class="bl"></td> \
                                        <td class="b"></td> \
                                        <td class="br"></td> \
                                    </tr> \
                                </tbody> \
                            </table> \
                            </div> \
                            </div> \
                    </div>');
            }
        }
    },


    /**
     * Public method.
     * Associates the links contained parameter lightBoxLink=true with LightBoxes
     */
    applyLightBoxes : function() {
        $("a[lightBoxLink*=true]").each(function(index, element) {
            $(element).attr("rel", "div." + RS.components.content.rsLightBoxLink.LB_OVERLAY_DIV_CLASS + ":eq(" + index + ")");

/* *******************START READING THE SETTINGS CONTAINED AT THE TAG <a>*****************************  */
            var theme = RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.themesId, "basic");

            RS.components.content.rsLightBoxLink.addOverlayDiv(index, theme);

            var width = parseInt(RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.widthId, 600));

            var isFixedHeight = RS.components.content.rsLightBoxLink.paramNames.heightFixedRadioId == RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.heightTypeRadioGroupId, RS.components.content.rsLightBoxLink.paramNames.heightFixedRadioId);
            var height = parseInt(RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.fixedHeightId, 400));
            if (!isFixedHeight) {
                height = 400;
            }

            var tooltip = RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.toolTipId);
            $(element).attr("title", tooltip);

            var isVideo = "true" == RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.isVideoId, "false");

            if (isVideo) {

                var href = $(this).attr("href");

                var flowkey = "#@4febdbbf4825e91674c";

                var player = $(".contentWrap:eq(" + index + ")").flowplayer({src: "/etc/designs/rosettastone/javascript/util/flowplayer-3.2.7.swf", wmode: 'transparent'}, {
                    key: flowkey,
                    cachebusting: true,
                    contextMenu: [
                        'Rosetta Stone video player'
                    ],
                    plugins:  {
                        controls:  {
                            url: '/etc/designs/rosettastone/javascript/util/flowplayer.controls-air-3.2.5.swf'
                        }
                    },
                    playlist: [
                        href
                    ]
                });
            }
            var opacity = RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.screenMasOpacity, 0.8);

            var screenColor = RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.screenMasColorId, "FFFFFF");
            var isFixedPosition = RS.components.content.rsLightBoxLink.paramNames.positionFixedRadioId == RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.positionRadioGroupId, RS.components.content.rsLightBoxLink.paramNames.positionFixedRadioId);
            var isDisplayTitle = "true" == RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.displayTitleId, false);
            var title = RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.titleId, "");

            var cssClass = RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.ccsClassId);
            $(element).attr("class", $(element).attr("class") + " " + cssClass);

            var defaultHorizontalPos = "center";
            var positionFromLeft = RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.positionXId, defaultHorizontalPos);
            if (RS.components.content.rsLightBoxLink.isInt(positionFromLeft)) {
                positionFromLeft = parseInt(positionFromLeft);
            }

            var defaultVerticalPos = "10%";
            var positionFromTop = RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.positionYId, defaultVerticalPos);
            if (RS.components.content.rsLightBoxLink.isInt(positionFromTop)) {
                positionFromTop = parseInt(positionFromTop);
            }

            var speed = RS.components.content.rsLightBoxLink.getSpeedValue(RS.components.content.rsLightBoxLink.getValueFromAttribute(element, RS.components.content.rsLightBoxLink.paramNames.speedTypeRadioGroupId, RS.components.content.rsLightBoxLink.paramNames.speedNormalRadioId));

/* *******************FINISH READING THE SETTINGS CONTAINED AT THE TAG <a>*****************************  */

            $(element).overlay({

                left: positionFromLeft,
                top: positionFromTop,
                oneInstance: false,
                mask: {
                    color: "#" + screenColor,
                    opacity: opacity
                },
                effect: 'apple',
                fixed: isFixedPosition,
                speed: speed,

                onBeforeLoad: function() {

                    var overlay = this.getOverlay();
                    $(overlay).css("width", width - 160);
                    $(overlay).css("height", height - 80);

                    var titleTag = overlay.find(".title");
                    $(titleTag).html(title);
                    var titleHeight = 0;
                    if (isDisplayTitle) {
                        $(titleTag).css("display", "block");
                        titleHeight = parseInt($(titleTag).css("line-height")) + parseInt($(titleTag).css("padding-bottom"))
                            + parseInt($(titleTag).css("padding-top")) + parseInt($(titleTag).css("margin-bottom"))
                            + parseInt($(titleTag).css("margin-top"));

                    } else {
                        $(titleTag).css("display", "none");
                    }

                    // grab wrapper element inside content
                    var closer = this.getClosers();
                    closer.css("left", width - 40);

                    var wrap = overlay.find(".contentWrap");
                    var wrapWidth = width - 80;
                    $(wrap).css("width", wrapWidth);
                    var wrapHeight = height - 80 - titleHeight;
                    $(wrap).css("height", wrapHeight);

                    if (!isVideo) {
                        //show processing image
                        wrap.html('<img style="top:' + (wrapHeight / 2 - 32) + 'px; left:' + (wrapWidth / 2 - 32) + 'px; position:relative;" src="/etc/designs/rosettastone/us/images/facebox/loading.gif" />');

                        // load the page specified in the trigger
                        wrap.load(this.getTrigger().attr("href"));

                    }
                },
                onLoad: function() {
                    if (isVideo) {
                        //run player
                        player.load();
                    }
                    var lbImg = $("img[src*='" + RS.components.content.rsLightBoxLink.getBackgroundImage(theme) + "']");
                    lbImg.css("height", height);

                },
                onClose: function() {
                    if (isVideo) {
                        //unload video
                        $f().unload();
                    }
                }
            });
        });
    }
};
