var videoOverlayCache = null;

/**************/
/** designJS **/
/**************/

if (typeof(console) == "undefined") 
{ 
	console = { "log": function () {} }; 
};

var isIE8 = function()
{
	// right now this also returns true for IE9 (necessary because we are using IE8Emulation-mode but IE9 Browser Mode)
	return jQuery.browser.msie && jQuery.browser.version.indexOf("8") != -1;
};

var arrayMerge = function (/* arrays */) 
{
    var newArr = [];
    for (var i=0; i<arguments.length; i++) 
    {
        var tmpArr = arguments[i];
        for (var j=0;j<tmpArr.length;j++) 
        {
        	newArr[newArr.length] = tmpArr[j];
        }
    }
    return newArr;
};

var partial = function (/** func, [param[, param [,...]]] */) 
{
    var func = arguments[0];
    var tmpArr = [];
    for (var i=1; i<arguments.length;i++) 
    {
        tmpArr[tmpArr.length] = arguments[i];
    }
    return function () { return func.apply(this,arrayMerge(tmpArr,arguments)); };
};

/*
Dummywidget-API v2.1
*/  var maria_sellaround_widget;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
maria_sellaround_widget = (function() {
/*
      the first parameter 'arrayIndex' is kind of deprecated, nonetheless it is still available for backwards-compatibility
      In this version of the widgetApi it is only used for the element-id of the iframe
      
      @param elemId: the unique-part of the element-id for the widget-iframe
      @param data: a data object as it normally comes from the widgetData REST-Call
      @param domContainer: a reference to the container element in the DOM where this widget should get appended to
  */    function maria_sellaround_widget(elemId, data, domContainer) {
this._onWidgetReady = __bind(this._onWidgetReady, this);
console.log("[maria_sellaround_widget] Initializing widget with elemId '" + elemId + "'");
this.iframe = jQuery("<iframe />");
this.iframe.attr({
  "class": "widgetIFrame",
  scrolling: 'no',
  id: 'maria_sellaround_widgetDummy_' + elemId,
  frameborder: '0',
  border: '0',
  allowtransparency: 'true'
});
if (location.href.substr(0, 34) === 'http://sellaround.staging.top21.de' || location.href.substr(0, 16) === 'http://localhost') {
  this.iframe.attr('src', '/widget_test.html');
} else {
  this.iframe.attr('src', '/widget.html');
}
this.iframe.css({
  border: 'none',
  overflow: 'hidden',
  width: '320px',
  height: '415px',
  background: 'none'
});
this.widget = false;
this.widgetReady = false;
this.initialData = data;
this.elemId = elemId;
this.iframe.load(__bind(function(e) {
  var iframe, y;
  iframe = e.currentTarget;
  y = iframe.contentWindow != null ? iframe.contentWindow : iframe.contentDocument != null ? iframe.contentDocument : void 0;
  if (y == null) {
   console.log("[maria_sellaround_widget] FATAL ERROR: could not initialize the iframe-handle - exiting");
    return;
  }
  if (y.document) {
    y = y.document;
  }
  this.widget = 'defaultView' in y? y.defaultView : y.parentWindow;
  return this.widget.$(this.widget.window).bind("widgetReady", this._onWidgetReady);
}, this));
domContainer.append(this.iframe);
}
maria_sellaround_widget.prototype._onWidgetReady = function() {
this.widget = this.widget.sellaroundDummyWidget;
this.widget.newDummyData(this.initialData);
return this.widgetReady = true;
};
/*
      simply pass the dataSetter through
  */
maria_sellaround_widget.prototype.newDummyData = function(data) {
if (data == null) {
 console.log("[maria_sellaround_widget] newDummyData requires at least one param: data, which is a complete dataset for the widget at elemId '" + this.elemId + "'");
  return;
}
if (!this.widgetReady) {
 console.log("[maria_sellaround_widget] widget with elemId '" + this.elemId + "' ignoring newDummyData call, as the widget is not ready yet");
  return;
}
return this.widget.newDummyData(data);
};
maria_sellaround_widget.prototype.updateSingleData = function(field, newVal, index) {
if (!((field != null) && (newVal != null))) {
 console.log("[maria_sellaround_widget] updateSingleData requires at least two params: field and newVal at elemId '" + this.elemId + "'");
  return;
}
if (!this.widgetReady) {
 console.log("[maria_sellaround_widget] widget with elemId '" + this.elemId + "' ignoring updateSingleData call, as the widget is not ready yet");
  return;
}
return this.widget.updateSingleData(field, newVal, index);
};
maria_sellaround_widget.prototype.updateMultiData = function(newData) {
if (newData == null) {
 console.log("[maria_sellaround_widget] updateMultiData requires at least one param: newData at elemId '" + this.elemId + "'");
  return;
}
if (!this.widgetReady) {
 console.log("[maria_sellaround_widget] widget with elemId '" + this.elemId + "' ignoring updateMultiData call, as the widget is not ready yet");
  return;
}
return this.widget.updateMultiData(newData);
};
return maria_sellaround_widget;
})();


/*

    beautiful checkboxes (M.Schneider)

*/
//define some static values
var beautifyCheckBox_alt = { 'checked': '[x]', 'unchecked': '[ ]' };
var beautifyCheckBox_imgs = { 'checked': '/_images/checkboxChecked.gif', 'unchecked': '/_images/checkbox.gif' };

var beautifyCheckBox_updateCheckboxProxy = function (id) {
    var elem = jQuery("#"+id);
    var proxy = jQuery ("#beautifyCheckBox_"+id+"_proxy");
    
    //detect the checkbox state
    var alt = beautifyCheckBox_alt['unchecked'];
    var src = beautifyCheckBox_imgs['unchecked'];
    if (elem.is(":checked")) {
        alt = beautifyCheckBox_alt['checked'];
        src = beautifyCheckBox_imgs['checked'];
    }
    
    //update the proxy
    proxy.attr('alt',alt);
    proxy.attr('src',src);
    
};

var beautifyCheckBox_proxyClick = function (id) {
    var elem = jQuery("#"+id);
    if (elem.is(":checked")) {
        elem.attr("checked",false);
    } else {
        elem.attr("checked",true);
    }
    
    elem.trigger('change');
};

var beautifyCheckBox = function (id,elem) {
    //if the checkbox has no id, generate a random one
    if (jQuery(elem).attr('id') == "") {
        id = Math.round((new Date).getTime()+Math.random ());
        jQuery(elem).attr("id",id);
    } else {
        id = jQuery(elem).attr('id');
    }
    
    //hide the original checkbox
    jQuery(elem).css('display','none');
    
    //detect the initial checkbox state
    var alt = beautifyCheckBox_alt['unchecked'];
    var src = beautifyCheckBox_imgs['unchecked'];
    if (jQuery(elem).is(":checked")) {
        alt = beautifyCheckBox_alt['checked'];
        src = beautifyCheckBox_imgs['checked'];
    }
    
    var tmp = "<img id='beautifyCheckBox_"+id+"_proxy' style='display:none;cursor:pointer;' class='"+jQuery(elem).attr("class")+"' src='' alt='' />";
    
    //add the checkbox-proxy-img to the dom
    jQuery(elem).after(tmp);
    
    //update the proxy state 
    beautifyCheckBox_updateCheckboxProxy(id);
    
    //add the callbacks
    jQuery(elem).change(partial(beautifyCheckBox_updateCheckboxProxy,id));
    jQuery("#beautifyCheckBox_"+id+"_proxy").click(partial(beautifyCheckBox_proxyClick,id));
    
    //show the checkbox-proxy
    jQuery("#beautifyCheckBox_"+id+"_proxy").show();
};

var sellaround_datepicker = function (index, initialStartDate, initialEndDate, monthfield) 
{    
    var elemYear = [ "<option>", "</option>" ];
    var elemMonth = [ "<option>", "</option>" ];
    var elemDay = [ "<td><span><span>", "</span></span></td>" ];
    var elemHighlightedDay = ['<td class="active"><span><span>', '</span></span></td>'];
    var elemEmptyDay = "<td><span><span>&nbsp;</span></span></td>";
    
    var startDate = initialStartDate;
    var endDate = initialEndDate;
    
    var curStartMonth = startDate.getMonth();
    var curStartYear = startDate.getFullYear();
    var curEndMonth = endDate.getMonth();
    var curEndYear = endDate.getFullYear();
    
    var addZero = function (value) 
    {
        if (value<10) 
        {
            return "0"+value;
        } 
        else 
        {
            return value;
        }
    };
    
    var dateObjToString = function (date) 
    {
        return date.getFullYear()+"-"+addZero(date.getMonth()+1)+"-"+addZero(date.getDate());
    };
    
    var updateField = function (which,value) 
    {
    	// set value and fire value change event (to force chart plotting)
    	jQuery("#"+which+"date_"+index).val(dateObjToString(value)).change(); 
        
        if (which == "start") 
        {
            startDate = value;
            curStartMonth = startDate.getMonth();
            curStartYear = startDate.getFullYear();
        } 
        else 
        {
            endDate = value;
            curEndMonth = endDate.getMonth();
            curEndYear = endDate.getFullYear();
        }
    };
    
    var initialized = false;
    var d = new Date();
    
    var myStartEngine = new datepicker_engine(elemYear,elemMonth,elemDay,elemHighlightedDay,elemEmptyDay,1,monthfield);
    var startYearlist = myStartEngine.getYearListing(2009,d.getFullYear());
    var startMonthlist = myStartEngine.getMonthListing();
    
    var myEndEngine = new datepicker_engine(elemYear,elemMonth,elemDay,elemHighlightedDay,elemEmptyDay,1,monthfield);
    var endYearlist = myEndEngine.getYearListing(2010,d.getFullYear());
    var endMonthlist = myEndEngine.getMonthListing();
    
    var startYearWidget = jQuery("#contentWidgetOptionsDateTimeStartYear_"+index);
    for (var i=0;i<startYearlist.length;i++) {
    	startYearWidget.append(startYearlist[i]).find("option:last-child").attr("value",i);
        if (myStartEngine.getYearIndex(startDate.getFullYear()) == i) {
        	startYearWidget.find("option:last-child").attr("selected","selected");
        }
    }
    var endYearWidget = jQuery("#contentWidgetOptionsDateTimeEndYear_"+index);
    for (var i=0;i<endYearlist.length;i++) {
    	endYearWidget.append(endYearlist[i]).find("option:last-child").attr("value",i);
        if (myEndEngine.getYearIndex(endDate.getFullYear()) == i) {
            endYearWidget.find("option:last-child").attr("selected","selected");
        }
    }
    var startMonthWidget = jQuery("#contentWidgetOptionsDateTimeStartMonth_"+index);
    for (var i=0;i<startMonthlist.length;i++) {
    	startMonthWidget.append(startMonthlist[i]).find("option:last-child").attr("value",i);
        if (startDate.getMonth() == i) {
        	startMonthWidget.find("option:last-child").attr("selected","selected");
        }
    }
    var endMonthWidget = jQuery("#contentWidgetOptionsDateTimeEndMonth_"+index);
    for (var i=0;i<endMonthlist.length;i++) {
    	endMonthWidget.append(endMonthlist[i]).find("option:last-child").attr("value",i);
        if (endDate.getMonth() == i) {
        	endMonthWidget.find("option:last-child").attr("selected","selected");
        }
    }
    
    var updateDaylist = function (year,month,which,row,col) {
        var myEngine = {};
        if (which == "start") {
            myEngine = myStartEngine;
        } else {
            myEngine = myEndEngine;
        }
        
        var newDate = myEngine.getDate(year,month,row,col);
        if (newDate == null) {
            return;
        }
        updateField(which,newDate);
        
        var newdaylist = myEngine.getDayListing(year,month,[ newDate.getDate() ]);
        printDayList(which,newdaylist,partial(updateDaylist,year,month));
    };
    
    var printDayList  = function (which,daylist,onclickfunc) 
    {
    	var contentWidgetOptionsDateTime = jQuery("#contentWidgetOptionsDateTime"+which+"Day_"+index);
    	contentWidgetOptionsDateTime.children().remove();
        for (var row=0;row<daylist.length;row++) 
        {
        	contentWidgetOptionsDateTime.append("<tr />");
            for (var line=0;line<daylist[row].length;line++) 
            {
            	contentWidgetOptionsDateTime.find("tr:last-child").append(daylist[row][line]).find("td:last-child").click(partial(onclickfunc,which,row,line));
            }
        }
    };
        
    var startDaylist = myStartEngine.getDayListing(myStartEngine.getYearIndex(startDate.getFullYear()),startDate.getMonth(),[ startDate.getDate() ]);
    printDayList("start",startDaylist,partial(updateDaylist,myStartEngine.getYearIndex(startDate.getFullYear()),startDate.getMonth()));
    var endDaylist = myEndEngine.getDayListing(myEndEngine.getYearIndex(endDate.getFullYear()),endDate.getMonth(),[ endDate.getDate() ]);
    printDayList("end",endDaylist,partial(updateDaylist,myEndEngine.getYearIndex(endDate.getFullYear()),endDate.getMonth()));
    
    this.changeMonth = function (which) 
    {
        var myEngine = {}; var curYear; var curMonth; var newMonth;
        if (which == "start") 
        {
            myEngine = myStartEngine;
            curStartMonth = jQuery("#contentWidgetOptionsDateTimeStartMonth_"+index).val();
            curYear = curStartYear;
            curMonth = curStartMonth;
        }
        else 
        {
            myEngine = myEndEngine;
            curEndMonth = jQuery("#contentWidgetOptionsDateTimeEndMonth_"+index).val();
            curYear = curEndYear;
            curMonth = curEndMonth;
        }
        
        var daylist = myEngine.getDayListing(myEngine.getYearIndex(curYear),curMonth,[ ]);
        printDayList(which,daylist,partial(updateDaylist,myEngine.getYearIndex(curYear),curMonth));
    };
    
    this.changeYear = function (which) 
    {
        var myEngine = {}; var curYear; var curMonth; var newMonth;
        if (which == "start") 
        {     
            myEngine = myStartEngine;
            curStartYear = myEngine.getYear(jQuery("#contentWidgetOptionsDateTimeStartYear_"+index).val());       
            curYear = curStartYear;
            curMonth = curStartMonth;
        }
        else 
        {
            myEngine = myEndEngine;
            curEndYear = myEngine.getYear(jQuery("#contentWidgetOptionsDateTimeEndYear_"+index).val());
            curYear = curEndYear;
            curMonth = curEndMonth;
        }
        
        var daylist = myEngine.getDayListing(myEngine.getYearIndex(curYear),curMonth,[ ]);
        printDayList(which,daylist,partial(updateDaylist,myEngine.getYearIndex(curYear),curMonth));
    };
    
    
    this.init = function () 
    {
        if (initialized) 
        {
            return ;
        }
        updateField("start",startDate);
        updateField("end",endDate);
        initialized = true;
    };
};

/**
 * @return
 */
/**
 * @return
 */
var designJs = /**
 * @returns {designJs}
 */
function () 
{    
    this.analyseDatePickers = {};
    var currency = "EUR"; // read from outside?
    var decimalSeparator = ",";

    /**
     * onload-method that will only be called once when loading the page (not after an ajax request).
     * 
	 * @param newCurrency
	 * @param decimalSeparator
	 * 
	 */
    this.design_onload = function (newCurrency, newDecimalSeparator) 
    {

        if (typeof(newCurrency) == "string") 
        {
            currency = newCurrency;
        }
        
        decimalSeparator = newDecimalSeparator;
        
        this.initWidgetEditContent();
        
        // init maria_sellaround_widgets once
        maria_sellaround_widgets = [];

        // hide reseller search cart
        jQuery("#cartContent").hide();
        
        // controls first time ajax init of widget edit content if authenticated
        widgetEditContentLoaded = false;
    };
    
    this.initWidgetEditContent = function()
    {
    	// create sorting menu
    	this.initWidgetSortBy();

        // init widget footers
        this.reinitWidgetFooters();
        
        // Set up the scroll listener
        // TODO still necessary ?
        jQuery(window).scroll(checkWidgetPositions);
    };
    

    this.initWidgetSortBy = function()
    {
    	// create sorting menu
    	jQuery('.widgetsSortBy').each(function()
   		{
    		var thisRef = jQuery(this);
    		// disablef of not logged in
    		if (jQuery("#loggedInState").val() == 'false') 
        	{
    			thisRef.attr("disabled",'disabled');
            }
        	
    		// in first time load (widgetsSortByHidden class set) init selectmenu
    		if(thisRef.hasClass("widgetsSortByHidden"))
    		{
	    		thisRef.removeClass("widgetsSortByHidden")
	        		.selectmenu(
	        			{
	        				"width":"147px",
	        				"style":"dropdown",
	        				"onclick":"if (jQuery('#loggedInState').val()=='false') { myDesignJS.fadeIn('#messageOverlay_notLoggedIn');}"
	        			}
	        		)
	        		.bind('click',
	        			function()
	        			{
	        				return false;
	        			}
	        		);
    		}
   		});
    };

    /**
	 * Intitializes different things according to the panel rendered.
	 * Called after ajax rerender.
	 * @param containerId: only elements in this container will be initialized
	 * @param infoBoxes: init container's infoBoxes
	 * @param iphoneSwitches: init container's iphoneSwitches
	 */
    this.initOnLoad = function(containerId, infoBoxes, iphoneSwitches) 
    {
		if (infoBoxes)
		{			
			// init info boxes of the container
			initInfoBoxes("#"+containerId);
		}
		
		if (iphoneSwitches)
		{
			// init iphone switches of the container
			myDesignJS.initIphoneSwitch("#"+containerId);
		}
	};
	
	 /**
	 * Intitializes the widget edit view 
	 * Called after ajax rerender.
	 * @param containerId: only elements in this container will be initialized
	 * @param index of the widget in widget list
	 */
    this.initOnLoadWidgetEdit = function(containerId, index)
    {    	
    	myDesignJS.initOnLoad(containerId, true, true);

    	// called to init input components (visibility and their default values) depending on en/disabled states of iphone slider
    	myDesignJS.enDisableAmount(index);
    	myDesignJS.enDisableShipping(index);
    	myDesignJS.enDisableTaxrate(index);
    	myDesignJS.enDisableResellrate(index);
    	myDesignJS.enDisableMultipleOrder(index);
    };
    
    /**
	 * Intitializes the widget info view 
	 * Called after ajax rerender.
	 * @param containerId: only elements in this container will be initialized
	 * @param index of the widget in widget list
	 */
    this.initOnLoadWidgetInfo = function(containerId, index)
    {
    	myDesignJS.initOnLoad(containerId, true, true);    	
    };

    /**
	 * Intitializes the widget share view 
	 * Called after ajax rerender.
	 * @param containerId: only elements in this container will be initialized
	 */
    this.initOnLoadWidgetShare = function(containerId)
    {
    	myDesignJS.initOnLoad(containerId, true);
    	
		// prepare all input fields value to be selected on click
    	jQuery('#'+containerId).find('input[type=text]').click(
			function()
			{					
				this.select();
			}
		);		
    };
    
    /**
	 * Intitializes the widget analyze view 
	 * Called after ajax rerender.
	 * @param containerId: only elements in this container will be initialized
	 * @param index: of the widget in widget list
	 * @param startDate: widget start date for calendar
	 * @param monthfield: a list of localized monthfields
	 */
    this.initOnLoadWidgetAnalyse = function(containerId, index, startDate, monthfield)
    {
    	myDesignJS.initOnLoad(containerId, true);
    	
		// init datepicker
        var d = new Date();
        var ld = new Date();
        ld.setTime(startDate);
        
        myDesignJS.analyseDatePickers[index] = new sellaround_datepicker(index, ld, d, monthfield);
        myDesignJS.analyseDatePickers[index].init();
        
        var contentWidgetOptionsDateTime = jQuery('select.contentWidgetOptionsDateTime');
        if (contentWidgetOptionsDateTime.length != 0) 
        {
        	contentWidgetOptionsDateTime.selectmenu({"width":"141px","style":"dropdown"});
        }
	};
	
	/**
	 * Reopens all widget to their previous states (edit,share,analyse) after an ajax rerender.
	 */
	this.reInitWidgetsAfterReRender = function() 
	{
		// reopen all widgets if previously opened
		jQuery("input[id^='contentWidgetDetailsOpened_']").each(function(index)
		{
			var previouslyOpened = jQuery(this).val();
			if (previouslyOpened != '')
			{
				showWidgetDetails(index+1, previouslyOpened, true);
			}		
		});
		
		// reinit footers
		this.reinitWidgetFooters();
	};
	
	/**
	 * Re-initializes the widgets' footers
	 */
	this.reinitWidgetFooters = function() 
	{
		jQuery("span[id^='contentWidgetFooterAvailabilityInfo_']").each(function(index)
		{
			myDesignJS.initOnLoad("contentWidgetFooterAvailabilityInfo_" + (index+1), true);
	    });
	};
    
    /**
	 * Initializes the mouseover info boxes
	 */
    var initInfoBoxes = function(containerId) 
    {
    	jQuery(containerId).find('span.infoBox').each(
			function (id,elem) 
		    {    	    	
		    	var infoText = jQuery(this);
		    	
		    	// only initialize of not already done (we check for parent container)
		    	if(infoText.parent("span.infoBoxContainer").length == 0)
		    	{    	
			    	// move additional classes defined for infoBox to infoBoxContainer
			    	var addClassesFromInfoBox = infoText.attr("class").replace("infoBox", "");
			    	infoText.removeClass(addClassesFromInfoBox);
			    	    	
			    	infoText.wrap('<span class="infoBoxContainer ' + addClassesFromInfoBox + '"/>')
			    		.addClass("greyfont")
			    		.append('<img src="_images/overlay_info_head.png" class="infoHeader" alt="information" /><img src="_images/overlay_info_footer.png" class="infoFooter" alt="information" />')
			    		.after('<img class="infoButton" src="_images/btn_info.png" alt="information" />');
			
			        var infoButton = infoText.parent().find("img.infoButton");        
			        infoButton.mouseover(
			        	function() 
			        	{
			        		infoText.show();        		    	   
			    	    }
			    	);
			        infoText.mouseout(
			        	function() 
			        	{
			            	infoText.hide();
			    		}
			        );				        
		    	}
		    }
    	);
    };
    
    
    /**
	 * init the registraion checkboxes after ajax load 
	 */
    this.initRegistrationCheckboxes = function()
    {
    	jQuery('#registerContent input:checkbox.beautifulCheckbox').each(beautifyCheckBox);
    };
    
    
    /**
	 * init the region overlay after ajax load 
	 */
    this.initRegionOverlay = function () 
    {   	     	
        // The dialog overlay got clicked
        jQuery('#regionOverlay').click(
        	function(e)
        	{        	    
	            // Get the clicked element
	            var clickedElement = jQuery(e.target);
	
	            if (clickedElement.attr('id') == 'widgetConfirm')
	            {
	                var countryIsoStr = "";
	                var localizedCountryStr = "";
	                var numberOfItems = 0;
	                jQuery("input[id^=regionCheckbox_]:checked", jQuery(this)).each(
	                	function()
	                    {
	                    	var inputObj = jQuery(this);
	                    	if (!inputObj.is(':disabled'))
	                    	{
	                            if (numberOfItems > 0) 
	                            {
	                            	countryIsoStr = countryIsoStr + ",";
	                                localizedCountryStr = localizedCountryStr + ",";
	                            }
	                            countryIsoStr = countryIsoStr + inputObj.val();
	                            localizedCountryStr = localizedCountryStr + inputObj.next().attr("innerHTML");
	                            numberOfItems++;
	                    	}
	                    }
	                );

	                // "selectedRegionInputParent" is a global var
	                
          			// set iso codes in input field
	                var regionInputParent = jQuery('#'+selectedRegionInputParent);
	                var regionInput = regionInputParent.find('input:eq(0)');
	                regionInput.val(countryIsoStr);
	                
	                // sort country names alphabetically and copy localized country string to hidden span for javascript-preview
	                var localizedCountryArray = localizedCountryStr.split(",");
	                localizedCountryArray.sort();
	                localizedCountryStr = localizedCountryArray.join(",");
	                regionInputParent.find('input:eq(0) ~ span').text(localizedCountryStr);

	                // fire onchange event to update widget preview
	                regionInput.change();
	                
	                 // Close the dialog
	                myDesignJS.fadeOut(this);	        
	            }
	            
	            // Check whether the user clicked next to the dialog
	            if (clickedElement.attr('id') == 'regionOverlay' || clickedElement.attr('id') == 'widgetCancel')
	            {
	                // Close the dialog
	            	myDesignJS.fadeOut(this);
	            }
	        }
        );
        
        // A checkbox got clicked
        jQuery('#regionOverlay .bodyContent > ul > li > input:checkbox,#regionOverlay .bodyContent > ul > li > ul > li > input:checkbox').click(
        	function(e, i)
	        {
	            // Get the cliced checkbox
	            var checkBox = jQuery(this);
	        
	            // Cache the checked state
	            var checked = checkBox.attr('checked');
	
	            // Update all child checkboxes
	            if (!allowSingleSelectionOnly || !checked) 
	            {
	            	checkBox.parent().find('ul li input:checkbox').not(':disabled').attr('checked', (checked ? 'checked' : ''));
	            }
	        }
        );

        // A second level label got clicked
        jQuery('#regionOverlay .bodyContent > ul > li > ul > li > label').click(
        	function(e, i)
	        {
	            // Get the clicked element
	            var clickedElement = jQuery(this);
	            
	            // Get the open list item
	            var listItem = clickedElement.parent();
	            
	            // Check whether the list is open
	            if (listItem.hasClass('open'))
	            {
	                // Resize the sublist
	                listItem.find('div').animate(
	                    {
	                        'height': 0
	                    },
	                    function()
	                    {
	                        listItem.removeClass('open');
	                    }
	                );
	            }
	            // The list is closed
	            else
	            {
	                jQuery(".open label").click();
	                
	                // Get the list
	                var list = listItem.find('div ul');
	            
	                // Get the height
	                var newHeight = list.outerHeight(true);
	            
	                // Resize the sublist
	                listItem.find('div').animate(
	                    {
	                        'height': newHeight
	                    },
	                    function()
	                    {
	                        listItem.addClass('open');
	                    }
	                );	                
	            }
	        }
        );
    };    
    
    /**
     * store id and flag globally for later use and fades in the region widget (done before ajax load)
     * 
	 * @param fieldId settingsCountryPanel | registerCountryPanel
	 * @param singleSelectionOnly
	 */
    this.setupRegionOverlay = function (fieldId, singleSelectionOnly)
    {
    	selectedRegionInputParent = fieldId;
        allowSingleSelectionOnly = singleSelectionOnly;
        this.fadeIn('#regionOverlay');      
    };
    
    /**
     * setup region widget with already selected countries (setupRegionOverlay() must have been called before, done after ajax load)
     * 
	 * @param index widget index for detecting already selected countries
	 */
    this.setupRegionOverlayCheckboxes = function (index) 
    {    	    	    	
        // collect all selected isoCodes
        var allSelectedIsoCodes = new Array();
        if(typeof(index) != 'undefined')
        {
	        jQuery('td[id^=contentShippingOptionsRegion_'+index+']').each(
	        	function(c, tableRow) 
				{ 
					allSelectedIsoCodes = allSelectedIsoCodes.concat(jQuery(this).find('input:eq(0)').val().split(","));
				}
	        );
        }

        // reselect selected checkboxes for actual isoCodes (current inputfield)
        var isoCodes = jQuery('#'+selectedRegionInputParent+' input:eq(0)').val().split(",");
        // TODO (doesn't fit checkboxes being disabled right now, but we're already using styleClass 'beautifulCheckbox')
        //checkboxes.each(beautifyCheckBox);

        var checkboxes = jQuery('#regionOverlayContent input:checkbox.beautifulCheckbox');            
        checkboxes.each(
            function()
            {
            	var inputObj = jQuery(this);
                if (jQuery.inArray(inputObj.val(), isoCodes) > -1) 
                {
                    // select country
                	inputObj.attr('disabled', false);
                	inputObj.attr('checked', true);
                }
                else 
                {
                	if (jQuery.inArray(inputObj.val(), allSelectedIsoCodes) > -1)
                	{
                		inputObj.attr('checked', true);
                		inputObj.attr('disabled', true);
                	}
                	else
                	{
                		inputObj.attr('disabled', false);
                		inputObj.attr('checked', false);
                	}
                }
            }
       );
       
       this.uncheckContinents();
    };             
    
    this.changeContinentSelection = function (currentCheckboxId) 
    {
        if (allowSingleSelectionOnly) 
        {
        	jQuery('input[id^=regionCheckbox_]:checked').each(
                function()
                {
                	var inputObj = jQuery(this);
                	if (currentCheckboxId != inputObj.attr('id')) 
                	{
						inputObj.attr('checked', false);
                	}
                }
            );
        }
        
        this.uncheckContinents();
    };
    
    this.uncheckContinents = function () 
    {
        // disable worldwide checkboxe when in registration/settings (allowSingleSelectionOnly=true)
    	if(allowSingleSelectionOnly)
    	{
    		jQuery('#worldwide').attr('disabled', true);
    	}
    	
    	jQuery('input[id^=continentCheckbox_]').each(
            function()
            {
            	var inputObj = jQuery(this);
            	var checkboxList = inputObj.parent().find('ul li');
            	                
                // disable continent checkboxes when in registration/settings (allowSingleSelectionOnly=true)
            	// or all children are disabled (shippingRegion)
                if (allowSingleSelectionOnly || checkboxList.find('input:checkbox:disabled').length == checkboxList.size())
                {
                	inputObj.attr('disabled', true);
                }
                else
                {
                	inputObj.attr('disabled', false);
                }
                
                // select parent if at least one child is selected
                if (checkboxList.find('input:checkbox:checked').length == 0) 
                {
                	inputObj.attr('checked', false);
                }
                else 
                {
                	inputObj.attr('checked', true);
                }                
            }
        );
    };    
    
    /**
	 * init the category overlay after ajax load 
	 */
    this.initCategoryOverlay = function ()     
    {
  
        // The dialog overlay got clicked
        jQuery('#categoryOverlay').click(
        	function(e)
	        {
	            // Get the clicked element
	            var clickedElement = jQuery(e.target);
	            
	            if (clickedElement.attr('id') == 'catWidgetConfirm') 
	            {
	                var selectedSubCat = jQuery('#subCat_'+selectedMainCatTextRef).val();
	                var selectedMainCat =  jQuery('#mainCat').val();
	                
	                if (selectedMainCat == null || selectedSubCat == null) 
	                {
	                	return false;
	                }
	                
	                jQuery('#contentWidgetProductCat_'+copyCatToInputFieldForIndex).val(selectedMainCat+" -> "+selectedSubCat).change();
	                
	                
	                // Close the dialog
	                myDesignJS.fadeOut('#categoryOverlay');
	            }	
	            // Check whether the user clicked next to the dialog
				if (clickedElement.attr('id') == 'categoryOverlay' || clickedElement.attr('id') == 'catWidgetCancel')
	            {
	                // trigger onchange to show error message if no value selected
	            	jQuery('#contentWidgetProductCat_'+copyCatToInputFieldForIndex).change();
	            	
	                // Close the dialog
	            	myDesignJS.fadeOut('#categoryOverlay');
	            }
	        }
        );
 
        
        this.setupCategoryOverlaySelects();
    };
    
    this.copyCategoryOverlay = function ()     
    {

    	// store the original mainCat select-box (we later remove the options that are not valid for the selected product type)
    	categoryMainCatSelectOriginal = jQuery("#mainCat").clone();
  
    };
    
    /**
     * store index and flag globally for later use and fades in the category widget (done before ajax load)
     * 
	 * @param index: widget index
	 */    
    this.setupCategoryOverlay = function(index)
    {  
    	// store id for later use
        copyCatToInputFieldForIndex = index;
        
        // reselect selected values
        selectedCats = jQuery('#contentWidgetProductCat_'+index).val().split(" -> ");
        this.fadeIn('#categoryOverlay');
    };
    
    /**
     * setup category overlay with already selected categories (setupCategoryOverlay() must have been called before, done after ajax load)
	 */
    this.setupCategoryOverlaySelects = function () 
    {
    	// restore original mainCat select box
    	var mainCatParent = jQuery("#mainCat").parent();
    	jQuery("#mainCat").remove();
    	
    	// insert a clone of the temp mainCat (so changes won't affect the original)
    	mainCatParent.append(categoryMainCatSelectOriginal.clone());
    	
    	// remove non-available categories (based on product type: physical/voucher or digital)
        if (jQuery("#selectedProductType_" + copyCatToInputFieldForIndex).text() == 'DIGITAL')
        {
        	jQuery("#mainCat option:not(.digitalProductCategory)").remove();
        }
        else
        {
        	jQuery("#mainCat option.digitalProductCategory").remove();
        }
        
        var mainCat = jQuery('#mainCat');
        mainCat.val(selectedCats[0]);
        jQuery('select[id^=subCat_]').val(selectedCats[1]);
        
        // get the previously selected option element
        var optionToSelect = mainCat.find("option[value='" + selectedCats[0] + "']");
        var selectedMainCatTextRef = optionToSelect.attr("id");
        
        if (typeof(selectedMainCatTextRef) == "undefined") 
        {
            // if none preselected -> select first available option
        	optionToSelect = mainCat.find("option:first");
            selectedMainCatTextRef = optionToSelect.attr("id");
            optionToSelect.attr("selected", "selected");
            jQuery('select[id=subCat_' + selectedMainCatTextRef + '] option:first').attr('selected','selected');
        }

        // display the select list with the subcategories for the selected main category 
        this.showSubCats(optionToSelect.parent());        
    };    
    
    /**
     * toggles to cart for reseller widgets to add
     * 
     * @param isAddWidget true|false if delayed slideUp after a slideDown shall be performed on add widget
	 */  
    this.toggleResellerWidgetCart = function (isAddWidget)
    {
    	var cartContent = jQuery("#cartContent");
    	var arrowImage = jQuery("#cartArrow");
    	var arrowImageSrc = arrowImage.attr('src');

    	var isOpen;
    	if(arrowImageSrc.indexOf("_up") != -1)
    	{    	
    		isOpen = true;
    	}
    	else
    	{
    		isOpen = false;
    	}

    	// do close
    	if(isOpen && !isAddWidget)
    	{
    		cartContent.slideToggle('fast');
    		arrowImage.attr('src', arrowImageSrc.replace('_up', '_down'));
    	}
    	// do open
    	else if(!isOpen)
    	{       	
    		cartContent.slideToggle('fast');
    		arrowImage.attr('src', arrowImageSrc.replace('_down', '_up'));    		
    		if(isAddWidget)
        	{
        		window.setTimeout("myDesignJS.toggleResellerWidgetCart()", 1500);
        	}
    	}
    };
    
    
    var contentWidgetDetailsHeadlineButtonImages = {
        "edit": "_images/btn_main_edit.png",
        "share": "_images/btn_main_share.png",
        "analyse": "_images/btn_main_analyse.png",
        "info": "_images/btn_main_edit.png"
    };
    
    var contentWidgetDetailsHeadlineButtonIds = {
        "edit": "contentWidgetEditDetails",
        "share": "contentWidgetShareDetails",
        "analyse": "contentWidgetAnalyseDetails",
        "info": "contentWidgetInfoDetails"
    };
    
    var isClosed = function (index) 
    {
    	// determines if any tab is visible
        return jQuery("div.widgetDetailContent_"+index+":visible").size() == 0;
    };
    
    var isAlreadyOpen = function (index,mode) 
    {
    	var element = jQuery('#'+contentWidgetDetailsHeadlineButtonIds[mode]+'_'+index);
        if (element.size() > 0 && element.css('background-image') !== "none") 
        {
            return true;
        }
        return false;
    };
    
    var getMode = function (index) 
    {
        for (var i in contentWidgetDetailsHeadlineButtonIds) 
        {
            if (isAlreadyOpen(index,i)) 
            {
                return i;
            }
        }
        return "";
    };
    
    /**
     * Opens a widget tab.
     * 
     * @param index: widget index
	 * @param mode: the tab to open
	 *            edit|share|analyse|info
	 * @param noAnimation: use show() instead of slideDown()
	 *            true|false           
	 */
    var showWidgetDetails = function (index, mode, noAnimation) 
    {    
        var tabToOpen;        
        switch (mode) 
        {
            case "edit": tabToOpen = jQuery("#widgetEditContent_" + index); break;
            case "share": tabToOpen = jQuery("#widgetShareContent_" + index); break;
            case "analyse": tabToOpen = jQuery("#widgetAnalyseContent_" + index); break;
            case "info": tabToOpen = jQuery("#widgetInfoContent_" + index); break;
            default: return;
        }
        
        if (noAnimation)
        {
        	// we have to use 1 because of a bug in ie (otherwise ie goes to compatibility mode!)
			tabToOpen.show(1, 
				function()
				{
					myDesignJS.scrollToWidget(index);
				});
        }
        else
        {
	    	tabToOpen.slideDown('slow', function()
				{
	    			myDesignJS.scrollToWidget(index);
    			});
	    	
            //NS 22.10.10: 	SELAR-558 fix ie8 bug 
            if (isIE8() && navigator.userAgent.indexOf('Trident')!==-1 && mode == 'share')            
            {               
                tabToOpen.find('.share').slice(-2).each(
        			function()
        			{
        				jQuery(this).addClass('shareIe').css('overflow','hidden');
        			});
            }
        }
        
        // highlight function
        
        // change <li>
        var widgetDetailsListElement = jQuery('#'+contentWidgetDetailsHeadlineButtonIds[mode]+'_'+index); 
        widgetDetailsListElement.css('background-image', "url("+contentWidgetDetailsHeadlineButtonImages[mode]+")");
        // change <a>
        widgetDetailsListElement.find('a:first').addClass("greyfont").removeClass("bluefont");   
    };
    
    this.hideWidgetDetails = function (index, mode, keepOpenStatus) 
    {
    	if (mode == "") 
    	{
            if (isAlreadyOpen(index,"edit")) 
            {
                mode = "edit";
            } 
            else if (isAlreadyOpen(index,"share")) 
            {
                mode = "share";
            } 
            else if (isAlreadyOpen(index,"analyse")) 
            {
                mode = "analyse";
            } 
            else if (isAlreadyOpen(index,"info")) 
            {
                mode = "info";
            } 
            else 
            {
                return ;
            }            
        }
        
        if (mode == "edit")
        {
        	myDesignJS.setOrRemoveWidgetChanged(index, false);
            jQuery('#widgetEditContent_'+index).slideUp('slow');
        }
        else if (mode == "share")
        {
             jQuery('#widgetShareContent_'+index).slideUp('slow');
        }
        else if (mode == "analyse")
        {
             jQuery('#widgetAnalyseContent_'+index).slideUp('slow');
        }
        else if (mode == "info")
        {
             jQuery('#widgetInfoContent_'+index).slideUp('slow');
        }
        
        // reset open status
        if (!keepOpenStatus) 
        {
        	jQuery('#contentWidgetDetailsOpened_'+index).val('');
        }
      
        
        // remove highlighting
        
        // change <li>
        var widgetDetailsListElement = jQuery('#'+contentWidgetDetailsHeadlineButtonIds[mode]+'_'+index); 
        widgetDetailsListElement.css('background-image', "none");
        // change <a>
        widgetDetailsListElement.find('a:first').addClass("bluefont").removeClass("greyfont");   
    };
    
    this.showSubCats = function (selectElement) 
    {
    	selectedMainCatTextRef = jQuery(selectElement).find("option:selected").attr("id");
        jQuery('select[id^=subCat_]').addClass("hidden");
        jQuery('#subCat_'+selectedMainCatTextRef).removeClass("hidden");
        if (jQuery('select[id^=subCat_'+selectedMainCatTextRef+'] option').length == 1)
        {
            jQuery('select[id^=subCat_'+selectedMainCatTextRef+'] option:first').attr('selected','selected');
        }
    };

    /**
     * @param index: widget index
	 * @param mode: the tab to open
	 *            edit|share|analyse|info
	 * @param skipConfirm: skips the save/cancel-confirm overlay
	 *            true|false
	 */
    this.toggleWidgetDetails = function (index, mode, skipConfirm) 
    {
    	var tabIsClosed = isClosed(index);
        if (tabIsClosed)
        {
            showWidgetDetails(index, mode, false);
            // save opened tab for reopening on page reload
            jQuery("#contentWidgetDetailsOpened_"+index).val(mode);

            // required for reset widget position after hide widget details if widget is next to extended options
            checkWidgetPositions(false);           
        }
        else
        {
        	// previously opened tab
        	var previouslyOpened = jQuery("#contentWidgetDetailsOpened_"+index).val();

        	// determine if widget is changed
        	var isWidgetChanged = this.isWidgetChanged(index);
        	
        	// widget opened and coming from edit-page: cancel all changes
        	if (previouslyOpened == "edit" && isWidgetChanged && !skipConfirm)
        	{
        	 	// save the new tab globally before we open the confirmation overlay
            	widgetDetailsTabToOpenAfterConfirmation = mode;
        		
        		// open the save/discard confirmation overlay (calls toggleWidgetDetailsClosing when discarding changes)
        		myDesignJS.fadeIn("#closeWidgetOverlay_"+index);
        		return;
        	}
        	else 
        	{
        		// reset new tab globally
        		widgetDetailsTabToOpenAfterConfirmation = undefined;
        	}
        	
        	var doAfterClosing = '';
        	if (isWidgetChanged) 
        	{
        		// force resetting widget's values
        		doAfterClosing = 'cancel';
        	}
        	
        	this.toggleWidgetDetailsClosing(index,previouslyOpened,doAfterClosing,mode);
        }
    };
        
    /**
     * Closes the widget or opens another tab (called directly when discarding changes in closeWidgetOverlay).
	 * @param index: widget index
	 * @param previouslyOpened: previously opened tab
	 * @param doAfterClosing: triggers the save or cancel button to be pressed
	 *            save|cancel
	 * @param toOpen: tab to be opened (if undefined we consider the global 'widgetDetailsTabToOpenAfterConfirmation' var)
	 */
    this.toggleWidgetDetailsClosing = function (index, previouslyOpened, doAfterClosing, toOpen) 
    {    	
    	// widget is opened (another tab than the one being opened)
		if (doAfterClosing == 'save')
		{
			// save widget and suppress animation (otherwise the validation errors will appear in another tab)
			jQuery('#saveWidget_'+index).click();
			return false;
		}
		
		var tabToOpen;
		if(typeof(widgetDetailsTabToOpenAfterConfirmation) == "undefined")
		{
			tabToOpen = toOpen;
		}
		else
		{
			tabToOpen = widgetDetailsTabToOpenAfterConfirmation;
		}
		
    	if (tabToOpen != previouslyOpened)
    	{
    		// now set the new tab status (tab status for save action is not set until form validation passed)

    		// required for reopen widets after creating new widgets (reRender)
    		jQuery("#contentWidgetDetailsOpened_"+index).val(tabToOpen);
    		
            this.hideWidgetDetails(index, getMode(index), true);
            showWidgetDetails(index, tabToOpen);
        }
    	else
    	{
    		// close widget
            this.hideWidgetDetails(index, tabToOpen);
            jQuery("#contentWidgetDetailsOpened_"+index).val('');
    	}
    	
		if (doAfterClosing == 'cancel')
    	{
			// reset widget
			jQuery('#cancelWidget_'+index).click();
        }
    };
    
    this.enDisableAmount = function (index) 
    {    
    	var optionAmountHead = jQuery("span.optionAmountHead_"+index);    
    	if (jQuery("#contentWidgetOptionsLimited_"+index).is(":checked")) 
    	{
    		// add 1 as value for limitedNumber on enable
    		if (optionAmountHead.hasClass("hidden"))
        	{
        		jQuery("input.limitedNumber_"+index).each(
        			function()
            		{
        				jQuery(this).val('1');        				
            		}
                );
        	}

    		jQuery("#articleRepeat_"+index+" .contentWidgetOptionsTableCol3").removeClass("hidden");
            optionAmountHead.removeClass("hidden");                	
        } 
    	else 
    	{    		
    		// add 0 as value for limitedNumber on enable
    		jQuery("input.limitedNumber_"+index).each(
    			function()
        		{
    				jQuery(this).val('0');
        		}
            );
    		optionAmountHead.addClass("hidden");
            jQuery("#articleRepeat_"+index+" .contentWidgetOptionsTableCol3").addClass("hidden");        	
        }
    };
    
    this.updateAmountFromVoucherCodes = function (index, articleIndex)
    {    	
    	// proceed voucher code input fields
    	if(typeof(articleIndex) == 'undefined')
    	{
    		var voucherCodeFields = jQuery("[id$=\\:voucherCodes_" + index+ "]");
    		for(var i=0; i<voucherCodeFields.size(); i++)
    		{
    			updateLimitedNumberForVoucherCodes(jQuery(voucherCodeFields.get(i)));	
    		};    		
    	}
    	// proceed voucher code input field
    	else
    	{
        	//articlesDataList_1:0:voucherCodes_1
        	updateLimitedNumberForVoucherCodes(jQuery("#articlesDataList_" + index + "\\:" + articleIndex + "\\:voucherCodes_" + index)); 
    	}    
    };
    
    function updateLimitedNumberForVoucherCodes(voucherCodesField)
    {
    	var counter = 0;
    	var voucherCodesArr = voucherCodesField.val().split(/,(\s+)?|;(\s+)?|\s+/);
    	jQuery.each(voucherCodesArr, function(index, value)
			{
    			if(jQuery.trim(value) != '')
				{
    				counter++;
				}
			});    	
    	
       	//articlesDataList_1:0:limitedNumber_1
    	var limitedNumberId = voucherCodesField.attr('id').replace(/:/g, '\\:').replace('voucherCodes', 'limitedNumber');
    	jQuery("#"+limitedNumberId).val(counter).change();
    }
        
    this.setInitialOptionPrice = function (index)
    {    
    	var priceOfFirstOption = jQuery("#articleRepeat_" + index+ " > table.contentWidgetOptionsTable > tbody > tr.articleRow > td.contentWidgetOptionsTableCol2 > input").val();
    	jQuery("#articleRepeat_" + index+ " > table.contentWidgetOptionsTable > tbody > tr.articleRow:last > td.contentWidgetOptionsTableCol2 > input").val(priceOfFirstOption);    	
    };
    
    this.enDisableTaxrate = function (index, defaultTaxrate) 
    {
        if (jQuery("#contentWidgetOptionsTaxable_"+index).is(":checked")) 
        {
        	jQuery(".taxRate_"+index).removeClass("hidden");
        	var taxRateInput = jQuery("#contentWidgetOptionsTaxrate_"+index);
        	if(taxRateInput.val() == ("0" + decimalSeparator + "00"))
        	{
        		// add default taxRate if non set on existing widgets (for new widgets this is done on newWidget server side)
        		taxRateInput.val(defaultTaxrate);
        		taxRateInput.change();
        	}
        } 
        else 
        {
        	jQuery(".taxRate_"+index).addClass("hidden");
        }
    };

    this.enDisableResellrate = function (index) 
    {    
        if (jQuery("#contentWidgetOptionsResell_"+index).is(":checked")) 
        {         	
        	jQuery(".resellRate_"+index).removeClass("hidden");
        } 
        else 
        {        	
        	jQuery(".resellRate_"+index).addClass("hidden");        	
        }
    };

    this.enDisableMultipleOrder = function (index) 
    {
    	if (jQuery("#contentWidgetOptionsMultipleOrderCheck_"+index).is(":checked")) 
        {
        	jQuery(".multipleOrder_"+index).removeClass("hidden");
        } 
        else 
        {
        	jQuery("#contentWidgetOptionsMultipleOrder_"+index).val('1');
        	jQuery(".multipleOrder_"+index).addClass("hidden");
        }     	
    };

    this.enDisableShipping = function (index) 
    {   	
        if (jQuery("#contentWidgetOptionsShipping_"+index).is(":checked")) 
        {
            jQuery("#shippingRepeat_"+index).removeClass("hidden").slideDown(400, 
            	function()
            	{
		            jQuery("td[id^=contentShippingOptionsRegion_"+index+"_],td[id^=contentShippingOptionsPrice_"+index+"_],td[id^=contentShippingOptionsTime_"+index+"_]").each(
		            	function()
			            {
			              	jQuery(this).find("input").removeAttr("disabled");
			            }
			        );
            	}
            );
        } 
        else 
        {        
            jQuery("#shippingRepeat_"+index).slideUp(400,
            	function () 
	            {
	                jQuery(this).addClass("hidden");
	                jQuery("td[id^=contentShippingOptionsRegion_"+index+"_],td[id^=contentShippingOptionsPrice_"+index+"_],td[id^=contentShippingOptionsTime_"+index+"_]").each(
	                	function()
	                    {
	                     	jQuery(this).find("input").attr("disabled","true");
	                    }
	                );
	            }
            );
        }
    };
    
    this.updateIphoneButton = function (name, value)
    {
    	jQuery("#"+name).attr('checked', value);
    	jQuery("#"+name).change();
    };
    
    /**
	 * Sets dummy values for required fields, that are hidden in the frontend
	 */
    this.setDummyValuesForDisabledFields = function (index, defaultTaxRate) 
    {
    	// taxRate 
    	if (!jQuery("#contentWidgetOptionsTaxable_"+index).is(':checked')) 
    	{
    		var taxRate = jQuery("#contentWidgetOptionsTaxrate_"+index); 
    		taxRate.val(defaultTaxRate);
    		taxRate.change();
    	}
    	
    	// resellRate
        if (!jQuery("#contentWidgetOptionsResell_"+index).is(":checked")) 
        {         	
        	jQuery("#contentWidgetOptionsResellRate_"  + index).val(1);
        } 
       
    	var isDigitalProduct = jQuery("#selectedProductType_" + index).text() == "DIGITAL";
    	
    	// shipping regions
    	if (!jQuery("#contentWidgetOptionsShipping_"+index).is(':checked') || isDigitalProduct) 
    	{    		
	    	jQuery("#shippingRepeat_"+index+" table tbody tr").each(
	    		function()
	    		{
		            // countries
		    		var inputFields = jQuery(this).find("td input");
		            // set at least the deliveryTime
		    		inputFields.eq(2).val(1);
	    		}
	    	);
    	}
    	
    	// digital product: set dummy values for options and regions
    	if (isDigitalProduct)
    	{
    		// set multiple order to 1 instead of disabling it
    		jQuery("#contentWidgetOptionsMultipleOrder_" + index).val(1);
    		
    		// set options' prices (all but the first one)
    		// -> necessary because we might have switched between physical and digital product (and created multiple options before switching)
    		jQuery("#articleRepeat_"+index+" table tbody tr").each(
	    		function(eachIndex)
	    		{
		    		var inputFields = jQuery(this).find("td input");
		    		if (eachIndex > 0)
		    		{
		    			// don't replace the price of the first article
		    			inputFields.eq(1).val(1.00);
		    			
		    			// set option value with dummy
		    			inputFields.eq(3).val("!");
		    		}
		    		
		    		// set limited number to 1
		    		inputFields.eq(2).val(1);		    		
	    		}
	    	);
		}
    	
    };

    var closeOverlay = function (videoId) 
    {
    	var videoOverlay = jQuery("#videoOverlay_" + videoId);
    	videoOverlay.unbind("click",closeOverlay);
        jQuery(document).unbind("keyup",closeOnEsc);
        jQuery("#videoOverlayContainer_" + videoId, videoOverlay).hide();
        if(isIE8)
        {
        	videoOverlay.hide(0, 
        			function ()
    	        {
    	            videoOverlay.remove();
    	        });
        }
        else
        {
	        videoOverlay.fadeOut(500, 
	      		function ()
	       		{
	            	videoOverlay.remove();
	       		});
        }
    };
    
    var closeOnEsc = function (event, videoId) 
    {       
        if (event.keyCode == 27) 
        {
            closeOverlay(videoId);
        }
    };

    /**
    * opens a video overlay on the start page and binds the close events.
    * @param videoId 
    **/
    this.openVideoOverlay = function (videoId) 
    {
        var videoOverlay = jQuery('#videoOverlay_' + videoId);
    	var videoOverlayContainer = jQuery("#videoOverlayContainer_" + videoId, videoOverlay);    	  
    	videoOverlayContainer.hide();
    	
        if (isIE8()) 
        {
        	videoOverlay.show();
            videoOverlayContainer.show();
        } 
        else 
        {
        	videoOverlay.fadeIn(500, 
        		function () 
	        	{
	            	videoOverlayContainer.show();
	            }
        	);
        }
        
        jQuery("#closeOverlayButton_" + videoId, videoOverlayContainer).click(
    		function()
    		{
    			closeOverlay(videoId);
			}
		);
        jQuery(document).keyup(
    		function(event)
    		{
    			closeOnEsc(event, videoId);
			}
        );
    };
        
    /**
	 * updates the pictures in preview widget
	 * 
	 * @param pictureIndex (1-4)
	 * @param widgetIndex (1-n)
	 */
    this.updatePictureInPreviewOnAdd = function (pictureIndex, widgetIndex) 
    {
    	var widget = maria_sellaround_widgets[widgetIndex];    
    	var imgUrlThumb = jQuery("#productPicture" + pictureIndex + "_" + widgetIndex).attr("src");

    	var data = {};    	
	   	// set image url (on base if thumb url)
		data['pictureUrl'+pictureIndex] = imgUrlThumb.replace('_thumb', '');
    	// set (new) big image url on widget (on base if thumb url)
		data['bigPictureUrl'+pictureIndex] = imgUrlThumb.replace('_thumb', '_big');
    	
    	widget.updateMultiData(data);    	
    };
    
    
    /**
	 * updates all pictures in preview widget (in case of tmp widget changed to real one on widget save)
	 * 
	 * @param pictureIndex (1-4)
	 * @param widgetIndex (1-n)
	 */
    this.updatePictureInPreviewOnSave = function (widgetIndex) 
    {
    	var widget = maria_sellaround_widgets[widgetIndex];
    	var data = {};
    	
    	for(var pictureIndex=1; pictureIndex<=4; pictureIndex++)
    	{
    	   	var imgUrlThumb = jQuery("#productPicture" + pictureIndex + "_" + widgetIndex).attr("src");
    		if(typeof(imgUrlThumb) != "undefined")
    	   	{
        	   	// set image url (on base if thumb url)
    			data['pictureUrl'+pictureIndex] = imgUrlThumb.replace('_thumb', '');
	        	// set (new) big image url on widget (on base if thumb url)
    			data['bigPictureUrl'+pictureIndex] = imgUrlThumb.replace('_thumb', '_big');
    	   	}
    	}
    	
    	widget.updateMultiData(data);
    };
    
    /**
	 * updates the pictures in preview widget
	 * 
	 * @param pictureIndex (1-4)
	 * @param widgetIndex (1-n)
	 */
    this.updatePictureInPreviewOnRemove = function (pictureIndex, widgetIndex) 
    {            
    	var widget = maria_sellaround_widgets[widgetIndex];
	    
    	// image has been removed -> shift urls and set '' in widget where no image is anymore   
		var imgUrl2Thumb = jQuery("#productPicture2_" + widgetIndex).attr("src");		
		var imgUrl2;
		var imgUrl2Big;
		if(typeof(imgUrl2Thumb) != "undefined")
		{
			imgUrl2 = imgUrl2Thumb.replace('_thumb', '');
			imgUrl2Big = imgUrl2Thumb.replace('_thumb', '_big');
		}
		else
		{
			imgUrl2 = '';
			imgUrl2Big = '';
		}
		
		var imgUrl3Thumb = jQuery("#productPicture3_" + widgetIndex).attr("src");
		var imgUrl3;
		var imgUrl3Big;
		if(typeof(imgUrl3Thumb) != "undefined")
		{
			imgUrl3 = imgUrl3Thumb.replace('_thumb', '');
			imgUrl3Big = imgUrl3Thumb.replace('_thumb', '_big');
		}
		else
		{
			imgUrl3 = '';
			imgUrl3Big = '';
		}
		
		var imgUrl4Thumb = jQuery("#productPicture4_" + widgetIndex).attr("src");
		var imgUrl4;
		var imgUrl4Big;
		if(typeof(imgUrl4Thumb) != "undefined")
		{
			imgUrl4 = imgUrl4Thumb.replace('_thumb', '');
			imgUrl4Big = imgUrl4Thumb.replace('_thumb', '_big');
		}
		else
		{
			imgUrl4 = '';
			imgUrl4Big = '';
		}		
		
		var data = {};
		
		if(pictureIndex == 1)
    	{
			data['pictureUrl1'] = imgUrl2;
			data['bigPictureUrl1'] = imgUrl2Big;
			data['pictureUrl2'] = imgUrl3;
			data['bigPictureUrl2'] = imgUrl3Big;
			data['pictureUrl3'] = imgUrl4;
			data['bigPictureUrl3'] = imgUrl4Big;
			data['pictureUrl4'] = '';
			data['bigPictureUrl4'] = '';
    	}
		else if(pictureIndex == 2)
		{
			data['pictureUrl2'] = imgUrl3;
			data['bigPictureUrl2'] = imgUrl3Big;
			data['pictureUrl3'] = imgUrl4;
			data['bigPictureUrl3'] = imgUrl4Big;
			data['pictureUrl4'] = '';
			data['bigPictureUrl4'] = '';
		}
		else if(pictureIndex == 3)
		{
			data['pictureUrl3'] = imgUrl4;
			data['bigPictureUrl3'] = imgUrl4Big;
			data['pictureUrl4'] = '';
			data['bigPictureUrl4'] = '';
		}
		else if(pictureIndex == 4)
		{
			data['pictureUrl4'] = '';
			data['bigPictureUrl4'] = '';
		}    	
		
		widget.updateMultiData(data);
    };    
    
     
    /**
     * we cannot init the iphone buttons on document load because the parent divs might be hidden then
     * -> we do it on demand by calling this function    
     * 
	 * @param containerId (optional) for limiting the iphone-checkboxes to be formatted
	 * @param caller (optional) control hidden-behavior of parent container dependent on caller 
	 */
    this.initIphoneSwitch = function(containerId, caller)
    {       	
   	
        // setup iphone checkboxes
    	var checkbox;
    	if(typeof(containerId) == 'undefined')
    	{
    		// all iphone-checkboxes on current page
    		checkbox = jQuery('input:checkbox.iphoneSwitch');
    	}
    	else
    	{
    		var container = jQuery(containerId);
    		// prevent init on
     		// -> initial case (container not visible until startAnimation, iphone switch will be formatted after startAnimation)
    		// -> ignore calls from the settings page -> the container is not hidden there but only when using the selector container.css('display') != 'hidden'? 
    		if(caller != 'callFromSettings' && container.is(':hidden'))
    		{
    			return;
    		}
    	
    		// limit to iphone-checkboxes in container
    		checkbox = container.find('input:checkbox.iphoneSwitch');
    	}
    	
    	checkbox.each(function()
		{    		
    		var parent = jQuery(this).parent();
    		
    		// chrome/safari SELAR-612:
    		// force parent to be visible on settings page after 'edit'-button was pressed 
    		// (only required in chrome/safari - why? parent has already been set to visible by css class change in toggleSettingsButton!)
    		if(!parent.is(':visible') && caller == 'callFromSettings')
    		{
    			parent.css('display', 'block');    			
    		}
    	
        	// only add plugin if not done already (and only if the checkbox is visible - otherwise is is not formatted correctly)
    		if(parent.is(":visible") && !parent.hasClass('iPhoneCheckContainer'))
    		{        		
    			//console.log(">>>> container: "+containerId+", caller: "+caller+", parent: "+parent+", parentId: "+parent.attr('id'));
    			jQuery(this).iphoneStyle();
    		}
		});
    };    
    
    /**
     * default fade out 
     */
    this.fadeOut = function(selector)
    {
        if(isIE8())
        {
        	jQuery(selector).hide();	
        }
        else
        {
        	jQuery(selector).fadeOut(250);
        }      	
    	
    };
    
    /**
     * default fade in 
     */
    this.fadeIn = function(selector)
    {
        if(isIE8())
        {
        	jQuery(selector).show();	
        }
        else
        {
        	jQuery(selector).fadeIn(250);
        }    	
    };
        

    this.createArticleRtoAsJson = function (index, currencyCode) 
    {    
        var rto = "[";

        // select visible rows only (digital product selection renders article rows invisible)
        var articleRows = jQuery("#articleRepeat_"+index+" table tbody tr.articleRow:visible");
        var articleSize=articleRows.size();
        
        if (articleSize==0) return;
        
        // article row is defined as:
        // first-col | customIdNumber (0) | price (1) | amount (2) | option (3) | delete
        
        articleRows.each(
        	function( idx )
	        {
	        	var inputFields = jQuery(this).find("td input");
	        	
	            rto += "{'articleId':0,";
	            
	            // options
	            rto += "'articleOptionRtoList':[";
	            var optionName="";
	            if (articleSize > 1) 
	            {
	                optionName=inputFields.eq(3).val().replace(",", "");
	            }
	            rto += "{'optionValue':'" + optionName + "'}],";
	            
	            // customIdNumber
	            rto += "'customIdNumber':'" + inputFields.eq(0).val() + "',";

	            // price
	            var price = inputFields.eq(1).val();
	            
	            // convert price to integer (cent)
	            price = price.replace(decimalSeparator, "");

	            // remove all zeros at the beginning
	            while(price.substring(0,1) == "0" && price.length > 1)
	            {
	            	price = price.substring(1);
	            }
	            
	            rto += "'price':" + price + ",";
	            
	            // currency
	            rto += "'currencyCode':'" + currencyCode + "',";
	
	            
	            var maxAmountPerOrder = '';
	            if (jQuery("#contentWidgetOptionsMultipleOrderCheck_"+index).is(':checked')) 
	            {
	            	maxAmountPerOrder = jQuery('#contentWidgetOptionsMultipleOrder_'+index).val();	
	            }
	            else 
	            {
	            	maxAmountPerOrder = 1;
	            }

	            if (maxAmountPerOrder <= 0 || maxAmountPerOrder == '') 
	            {
	            	maxAmountPerOrder = 1;
	            }

	            var limitedNumberOf = inputFields.eq(2).val();
	            var availabilityStr;

	            if (isNaN(new Number(limitedNumberOf)) || isNaN(new Number(maxAmountPerOrder)))
	            {
	            	// Dummy data
	            	availabilityStr = "'limitedNumberOf':1,'availability':1";
	            }
	            else
	            {	                
	            	var contentWidgetOptionsLimited = jQuery("#contentWidgetOptionsLimited_"+index);
	            	
	            	// If widget options is false or not present in dom tree we have to convert 1 (because of the validator) to -1 (unlimited) for the widget.
	            	// For server side we convert in EditWidgetBean.saveInternalWidget().
		            if (limitedNumberOf == 0 && contentWidgetOptionsLimited.size() > 0 && !contentWidgetOptionsLimited.is(':checked')) 
		            {
		            	limitedNumberOf = -1;
		            }

		            availabilityStr = myDesignJS.calculateAvailability(limitedNumberOf, maxAmountPerOrder, jQuery("#contentWidgetOptionsMultipleOrderCheck_"+index).is(':checked'));
	            }
	            
	            rto += availabilityStr;
	            
	            rto += "}";
	            
	            if (articleSize != idx+1) 
	            {
	                rto += ",";
	            }
	        }
        );     
        
        rto=rto+"]";

        //console.log(rto);

        return eval(rto);
    };
    
    // copied and translated from SalesServiceImpl.calculateAndSetAvailability()
    this.calculateAvailability = function (limitedNumberOf, maxAmountPerOrder, multipleOrder)
    {    	
    	limitedNumberOf = new Number(limitedNumberOf);    	
    	maxAmountPerOrder = new Number(maxAmountPerOrder);
    	var availability = 0;
    	
    	  // check for unlimited number of articles
        if (limitedNumberOf < 0)
        {
            // with limit of max amount per order - limit limitedNumbersOf to max amount per order
            if (multipleOrder)
            {
            	limitedNumberOf = maxAmountPerOrder;
            }
            // without limit of max amount per order - unlimited limitedNumbersOf
            else
            {
            	limitedNumberOf = -1;
            }

            // availability is unlimited anyway
            availability = -1;
        }
        // check for limited number of articles
        else
        {   
            // availablity is always equal to limitedNumbersOf (maxAmountPerOrder is not considered) 
            availability = limitedNumberOf;

            // limit of max amount per order and limitedNumbersOf is greater then max amount per order
            if (multipleOrder && limitedNumberOf > maxAmountPerOrder)
            {
                // -> limit limitedNumbersOf to max amount per order
            	limitedNumberOf = maxAmountPerOrder;
            }
        }
        
        return "'limitedNumberOf':" + limitedNumberOf + ",'availability':" + availability;
    };
    
    
    /**
     * checks if we have at least one article with availability 
     */
    this.checkOutOfStock = function(index)
    {    
    	// limited avail. is siwtched off
    	if(!jQuery("#contentWidgetOptionsLimited_"+ index).is(":checked"))
    	{
    		return false;
    	}
    	
    	// check availability of all options
        var limitedNumberFields = jQuery("input[id$=limitedNumber_" + index + "]");
        for(var i=0; i<limitedNumberFields.size(); i++)
        {
        	if(jQuery(limitedNumberFields.get(i)).val() != 0)
        	{
        		return false;
        	}
        }
        return true;         
    };
    
    this.updateTaxRateOnWidget = function(index, taxRate) 
    {    	
    	if (taxRate.indexOf(decimalSeparator) == -1)
        {
    		taxRate = taxRate + decimalSeparator + "00";
        }
        else if (taxRate.indexOf(decimalSeparator) == taxRate.length-2)
        {
        	taxRate = taxRate + "0";
        }
    	
    	// we need a float -> convert "," to "."
    	if(taxRate.indexOf(",") != -1)
    	{
    		taxRate = taxRate.replace(",", ".");
    	}
    	
    	maria_sellaround_widgets[index].updateSingleData('taxRate', taxRate);
    };

    // used for the resellPercentage update
    this.updateResellRateOnWidget = function(index, resellPercentage) 
    {        
    	// do not update dummy widget on invalid value
    	if(resellPercentage == '-' || resellPercentage < 1 || resellPercentage > 99)
    	{
    		return;
    	}
    	
        maria_sellaround_widgets[index].updateSingleData('resellCommission', resellPercentage);
        
        //this is not used right now..
        /*
    	// we have to calculate with integers to prevent rounding errors
    	// 1.5 => 150
    	resellPercentage = resellPercentage * 100;
    	// cent (10 => 1000)
    	var price = jQuery("input[id$='contentWidgetOptionPrice_"+index+"']").eq(0).val() * 100;
    	
    	var commissionStr = "" + (price * resellPercentage);
    	
    	// we have to remove the last 4 characters (numbers) to correct the multiplications with 100
    	commissionStr = commissionStr.substring(0, commissionStr.length-4);
    	
    	if(commissionStr.length == 0)
    	{
    		commissionStr = "0.00";
    	}
    	else if(commissionStr.length == 1)
    	{
    		commissionStr = "0.0" + commissionStr;
    	}
    	else if(commissionStr.length == 2)
    	{
    		commissionStr = "0." + commissionStr;
    	}
    	else if(commissionStr.length == 3)
    	{
    		commissionStr = commissionStr.substring(0,1) + "." + commissionStr.substring(1);
    	}    	
    	else
    	{
    		commissionStr = commissionStr.substring(0,2)+ "." + commissionStr.substring(2);	
    	}
    	
    	jQuery("#contentWidgetOptionsResellPrice_"+index).val(commissionStr);
        */
    };
  
    
    this.createShippingRtoAsJson = function (index, currencyCode) 
    {            	
        var regionRows = jQuery("#shippingRepeat_"+index+" table tbody tr");
        var shippingSize=regionRows.size();        
        if (shippingSize==0) 
        {
        	return;
        }
                
        var rto = "[";
        
        regionRows.each(
        	function( idx )
	        {     	        	
	            rto = rto + "{'shippingId':0,";
	            
	            // regions
	            rto = rto + "'shippingRegionRtoList':[";
	            
	            // split string from hidden span for this row with country names
	            var regionNames =  jQuery(this).find('span[id$=localizedShippingCountries_' + index + "]");
	            
	            // concatenate localized counry strings of all hidden spans with "," as delimiter (calling regionNames.text() concatenates without separator)
	            var regionNamesStr = "";
	            for(var i=0; i<regionNames.size(); i++)
	            {	            	
	            	regionNamesStr += jQuery(regionNames.get(i)).text();
	                if (regionNames.size() > i+1) 
	                {
	                	regionNamesStr += ",";
	                }
	            }
	            // escape "'" of localized country names
	            regionNamesStr = regionNamesStr.replace("'", "\\'");
	            
	            var regionNamesArray = regionNamesStr.split(",");
	            for (var i=0; i<regionNamesArray.length; ++i)
	            {
	                rto = rto + "{'region':'" + regionNamesArray[i] + "'}";
	                if (regionNamesArray.length > i+1) 
	                {
	                    rto += ",";
	                }
	            }
	            
	            rto= rto + "],";
	            
	            var inputFields = jQuery(this).find("td input");
	        	
	            // shippingCosts
	            var shippingCosts = inputFields.eq(1).val();	            
	            
	            // convert price to integer (cent)
	            shippingCosts = shippingCosts.replace(decimalSeparator, "");

	            // remove all zeros at the beginning
	            while(shippingCosts.substring(0,1) == "0" && shippingCosts.length > 1)
	            {
	            	shippingCosts = shippingCosts.substring(1);
	            }
	            
	            var freeShippingLimit = inputFields.eq(3).val();
	            var freeShippingLimitEnabled;
	            if(freeShippingLimit != "")
	            {
	            	freeShippingLimitEnabled = true;
	            	freeShippingLimit = freeShippingLimit.replace(decimalSeparator, "");
	            }
	            else
	            {
	            	freeShippingLimitEnabled = false;
	            }
	            
	            rto = rto + "'shippingCosts':" + shippingCosts + ",";
	            rto = rto + "'deliveryTime':'" + inputFields.eq(2).val() + "',";
	            rto = rto + "'currencyCode':'" + currencyCode + "',";
	            if(freeShippingLimitEnabled)
	            {
	            	rto = rto + "'freeShippingLimitEnabled':true,";
		            rto = rto + "'freeShippingLimit':" + freeShippingLimit;	
	            }
	            else
	            {
	            	rto = rto + "'freeShippingLimitEnabled':false";
	            }
	            rto = rto + "}";
	            
	            if (shippingSize != idx+1) 
	            {
	                rto += ",";
	            }
	        }
        );     
        
        rto = rto + "]";
        
        return eval(rto);
    };
    
    this.validateInputField = function (field, inputval) 
    {
    	field = jQuery(field);
    	var anyValidationFailed = false;    	 
    	var fieldValue = jQuery.trim(field.val());
    	
    	for ( var i = 0; i < inputval.length; i++) 
    	{    		
			var val = inputval[i];

			// after first validation failed break loop
			if(anyValidationFailed)
			{
				break;
			}
			
			switch (val.validator) 
			{
	    		case "required":
	    			
	    			if (fieldValue == '') 
	    			{
	    				anyValidationFailed = true;
	    				if (val.message!=null) 
	    				{
	    					field.val(val.message);
	    				}
	    			}
	    			break;
	    			
				case "number":

					// we always need "." instead of "," for isNaN
					fieldValue = fieldValue.replace(decimalSeparator, ".");
					if (fieldValue == '')
					{
						break; // ignore empty fields for validation (must be controlled with 'required')
					}						
					else if (isNaN(fieldValue)) 
	    			{
	    				anyValidationFailed = true;
	    				if (val.message!=null) 
	    				{
	    					field.val(val.message);
	    				}
	    			}
	    			break;
	    			
				case "integer":
					
					if (fieldValue == '')
					{
						break;
					}					
					else if (parseInt(fieldValue)!=fieldValue-0) 
	    			{
	    				anyValidationFailed = true;
	    				if (val.message!=null) 
	    				{
	    					field.val(val.message);
	    				}
	    			}
	    			break;
	    			
				case "maxlength":
					
					if (fieldValue == '')
					{
						break;
					}	
					else if (fieldValue.length > val.value) 
	    			{
	    				anyValidationFailed = true;
	    				if (val.message!=null) 
	    				{
	    					field.val(val.message);
	    				}
	    			}
	    			break;
	    			
				case "maxvalue":
				
					// we always need "." instead of "," for numeric validation
					fieldValue = fieldValue.replace(decimalSeparator, ".");	    			
					if (fieldValue == '')
					{
						break;
					}	
					else if (fieldValue > val.value) 
	    			{
	    				anyValidationFailed = true;
	    				if (val.message!=null) 
	    				{
	    					field.val(val.message);
	    				}
	    			}
	    			break;
	    			
				case "minvalue":

					// we always need "." instead of "," for numeric validation
					fieldValue = fieldValue.replace(decimalSeparator, ".");
					if (fieldValue == '')
					{
						break;
					}	
	    			if (fieldValue < val.value) 
	    			{
	    				anyValidationFailed = true;
	    				if (val.message!=null) 
	    				{
	    					field.val(val.message);
	    				}
	    			}
	    			break;
	    	}
		}
		
		if (anyValidationFailed) 
		{
			field.addClass("error");
			
			// we use 'mousedown' because 'click' is used by <scomp:defaultValueForInputText>
			field.bind('mousedown', function()
				{
					field.removeClass("error");
				});
			
			return false;
		}
		else
		{
			field.unbind('mousedown');
			return true;
		}
	};
	
	
	 /**
     * encapsulates all comma functions needed for price-typed fields
     * 
     * @param field
     * @param numbersBeforeComma
     * @param numbersAfterComma
     * @param ignoreEmtpyField
     */
	this.handleComma = function (field, numbersBeforeComma, numbersAfterComma, ignoreEmtpyField)
	{
		// check on empty field -> set 0
		field = jQuery(field);
		if(jQuery.trim(field.val()) == '')
		{
			if(ignoreEmtpyField)
			{
				return;
			}
			field.val(0);
		}
		
		this.correctComma(field);
		this.addZeroAfterComma(field);
		this.convertComma(field, numbersBeforeComma, numbersAfterComma);
	};
	
    /**
     * corrects wrong comma character in price compared to the given decimalSeparator
     * 
     * @param field field obj
     */
	this.correctComma = function (field)
	{		
    	field = jQuery(field);
    	var price = field.val();
    	
    	var shouldNotBeInPrice;
    	if(decimalSeparator == ".")
    	{
    		shouldNotBeInPrice = ",";
    	}
    	else
    	{
    		shouldNotBeInPrice = ".";
    	}
    	
    	price = price.replace(shouldNotBeInPrice, decimalSeparator);  
    	
    	field.val(price);
	};
    
    /**
     * fills up a field's value to a total count of 2 numbers after comma
     * 
     * @param field field obj
     */
    this.addZeroAfterComma = function (field) 
    {
    	field = jQuery(field);
    	var price = field.val();
  	
    	// 10
        if (price.indexOf(decimalSeparator) == -1)
        {
        	price = price + decimalSeparator + "00";
        }
        // 10.
        else if(price.length == 3 && price.indexOf(decimalSeparator) == 2)
        {
        	price = price + "00";
        }
        // 1.
        else if(price.length == 2 && price.indexOf(decimalSeparator) == 1)
        {
        	price = price + "00";
        }
        // 10.0
        else if (price.indexOf(decimalSeparator) == price.length-2)
        {
        	price = price + "0";
        }
    	
        field.val(price);
    };
    
    /**
     * removes any comma if exits in input field
     * 
     * @param field obj
     */    
    this.removeComma = function (field)
    {
    	field = jQuery(field);
    	var fieldValue = field.val();
    	field.val(fieldValue.replace(decimalSeparator, ""));    	
    };
    
    /**
     * converts a field value on a maximum count of allowed numbers before and after the comma
     * 
     * @param field field obj
     * @param numbersBeforeComma count of numbers allowed before comma
     * @param numbersAfterComma count of numbers allowed after comma
     */
    this.convertComma = function (field, numbersBeforeComma, numbersAfterComma)
    {
    	field = jQuery(field);
    	var price = field.val();
    	
    	// only allow maxNumbers before comma
    	if(price.length > numbersBeforeComma && price.indexOf(decimalSeparator) == -1)
    	{    	
	    	price = price.substring(0,numbersBeforeComma) + decimalSeparator + price.substring(numbersBeforeComma);    		
    	}
    	
    	// only allow numbersAfterComma after comma
    	var indexOfComma = price.indexOf(decimalSeparator);
    	if(indexOfComma != -1)
    	{
    		if(price.substring(indexOfComma).length > numbersAfterComma)
    		{
    			price = price.substring(0, indexOfComma + numbersAfterComma + 1);
    		}
    	}
    	
    	field.val(price);    	
    };
   
    /**
     * escapes all html elements from text
     */
    this.escapeHTML = function (text){
    	return jQuery("<span>").text(text).html();
    };
    
	this.showHideEditor = function (elem) 
	{		
		var checkbox = jQuery(elem);
		// traverse to parent of checkbox first (iphone slider wrapps checkbox with div)
		// -> and catch first div with class editor
		var editor = checkbox.parent().next("div.editor");
        if (checkbox.is(':checked')) 
        {  
        	editor.slideDown(400);
        } 
        else 
        {        	
        	editor.slideUp(400);
        }
    };
    
    this.nextInputOnEnter = function (parentId,currentElement,event) 
    {
    	// switches input focus to next element on enter
    	if (event.keyCode == 13) 
    	{
    		// all input fields except checkboxes (iphone) and buttons
	    	var formFields = jQuery("#"+parentId).find(':input:visible:enabled:not(:checkbox):not(:button)');
	    	
	    	var index = formFields.index(currentElement);
	    	if (index>-1 && (index+1) < formFields.length)
	    	{
	    		var nextElement = formFields.eq(index+1);
	    		nextElement.focus();
	    	};
	    	return false;
    	}
	};
    
    this.setOrRemoveWidgetChanged = function (index,newValue) 
    {
    	jQuery("#contentWidgetChanged_"+index).val(newValue);
    };
    
    this.isWidgetChanged = function (index) 
    {
    	return jQuery("#contentWidgetChanged_"+index).val() == "true";
    };
        
    /**
     * scrolls to a widget's header
     * 
     * @param index
     */ 
    this.scrollToWidget = function(index)
    {
        //jQuery(window).scrollTop(jQuery('#widgetEditView_' + index).offset().top);
        jQuery('html,body').animate({ scrollTop: jQuery('#widgetEditView_' + index).offset().top }, 300);
         
    };
        
    /**
     * scrolls to the page footer
     * 
     */ 
    this.scrollToFooter = function()
    {
    	jQuery(window).scrollTop(jQuery('#footer').offset().top);
    };
    
     /**
     * scrolls to registration panel  
     */ 
    this.scrollToRegister = function()
    {
    	jQuery(window).scrollTop(jQuery('#registrationHeadline').offset().top);		
    };
    
    /**
     * scrolls to registration panel  
     */ 
    this.scrollToRegisterError = function()
    {
    	jQuery(window).scrollTop(jQuery('#registerFormContent .error').offset().top);		
    };
    
    /**
     * scrolls to settings panel  
     */ 
    this.scrollToSettings = function()
    {
    	jQuery(window).scrollTop(jQuery('#settingsDataContent').offset().top);		
    };
    
    /**
     * scrolls to settings error  
     */ 
    this.scrollToSettingsError = function()
    {
    	jQuery(window).scrollTop(jQuery('#settingsDataContent .error').offset().top);		
    };
    
    /**
     * creates the imprint based on a template with the entered user data on registration form
     * 
     * @param textareaId id of imprint text area to fill
     * @param userData all user field values
     */
    this.createImprint = function(textareaId, userData)
    {
    	
    	var imprintTxt = addValueToImprint(userData.AddressComponent_company, "");
    	imprintTxt = addValueToImprint(userData.MasterData_name1 + " " + userData.MasterData_name2, imprintTxt);
    	imprintTxt = addValueToImprint(userData.AddressComponent_street, imprintTxt);    	
    	imprintTxt = addValueToImprint(userData.AddressComponent_zipCode + " " + userData.AddressComponent_town, imprintTxt);
    	imprintTxt = addValueToImprint(userData.AddressComponent_country, imprintTxt)  + "\n";
    	
    	imprintTxt = addValueToImprint(userData.SolseitAuthComponent_userLogin, imprintTxt);
    	imprintTxt = addValueToImprint(userData.MasterData_url, imprintTxt);
    	imprintTxt = addValueToImprint(userData.MasterData_phone, imprintTxt);
    	
    	jQuery("#"+textareaId).val(imprintTxt);
    };
    
    /**
     * adds a label and it's value to the imprint text, if the value is not empty.
     */
    function addValueToImprint(value, imprintTxt)
    {
    	if(value.length > 0)
    	{
    		imprintTxt = imprintTxt + value + "\n";    		
    	}
    	return imprintTxt;
    };
        
    this.updateAllRegions = function (inputId, index) 
    {
    	var inputComp = jQuery("#"+inputId);
    	inputComp.val("");
    	var shippingRegionInputs = jQuery("input[id$=shippingRegion_"+index+"]");
    	inputSize = shippingRegionInputs.size();
    	shippingRegionInputs.each(
    		function (i,selected) 
	    	{
	    		if (inputSize > i+1) 
	    		{
	    			newVal = inputComp.val() + jQuery(this).val() + ",";
	    		}
	    		else 
	    		{
	    			newVal = inputComp.val() + jQuery(this).val();
	    		}
	    		inputComp.val(newVal);
	        }
    	);
    };
    
    /**
     * Copies all article prices into a hidden field (comma-separated), so they can be accessed in custom validator PriceDiscountValidator.
     * 
     * @param inputId
     * @param index
	 */
    this.updateAllArticlePrices = function (inputId, index) 
    {
    	var inputComp = jQuery("#"+inputId);
    	inputComp.val("");
    	var priceInputs = jQuery("input[id$=contentWidgetOptionPrice_"+index+"]");
    	inputSize = priceInputs.size();
    	priceInputs.each(
    		function (i,selected) 
	    	{
    			// we need the price as float values (for PriceDiscountValidator)
    			newVal = inputComp.val() + jQuery(this).val().replace(",",".");
	    		if (inputSize > i+1) 
	    		{
	    			newVal += ",";
	    		}

	    		inputComp.val(newVal);
	        }
    	);
    };
    
	
    /**
     * toggles to edit button and formular view for settings side.
     * 
	 * @param settingsContainerId 
	 * @param inactiveText language dependent text for button on inactive edit
	 * @param activeText language dependent text for button on active edit
	 */  
    this.toggleSettingsButton = function (settingsContainerId, inactiveText, activeText) 
    {
		var settingsContainer = jQuery('#'+settingsContainerId);
		var settingsDiv = settingsContainer.find("div:first");
		var editButton = settingsContainer.find(":first.settingsEditButton");		
		var saveButton = settingsContainer.find(".settingsEditButton.save");
		
		// edit is inactive -> switch to active
		if(settingsDiv.hasClass('mode1'))
    	{
			settingsDiv.removeClass('mode1').addClass('mode2');
		   
	        editButton.text(activeText);
	        editButton.addClass('cancel');
	        saveButton.css('display', 'inline-block');
		}
		// edit is active -> switch to inactive
		else
    	{	
			settingsDiv.removeClass('mode2').addClass('mode1');
    		
    		editButton.text(inactiveText);
    		editButton.removeClass('cancel');
    		saveButton.hide();
		}
    };
	
    /**
     * toggles all to edit button and formular view for settings side.
	 */  
    this.toggleSettingsButtonAll = function(editAccountData, editSellerInformation, editImprint, editPrivacy, editRevocation, editGtc, editTax, editOrderConfirm, inactiveText, activeText)
    {
    	 if(editAccountData)
         {
             myDesignJS.toggleSettingsButton('accountDataContainer', inactiveText, activeText);
         }
         if(editSellerInformation)
         {
             myDesignJS.toggleSettingsButton('sellerInformationContainer', inactiveText, activeText);
         }
         if(editImprint)
         {
             myDesignJS.toggleSettingsButton('imprintContainer', inactiveText, activeText);
         }
         if(editPrivacy)
         {
             myDesignJS.toggleSettingsButton('privacyContainer', inactiveText, activeText);
         }
         if(editRevocation)
         {
             myDesignJS.toggleSettingsButton('revocationContainer', inactiveText, activeText);
         }
         if(editGtc)
         {
             myDesignJS.toggleSettingsButton('gtcContainer', inactiveText, activeText);
         }
         if(editTax)
         {
             myDesignJS.toggleSettingsButton('taxContainer', inactiveText, activeText);
         }
         if(editOrderConfirm)
         {
             myDesignJS.toggleSettingsButton('orderConfirmContainer', inactiveText, activeText);
         };
    };
    
	
	/**
	 * Changes the main view selection in navigation  
	 * 
	 * @param toView myWidgetsContent | myResellWidgetsContent | settingsContent | salesAndCostsContent | widgetSearchContent (nothing means reset all links to inactive)
	 */
	this.changeMainViewSelection = function(toView)
	{
		var inactiveLinksSelector = '#myWidgetsMainLink,#settingsLink,#salesAndCostsLink,#widgetSearchLink';
		
		if(typeof(toView) == 'undefined') // reset all active links
		{
			jQuery(inactiveLinksSelector).removeClass('alreadyActive');
		}
		else if(toView != 'registerContent')
		{			
			// set links in navMenu
			var activeLinkSelector = '#' + toView.replace("Content", "Link");
	
				
			// we remove the selected link selector to be active from inactiveLinksSelector-string
			inactiveLinksSelector = inactiveLinksSelector.replace(activeLinkSelector, "");
			
			if(inactiveLinksSelector.charAt(0) == ",")
			{
				inactiveLinksSelector = inactiveLinksSelector.substring(1);	
			}
			else if(inactiveLinksSelector.charAt(inactiveLinksSelector.length-1) == ",")
			{
				inactiveLinksSelector = inactiveLinksSelector.substring(0, inactiveLinksSelector.length-1);
			}

			// activate selected link
			var activeLink = jQuery(activeLinkSelector);
	    	if(!activeLink.hasClass('alreadyActive'))
	    	{
	    		activeLink.addClass('alreadyActive');
	    		// deactivate the other links
				jQuery(inactiveLinksSelector).removeClass('alreadyActive');
	    	}	    	
	    	
			// special: on call of 'myWidgetsContent' or 'myResellWidgetsContent' 
			// -> we also have to activate 'myWidgetMainLink'
			if(activeLinkSelector == '#myWidgetsLink' || activeLinkSelector == '#myResellWidgetsLink')
			{				
				var activeMyWidgetsMainLink = jQuery('#myWidgetsMainLink');
				if(!activeMyWidgetsMainLink.hasClass('alreadyActive'))
		    	{
					activeMyWidgetsMainLink.addClass('alreadyActive');
		    		// deactivate the other links
					inactiveLinksSelector = inactiveLinksSelector.replace('#myWidgetsMainLink', '');
					jQuery(inactiveLinksSelector).removeClass('alreadyActive');
		    	}				
			}
		}
	};
	
	/**
	 * Changes the main view container  
	 * 
	 * @param toView registerContent | myWidgetsContent | settingsContent | salesAndCostsContent | widgetSearchContent
	 */
	this.changeMainView = function(toView)
	{		
		// show main view
		var toShowSelector = '#' + toView;
		var toHideSelector = '#registerContent,#myWidgetsContent,#settingsContent,#salesAndCostsContent,#widgetSearchContent';
		toHideSelector = toHideSelector.replace(toShowSelector, "");
		if(toHideSelector.charAt(0) == ",")
		{
			toHideSelector = toHideSelector.substring(1);	
		}
		else if(toHideSelector.charAt(toHideSelector.length-1) == ",")
		{
			toHideSelector = toHideSelector.substring(0, toHideSelector.length-1);
		}
		
		// hide mainViews and remove openend flag
		jQuery(toHideSelector).hide().removeClass('opened');
		// show toView and add opened flag (we also need to remove "height:0" of close animation was performed an a main view)
		jQuery(toShowSelector).removeClass('hidden').removeClass('closed').addClass('opened').css('height','').show();
	};
	
	
	/**
	 * Opens the confirm mail preview overlay in the registration/settings screen.
	 * Placeholders are replaced by their actual values or by example values.
	 * 
	 * @param String currencySymbol
	 * @param String digitalProductLinkText
	 * @param String sellaroundMailFooter
	 * @param isRegistration 
	 * @param userData all user data fields
	 * @param String language
	 */
	this.openOrderConfirmPreview = function(currencySymbol, sellaroundMailFooter, isRegistration, userData, language)
	{
		var confirmText;
		
		if(isRegistration)
		{
			confirmText = jQuery("#registrationOrderConfirmText").val();
		}
		else
		{
			confirmText = jQuery("#SellaroundUserComponent_orderConfirmText").val();
		}
		
		// digital product download link
		confirmText = confirmText.replace(/\{digitalProductDownloadLink\}/g, "https://sellaround.s3.amazonaws.com/...");
		
		// voucher product codes
		confirmText = confirmText.replace(/\{voucherCodes\}/g, "VOUCHER-12345678");
		
		// replace placeholders by example values
		var now = new Date();
		confirmText = confirmText.replace(/\{sellDate\}/g, now.getDay() + "/" + now.getMonth() + "/" + now.getFullYear());		
		confirmText = confirmText.replace(/\{productName\}/g, language == "de" ? "Mein Produkt" : "My Product" );
		confirmText = confirmText.replace(/\{amount\}/g, "1");
		confirmText = confirmText.replace(/\{articleOption\}/g, language == "de" ? "Größe M" : "Size M");
		confirmText = confirmText.replace(/\{grossPrice\}/g, language == "de" ? "5,00 ".concat(currencySymbol) : "5.00 ".concat(currencySymbol));
		confirmText = confirmText.replace(/\{taxRate\}/g, language == "de" ? "19,00" : "19.00");
		confirmText = confirmText.replace(/\{tax\}/g, language == "de" ? "0,80 ".concat(currencySymbol) : "0.80 ".concat(currencySymbol));
		confirmText = confirmText.replace(/\{discount\}/g, "{}");
		confirmText = confirmText.replace(/\{shipping\}/g,  language == "de" ? "2,50 ".concat(currencySymbol) : "2.50 ".concat(currencySymbol));
		confirmText = confirmText.replace(/\{totalGross\}/g, language == "de" ? "6,50 ".concat(currencySymbol) : "6.50 ".concat(currencySymbol));
		
		// shipping
		confirmText = confirmText.replace(/\{shippingTime\}/g, "2");
		
		// buyer address
		confirmText = confirmText.replace(/\{buyerName\}/g, language == "de" ? "Max Mustermann" : "Max Patternman");
		confirmText = confirmText.replace(/\{buyerCompany\}/g, "{}");
		confirmText = confirmText.replace(/\{buyerStreet\}/g, language == "de" ? "Musterstrasse 42" : "42nd Pattern St");
		confirmText = confirmText.replace(/\{buyerAdditional\}/g, "{}");
		confirmText = confirmText.replace(/\{buyerZip\}/g, "12345");
		confirmText = confirmText.replace(/\{buyerCity\}/g, language == "de" ? "Musterstadt" : "Patterncity");
		confirmText = confirmText.replace(/\{buyerCountry\}/g, language == "de" ? "Deutschland" : "United States");
		
		// seller information
		confirmText = confirmText.replace(/\{sellerName\}/g, userData.MasterData_name1 + " " + userData.MasterData_name2);
		confirmText = confirmText.replace(/\{sellerCompany\}/g, userData.AddressComponent_company);
		confirmText = confirmText.replace(/\{sellerEmail\}/g, userData.SolseitAuthComponent_userLogin);		
		confirmText = confirmText.replace(/\{sellerCountry\}/g, userData.AddressComponent_country);
		
		// phone
		if (userData.MasterData_phone.length > 0)
		{
			confirmText = confirmText.replace(/\{sellerPhone\}/g, userData.MasterData_phone);
		}
		else
		{
			confirmText = confirmText.replace(/\{sellerPhone\}/g, "{}");
		}
		
		// web
		if (userData.MasterData_url.length > 0)
		{
			confirmText = confirmText.replace(/\{sellerWeb\}/g, userData.MasterData_url);
		}
		else
		{
			confirmText = confirmText.replace(/\{sellerWeb\}/g, "{}");
		}
		
		// revocation text	
		if (userData.SellaroundUserComponent_revocationText != null && userData.SellaroundUserComponent_revocationText.length > 0)
		{
			confirmText = confirmText.replace(/\{revocationText\}/g, userData.SellaroundUserComponent_revocationText);
		}
		else
		{
			confirmText = confirmText.replace(/\n.*?:\n\{revocationText\}\n/g, "");
		}
		
		// privacy text		
		if (userData.SellaroundUserComponent_privacyText)
		{
			confirmText = confirmText.replace(/\{privacyLink\}/g, "http://seller.sellaround.net/SellerName#privacy");
		}
		else
		{
			confirmText = confirmText.replace(/\n.*?:\n\{privacyLink\}\n/g, "");
		}

		// terms
		if (userData.SellaroundUserComponent_gtcText)
		{
			confirmText = confirmText.replace(/\{termsLink\}/g, "http://seller.sellaround.net/SellerName#terms");
		}
		else
		{
			confirmText = confirmText.replace(/\n.*?:\n\{termsLink\}\n/g, "");
		}

		// replace lines with empty {} -> .*?\{\}.*?\n
		confirmText = confirmText.replace(/.*?\{\}.*?\n/g, "");
		
		confirmText = confirmText.replace(/\{sellaroundMailFooter\}/g, sellaroundMailFooter.replace(/\n/g,"<br/>"));
		
		jQuery("#orderConfirmPreviewText").html(confirmText.replace(/\n/g,"<br/>"));
		
		myDesignJS.showInfoOverlay("orderConfirmPreviewOverlay");		
	};
	
	/**
	 * Initializes the infobox for reselles.
	 */
	this.initHowToResellWidgetResellerInfoOverlay = function()
	{
		jQuery("#resellerInfoPopupBox").show();
		
		// bind click events
		jQuery("#resellerInfoPopupBox div,#resellerInfoPopupBox img").unbind("click").click(
			function(event)
			{
				if (jQuery(this).get(0).tagName != "IMG")
				{
					myDesignJS.showInfoOverlay("howToResellWidgetResellerInfoOverlay");
				}
				jQuery("#resellerInfoPopupBox").hide();
							
				event.stopPropagation();
			}
		);
	};
	
	this.showInfoOverlay = function(overlayId)
	{
		myDesignJS.fadeIn("#" + overlayId);
		myDesignJS.fadeIn("#" + overlayId+ " .infoOverlayBackground");
	};
	
	this.hideInfoOverlay = function(overlayId)
	{
		myDesignJS.fadeOut("#" + overlayId);
		myDesignJS.fadeOut("#" + overlayId+ " .infoOverlayBackground");
	};
	
	
	/**
	 * @param resellOnly true if only resell widgets should be shown in product catalog
	 */
	this.loadProductCatalog = function(resellerSearch)
	{
		var sortField;
		if(resellerSearch)
		{
			sortField = "commission";
		}
		else
		{
			sortField = "creationDate";	
		}
		
		ajaxLoadWidgetSearchResultContent(sortField, resellerSearch, resellerSearch);
	
        myDesignJS.changeMainViewSelection('widgetSearchLink');
        if(startPageAnimationCurtainIsOpen())
        {
            myDesignJS.changeMainView('widgetSearchContent');   
        }
        else
        {
            startPageAnimation(true, jQuery('#widgetSearchContent'));
        };
        
        if(resellerSearch)
    	{
        	myDesignJS.initHowToResellWidgetResellerInfoOverlay();	 
    	}
        else
        {
        	jQuery("#resellerInfoPopupBox").hide();
        }
	};
	
};

var myDesignJS = new designJs();


/************************/
/** startPageAnimation **/
/************************/

var startPageAnimationCurtainIsOpen = function()
{
	return jQuery('#startAnimationContentContainer').find('.opened').length > 0;
};


var animationDoneOnce = false;
var startPageAnimationActive = false;

/**
 *   
 * @param openOrClose true = open, false = close
 * @param elementToOpen 
 * @param skipAnimation 
 * @param callbackFct function to perform after animation
 */
var startPageAnimation = function (openOrClose, elementToOpen, skipAnimation, callbackFct)
{			
    if (startPageAnimationActive)
    {
        return;
    }

    // Update the indicator
    startPageAnimationActive = true;

    // Get all required elements    
    var startPageAnimationTop = jQuery('#startPageAnimationTop');
    var startPageAnimationFooter = jQuery('#startPageAnimationFooter');
    var startAnimationContentContainer = jQuery('#startAnimationContentContainer');
    var footerBackground = jQuery("#startPageAnimationFooterContainer");

    animationDoneOnce = true;

    // set animation speed
    var speedStartPageAnimationTop;
	var speedBackground;
	var speedElementToOpen;
    var speedFadeOut;
    if (skipAnimation)
    {        	
    	// don't animate when reloading the page (e.g. after saving widget)
    	speedStartPageAnimationTop = 0;
    	speedBackground = 0;
    	speedElementToOpen = 0;
        speedFadeOut = 0;
    }
    else
    {
    	speedStartPageAnimationTop = 750;
    	speedBackground = 1000;
    	speedElementToOpen = 300;        	
        speedFadeOut = 200;
    }
    
    // Check whether we have to open the curtain
    if (openOrClose)
    {   
    	// clean up footer-carpet divs
        var footerCarpetHeight = jQuery(document).height() - 512;
        footerBackground.css("top", '627px')
        	.css("height",footerCarpetHeight + 42);
        jQuery("#startPageAnimationFooterBackground_body").addClass("hidden");
        footerBackground.css("z-index",'110');
        
        elementToOpen.removeClass('hidden');

        if (isIE8())
        {
            // Hide the real widget and the card wheel
            jQuery('#startPageAnimationCardWheel,#startPageAnimationWidget').css('display', 'none');
        
            // Show the header text
            jQuery('#headText').css('display', 'block');   
        }
        else
        {
            // Hide the real widget and the card wheel
            jQuery('#startPageAnimationCardWheel,#startPageAnimationWidget').animate({ opacity: 0 }, speedFadeOut, 
            		function ()
            		{
            			// Show the header text
                		jQuery('#headText').fadeIn(250);
            		}
            );
        }

        // Resize the header
        startPageAnimationTop.animate(
            {
                height: 110
            },
            speedStartPageAnimationTop // Speed in milliseconds
        );
       
        // hide the footer-carpet
        elementToOpen.animate(
            {
               height:footerCarpetHeight*2
            },
            speedElementToOpen, // Speed in milliseconds
            function ()
            {
                // Flag the element as opened
                elementToOpen.addClass('opened');
                elementToOpen.removeClass('closed');
                elementToOpen.css('height','auto'); 
            }
        );
                
        footerBackground.animate ( 
            {
                'top':footerCarpetHeight*3
            },
            speedBackground,
            function ()
            {
                footerBackground.css('display', 'none');
                // Update the indicator
                startPageAnimationActive = false;
                if(typeof(callbackFct) != 'undefined')
                {
                	callbackFct();
                }
            }
        );

        jQuery(".blackoverlay").animate(
            {
                opacity:0
            },
            speedBackground,
            function ()
            {
                jQuery(".blackoverlay").remove();  
            }
        );	        
        
        // Show the footer (is set to hidden initially - otherwise that footer is shortly visible on page load in fast browsers)
        startAnimationContentContainer.find(".footer").show();               
    }
    // We have to close the curtain
    else
    {    	    	
        if (isIE8())
        {
            // Get the opened div
            footerBackground.css('display', 'block').animate(
        	{
                top: 627
        	}, 700
            );

        }
        else
        {
        	// Get the opened div
	        footerBackground.css('opacity', 0).css('display', 'block').animate(
        	{
                opacity: 1,
                top: 627
            },700
	        );

        }

        // Resize the header
        startPageAnimationTop.animate(
            {
                height: 587
            },
            500 // Speed in miliseconds
        );

        
        // Show the footer
        if(isIE8())
        {
        	// no opacity used here (otherwise fonts in footer become busted)
            startPageAnimationFooter
                .css('display', 'block')
                .animate(
                    500 // Speed in milliseconds                    
                );
        }
        else
        {
            startPageAnimationFooter
            .css(
                {
                    opacity: 0,
                    display: 'block'
                }
            )
            .animate(
                {
                    opacity: 1
                },
                500 // Speed in milliseconds                    
            );
        }

        // Hide the content
        var openedDiv = startAnimationContentContainer.find('.opened');	        	
        openedDiv
            .css('overflow', 'hidden')
            .animate(
                {
                    height: 0                  
                },
            500, // Speed in milliseconds
            function ()
            {
                if (isIE8())
                {
                    // Show the real widget and the card wheel
                    jQuery('#startPageAnimationCardWheel,#startPageAnimationWidget').css('display', 'block');

                    // Hide the header text
                    jQuery('#headText').css('display', 'none');
                }
                else
                {

                    // Show the real widget and the card wheel
                    jQuery('#startPageAnimationCardWheel,#startPageAnimationWidget').animate(
                    	{ 
                    		opacity: 1 
                    	}, speedFadeOut
                    );

                    // Hide the header text
                    jQuery('#headText').fadeOut(250);

                }

                // Remove the opened flag
                openedDiv.removeClass('opened');
                
                jQuery(document.body).addClass("bodyBack");
                
                // Update the indicator
                startPageAnimationActive = false;

        		// perform a callback if givens
                if(typeof(callbackFct) != 'undefined')
                {	                    	
                	callbackFct();
                }
            }
        );

	    // Hide the footer
	    startAnimationContentContainer.find(".footer").hide();	    	    
    }
};


/************************/
/** cardWheelAnimation **/
/************************/

var startPageCartWheelAnimationActive = false;
var startPageAnimationCardIndex = 0;
var startPageAnimationCardWheel = null;
var startPageAnimationDotList = null;
var startPageAnimationDotListItems = null;
var startPageAnimationTexts = null;
var startPageAnimationTimer = null;
var startPageAnimationTimerTimout = 4000;

var nextStartPageAnimationCard = function ()
{
    // Get the next card index
    var nextCardIndex = startPageAnimationCardIndex + 1;

    // Check the bounds
    if (nextCardIndex > 5)
    {
        nextCardIndex = 0;
    }

    // Show the next card
    changeStartPageAnimationCardIndex(nextCardIndex);
};

var resetStartPageAnimationCardTimer = function ()
{
    if (startPageAnimationTimer !== null)
    {
        clearInterval(startPageAnimationTimer);
    }

    startPageAnimationTimer = setInterval(nextStartPageAnimationCard, startPageAnimationTimerTimout);
};

var changeStartPageAnimationCardIndex = function (newCardIndex)
{
    // Reset up the timer
    resetStartPageAnimationCardTimer();

    // Check whether we have to do something
    if (newCardIndex != startPageAnimationCardIndex && !startPageCartWheelAnimationActive)
    {
        // Update the indicator
    	startPageCartWheelAnimationActive = true; 	
    	
        // Get the current card
        var currentCard = startPageAnimationCardWheel.find('li.selected');
        var currentCardImage = currentCard.find('img');

        // Get the next card
        var nextCard = startPageAnimationCardWheel.find('li').eq(newCardIndex);
        var nextCardImage = nextCard.find('img');

        // Prepare the next card to get faded in
        nextCard.addClass('fadingIn');

        if (isIE8())
        {
            nextCardImage.css({
                marginTop: 60,
                marginLeft: 200,
                height: 303,
                width: 200
            });
        }
        else
        {
            nextCardImage.css({
                marginTop: 60,
                marginLeft: 200,
                opacity: 1,
                height: 303,
                width: 200
            });
        }

        if (isIE8())
        {
            // Hide the current card
            currentCardImage.animate({
                marginTop: 40,
                marginLeft: 80,
                height: 343,
                width: 200
            }, 500);
        }

        else
        {
            // Hide the current card
            currentCardImage.animate({
                marginTop: 40,
                marginLeft: 80,
                opacity: .2,
                height: 343,
                width: 200
            }, 500);
        }



        // Show the next card
        nextCardImage.animate(
        (isIE8()
        ?
            {
                marginTop: 0,
                marginLeft: 0,
                height: 423,
                width: 344
            }
        :
            {
                marginTop: 0,
                marginLeft: 0,
                opacity: 1,
                height: 423,
                width: 344
            }
        )



        , 500, function ()
        {
            // Hide the current card
            currentCard.removeClass('selected');

            // Finaly show the next card
            nextCard.removeClass('fadingIn').addClass('selected');

            // Update the card index
            startPageAnimationCardIndex = newCardIndex;

            // Update the indicator
            startPageCartWheelAnimationActive = false;
        });

        // Get the current text
        var currentText = startPageAnimationTexts.find('li.selected');

        // Get the next text
        var nextText = startPageAnimationTexts.find('li').eq(newCardIndex);



        if (isIE8())
        {
            // Prepare the next text to get faded in
            nextText.css('display', 'block');

            // Hide the current text
            currentText.css('display', 'none');

            // Update the classes
            currentText.removeClass('selected');
            nextText.addClass('selected');

        }
        else
        {

            // Prepare the next text to get faded in
            nextText.css({
                opacity: 0,
                display: 'block'
            });

            // Hide the current text
            currentText.animate({
                opacity: 0
            }, 250, function ()
            {
                // Finaly hide the current text
                currentText.css('display', 'none');

                // Show the next text
                nextText.animate({
                    opacity: 1
                }, 250, function ()
                {
                    // Update the classes
                    currentText.removeClass('selected');
                    nextText.addClass('selected');
                });
            });
        }

        // Remove the white dot
        startPageAnimationDotList.find('.selected').removeClass('selected');

        // Set a new white dot
        startPageAnimationDotListItems.eq(newCardIndex).addClass('selected');
    }
};

/****************/
/** datePicker **/
/****************/

/**
 * @param elemYear
 *            the html to wrap around exactly one year in a possible
 *            year-listing, its an array: 0 -> before the value, 1 -> after the
 *            value
 * @param elemMonth
 *            the html to wrap around exactly one month in a possible
 *            month-listing, its an array: 0 -> before the value, 1 -> after the
 *            value
 * @param elemDay
 *            the html to wrap around exactly one day in a possible day-listing,
 *            its an array: 0 -> before the value, 1 -> after the value
 * @param elemHighlightedDay
 *            the html to wrap around a highlighted day in a possible
 *            day-listing, its an array: 0 -> before the value, 1 -> after the
 *            value
 * @param elemEmptyDay
 *            the html to use for empty days
 * @param firstDayOfWeek
 *            the day of week on which the day-listing rows start (0-6, 0 is
 *            sunday)
 * @param monthfield
 *            an array containing string for month values. should start with
 *            January at index 0
 */
var datepicker_engine = function (elemYear,elemMonth,elemDay,elemHighlightedDay,elemEmptyDay,firstDayOfWeek,monthfield) 
{
	
	var years = [];
	var days = [];
	
	/*
	 * return a listing with all the years
	 */
	this.getYearListing = function (startYear,EndYear) 
	{
	    var elems = [];
	    years = [];
	    for (var i=startYear;i<=EndYear;i++) 
	    {
	        years[years.length] = i;
	        elems[elems.length] = elemYear[0]+i+elemYear[1];
	    }
	    return elems;
	};
	
	/*
	 * return a listing with all months
	 */
	this.getMonthListing = function () 
	{
	    var elems = [];
	    for (var i=0;i<12;i++) 
	    {
	        elems[elems.length] = elemMonth[0]+monthfield[i]+elemMonth[1];
	    }
	    return elems;
	};
	
	
	var returnDayElem = function (day, highlightedDays) 
	{
	    var isHighlighted = false;
	    for (var i=0;i<highlightedDays.length;i++) 
	    {
	        if (highlightedDays[i] == day) 
	        {
	            isHighlighted = true;
	        }
	    }
	    if (isHighlighted) 
	    {
	        return elemHighlightedDay[0]+day+elemHighlightedDay[1];
	    }
	    return elemDay[0]+day+elemDay[1];
	};
	
	/*
	 * return a listing with all days for a month of a specific year @param year
	 * the index of the array returned by getYearListing @param month the index
	 * of the array returned by getMonthListing @param highlightedDays an array
	 * containing all days (1-31) that should be highlighted
	 */
	this.getDayListing = function (year, month, highlightedDays) 
	{
	    var elems = [];
	    days = [];
	    var dayDate = 1;
	    var d = new Date(years[year],month,dayDate);
	    var dow = d.getDay();
	    
	    var positionOfFirstDay = (7-firstDayOfWeek*1.0+dow*1.0)%7;
	    
	    // fill empty days
	    for (var i=0;i<positionOfFirstDay;i++) 
	    {
	        if (typeof(elems[0]) == "undefined" || typeof(days[0]) == "undefined") 
	        {
	            elems[0] = [];
	            days[0] = [];
	        }
	        elems[0][i] = elemEmptyDay;
	        days[0][i] = 0;
	    }
	    // complete the first row
	    for (var i=positionOfFirstDay;i<7;i++) 
	    {
	        if (typeof(elems[0]) == "undefined" || typeof(days[0]) == "undefined") 
	        {
	            elems[0] = [];
	            days[0] = [];
	        }
	        elems[0][i] = returnDayElem(dayDate,highlightedDays);
	        days[0][i] = dayDate;
	        dayDate++;
	    }
	    // generate the middle of the month, which is always there
	    for (var rowIndex=1;rowIndex<10;rowIndex++) 
	    {
	        if (typeof(elems[rowIndex]) == "undefined" || typeof(days[rowIndex]) == "undefined") 
	        {
	            elems[rowIndex] = [];
	            days[rowIndex] = [];
	        }
	        for (var j=0;j<7;j++) 
	        {
	            elems[rowIndex][j] = returnDayElem(dayDate,highlightedDays);
	            days[rowIndex][j] = dayDate;
	            dayDate++;
	            if (dayDate == 29) 
	            {
	                break;
	            }
	        }
	        if (dayDate == 29) 
	        {
	            break;
	        }
	    }
	    // check the next 3 days for their existence before writing them in the
		// array
	    for (dayDate; dayDate<32; dayDate++) 
	    {
	        var tmpDate = new Date(years[year],month,dayDate);
	        if (tmpDate.getDate() == dayDate && tmpDate.getMonth() == month && tmpDate.getFullYear() == years[year]) 
	        {
	            // alrite this day exists.. write it
	            var rowIndex = days.length-1;
	            if (days[rowIndex].length >= 7) 
	            {
	                rowIndex++;
	                elems[rowIndex] = [];
	                days[rowIndex] = [];
	            }
	            var lineIndex = days[rowIndex].length;
	            days[rowIndex][lineIndex] = dayDate;
	            elems[rowIndex][lineIndex] = returnDayElem(dayDate,highlightedDays);
	        }
	    }	    
	    // fill the rest of the last line with emptyElems
	    var rowIndex = days.length-1;
	    for (var i=days[rowIndex].length;i<7;i++) 
	    {
	        elems[rowIndex][i] = elemEmptyDay;
	        days[rowIndex][i] = 0;
	    }
	    
	    return elems;
	};
	
	/*
	 * return the date-Object for a specific day @param year the index of the
	 * array returned by getYearListing @param month the index of the array
	 * returned by getMonthListing @param dayRow the first-dimension index of
	 * the array returned by getDayListing @param dayCol the second-dimension
	 * index of the array returned by getDayListing
	 */
	this.getDate = function (year,month,dayRow,dayCol) 
	{
	    if (days[dayRow][dayCol] == 0)
	    {
	        return null;
	    }
	    var d = new Date(years[year],month,days[dayRow][dayCol]);
	    if (d.getDate() == days[dayRow][dayCol] && d.getMonth() == month && d.getFullYear() == years[year]) 
	    {
	        return d;
	    }
	    return null;
	};
	
	/*
	 * get a year-index for a real year
	 */
	this.getYearIndex = function (year) 
	{
	    for (var i=0;i<years.length;i++) 
	    {
	        if (years[i] == year) 
	        {
	            return i;
	        }
	    }
	    return -1;
	};
	
	/*
	 * get a month-index for a real month
	 */
	this.getMonthIndex = function (month) 
	{
	    return month;
	};
	
	/*
	 * get a day-index for a real day
	 */
	this.getDayIndex = function (day) 
	{
	    for (var i=0;i<days.length;i++) 
	    {
	        for (var j=0;j<days[i].length;j++) 
	        {
	            if (days[i][j] == day) 
	            {
	                return {"row":i,"col":j};
	            }
	        }
	    }
	    return {};
	};
	
	/*
	 * get a year for index
	 */
	this.getYear = function (yearIndex) 
	{
	    return years[yearIndex];
	};
	
	/*
	 * get a month for an index
	 */
	this.getMonth = function (month) 
	{
	    return month;
	};
	
	/*
	 * get a day for an index
	 */
	this.getDay = function (row,col) 
	{
	    return days[row][col];
	};

};

/******************/
/** footerDialog **/
/******************/

var enableFooterDialogTab = function(tabIndex, animated)
{
    // Check whether no animation is required
    if (!animated)
    {
        // Disable active tabs
        jQuery('#footerDialog').find('.active')
            .removeClass('active')
        .end()
            .find('#footerDialogHeader #' + tabIndex + ',#footerDialogContents div.footerDialogTab.' + tabIndex)
            .addClass('active');
    }
    // A animation is required
    else
    {
        // Get the dialog
        var dialog = jQuery('#footerDialog');
        
        // Get the header
        var headerList = jQuery('#footerDialogHeader ul');
        
        // Disable the active header tab
        headerList.find('li.active').removeClass('active');
    
        // Enable the new header tab
        headerList.find('li.' + tabIndex).addClass('active');
        
        // Hide the active tab content
        jQuery('div.footerDialogTab.active').removeClass('active');

        // Display the new active header and tab
        dialog.find('#footerDialogHeader #' + tabIndex + ',#footerDialogContents div.footerDialogTab.' + tabIndex)
        	.addClass('active');
    }
};

var hideFooterDialog = function ()
{
    // Fade in both
	myDesignJS.fadeOut('#footerDialogOverlay');
	myDesignJS.fadeOut('#footerDialog');
};

var showFooterDialog = function (tabIndex)
{
    // Check whether a tab index is given
    if (typeof(tabIndex) == 'undefined')
    {
        tabIndex = 'aboutSellaround';
    }
    
    // Get the overlay
    var overlay = jQuery('#footerDialogOverlay');

    // Get the dialog
    var dialog = jQuery('#footerDialog');

    // Enable the prefered tab
    enableFooterDialogTab(tabIndex, false);

    // Fade in both    
    myDesignJS.fadeIn(overlay);
    myDesignJS.fadeIn(dialog);
    
    // Get the header list
    var headerList = dialog.find('#footerDialogHeader ul');
  
    // Set up the header events
    headerList.find('li[class!=close]').unbind("click").click(function()
    {
        // Get the tab index of the clicked tab
        var newIndex = jQuery(this).attr('id');
        
        // Enable the tab
        enableFooterDialogTab(newIndex, true);
    });
    
    // Set up the close events
    dialog.find('div.close,li.close').unbind("click").click(function()
    {
        hideFooterDialog();
    });
};

/****************
 * scroll widget (T.Kekeisen)
    modified by M.Schneider
 ****************/


var timer = null;

var calcAnimationRuntime = function (way)
{
    return Math.round(way*5);
};

var rightColToWidgetOffset = 40;
var contentWidgetDetailsToRightColOffset = 500;

//The window got resized
var checkWidgetPositions = function (timed)
{
    if (typeof(timed) != "boolean" || !timed)
    {
        timed = false;
    }

    // reset the timer on each scrolling event if it is already active
    if (!timed)
    {
        if (timer !== null)
        {
            clearTimeout(timer);
        }
        timer = setTimeout(function () { checkWidgetPositions(true); },400);
    
        return;
    }
    
    timer = null;
    
    // Get all visible widgets
    var allWidgets = jQuery('div.widgetDetailContent:visible').find('iframe.widgetIFrame');

    // Get the scroll position
    var scrollTop = jQuery(window).scrollTop();

    // Iterate all widgets
    allWidgets.each(
    	function (index, widget)
    	{
	        // jQuery the widget
	        widget = jQuery(widget);
	
            // Get the parent container (.rightcol)
            var parentContainer = widget.parent();

            // Get the parent container offset
            var parentContainerOffset = parentContainer.offset();
            
            // Get the container's parent height (as the container grows)
            var containerHeight = parentContainer.parent().height();

            // Calculate the maximum height
            var maxHeight = containerHeight - contentWidgetDetailsToRightColOffset - rightColToWidgetOffset;

            // Get the height of the gap
            var gapHeight = scrollTop - parentContainerOffset.top - rightColToWidgetOffset;

            // If the user scrolls too fast
            if (gapHeight > maxHeight)
            {
                gapHeight = maxHeight;
            }


            // Check whether we are not out of bounds
            var distance = 0;
            var newMarginTop = 0;
            if (gapHeight < maxHeight && gapHeight > 0)
            {
                //scroll within the boundaries of the .rightcol parent
                newMarginTop = gapHeight;
                distance = Math.round(Math.abs(newMarginTop-widget.css('marginTop').substring(0,widget.css('marginTop').length-2)));
            }
            else if (gapHeight <= 0)
            {
                //scroll to the top: user scrolled anywhere over this .rightcol
                newMarginTop = 0;
                distance = Math.round(widget.css('marginTop').substring(0,widget.css('marginTop').length-2));
            }
            else if (gapHeight >= maxHeight)
            {
                //scroll to the bottom: user scrolled anywhere under this .rightcol
                newMarginTop = gapHeight-1;
                distance = Math.round(Math.abs(newMarginTop-widget.css('marginTop').substring(0,widget.css('marginTop').length-2)));
            }
            
            if (typeof(distance) == "number" && distance > 0)
            {
                var time = calcAnimationRuntime(distance);
                var easing = "easeOutElastic";
                if (distance < 200)
                {
                    easing = "easeOutCirc";
                }

                // Reset the widget position
                widget.stop();
                widget.animate( {'marginTop': newMarginTop+"px"}, time,easing );
            }
	    }
    );
};


/****************
 * jqplot for analyze (J.Ziegler)
 ****************/

/*
 * http://www.jqplot.com/docs/files/jqPlotOptions-txt.html
 * http://www.jqplot.com/docs/files/jqplot-core-js.html 
 */

// array that stores the plot objects for each analyse chart 
var plot_analyse_charts_array = [];

/**
 * renders the chart on base of viewsData and salesData in the chartDiv of the widget
 * 
 * @param index widget index (display order)
 * @param viewsData [[2010-01-01,value1],[2010-01-01,value2],...]
 * @param salesData  see above
 * @param tickInterval (interval for writing the date on the x axis, e.g. '2 weeks')
 * @param viewsLabel label for "views" in diagram
 * @param salesLabel label for "sales" in diagram  
 * @param language locale/language style used for diagramm date output
 */
var plot_analyse_chart = function (index, viewsData, salesData, tickInterval, viewsLabel, salesLabel, language) {

	// globally enable plugins
	jQuery.jqplot.config.enablePlugins = true;
	
	// choose date pattern
	var datePattern;
	var dateText;
	var valueText;
	if(language.indexOf('en') != -1)
	{
		datePattern = '%m/%d/%y';
		dateText = "Date";
		valueText = "Value";
	}
	else
	{
		datePattern = '%d/%m/%y';
		dateText = "Datum";
		valueText = "Wert";
	}
		
	// prevents drawing empty chart (data empty date range validation)
	if(viewsData.length > 0 && salesData.length > 0) 
	{
		plot = jQuery.jqplot('chart_'+index, [viewsData,salesData], {
			axesDefaults:
			{
				autoscale: true,
				tickOptions: 
				{
					showGridline: false,
					fontFamily: '"Trebuchet MS" ,Arial, Sans-serif',
					fontSize: '11px'
				}
			},
  			axes:
      		{
  				xaxis:
  				{
					renderer: jQuery.jqplot.DateAxisRenderer,
					rendererOptions: {tickRenderer:jQuery.jqplot.CanvasAxisTickRenderer},
					min: viewsData[0][0],
					max: viewsData[viewsData.length-1][0],
					tickInterval: tickInterval,
					tickOptions: 
					{
      					formatString: datePattern
					}					
  				},
  				yaxis:
      			{						
					min: 0,			
					label: viewsLabel,
					tickOptions: 
					{
						formatString: '%.0f'							
					}
      			},
      			y2axis:
      			{						
					min: 0,
					label: salesLabel,
					tickOptions: 
					{
						formatString: '%.0f'							
					}
      			}					
      		},
		    seriesDefaults: 
			{
				lineWidth:2
			},				
			series:
	  		[
	  		 	{
	  		 		label: viewsLabel,
	  		 		color: '#94B9CA'
	  		 	},
	   			{
	  		 		yaxis: 'y2axis',
	       			label: salesLabel,
	       			color: '#F5AE4A'
	       		}
	   		],
		    legend: 
	  		{
		        show: true,
		        location: 'ne',    
		        xoffset: 15,    
		        yoffset: 15 ,
				fontFamily : '"Trebuchet MS" ,Arial, Sans-serif',
				fontSize : '11px'
	  		},
	  		highlighter:
	  		{
	  		    tooltipAxes: 'xy',
	  		    sizeAdjust: 7.5,
	  		    formatString:'<table class="jqplot-highlighter"><tr><td>'+ dateText +':</td><td>%s</td></tr><tr><td>'+ valueText +':</td><td>%s</td></tr></table>'	  		    
	  		},
	  	    cursor: {  
	  	      showVerticalLine: true,
	  	      showCursorLegend: true,	  	      
	  	      cursorLegendFormatString: '%s %3$s',
	  	      showTooltip: false	  	      		
	  	    }	  		

		});		
		
		if(this.plot_analyse_charts_array[index] != null)
		{
			this.plot_analyse_charts_array[index] = plot;
			this.plot_analyse_charts_array[index].replot();
		}
		else
		{
			this.plot_analyse_charts_array[index] = plot;
		}
	}
};



/***********************************************/
/*************   STARTPAGE V2   ****************/
/***********************************************/

var startPageV2AnimationActive = false;

jQuery(document).ready(function ()
{

    // Add some slideshow stuff
    jQuery('#startPageV2Footer .startPageV2Slideshow').append
    (
        jQuery('<span></span>').addClass('startPageV2SlideshowScrollLeft')
    )
    .append
    (
        jQuery('<span></span>').addClass('startPageV2SlideshowScrollRight')
    ).each(function (index)
    {
        var childCount = jQuery(this).find('li').length;

        var list = jQuery(this).find('.startPageV2SlideshowContent ul');

        var dotList = jQuery('<ul></ul>').addClass('startPageV2DotList');

        for (var i = 0; i < childCount; ++i)
        {
            dotList.append(jQuery('<li></li>').click(function ()
            {
                if (!startPageV2AnimationActive)
                {
                    startPageV2AnimationActive = true;
                    var index = jQuery(this).parent().find('li').index(jQuery(this));

                    // Animate the content
                    list.animate({ marginLeft: -(index * 660) }, 250, function () { startPageV2AnimationActive = false; startPageV2SlideshowUpdateScrollDots(); });



                }
            }));
        }

        dotList.find('li:eq(0)').addClass('selected');
        dotList.css('left', (690 / 2) - (childCount * 14 - 4) / 2);
        jQuery(this).append(dotList);

    });

    jQuery('.startPageV2SlideshowScrollLeft').click(function ()
    {
        // Get the slideshow content list
        var list = jQuery(this).parent().find('.startPageV2SlideshowContent ul');

        // Check whether we are able to scroll to the left
        if (!startPageV2AnimationActive)
        {
            startPageV2AnimationActive = true;

            if (parseInt(list.css('margin-left')) < 0)
            {
                // Animate the content
                list.animate({ marginLeft: parseInt(list.css('margin-left')) + 660 }, 250, function () { startPageV2AnimationActive = false; startPageV2SlideshowUpdateScrollDots(); });
            }
            else
            {
                // Animate the content
                list.animate({ marginLeft: -((list.find('li').length - 1) * 660) }, 250, function () { startPageV2AnimationActive = false; startPageV2SlideshowUpdateScrollDots(); });
            }


        }
    });

    jQuery('.startPageV2SlideshowScrollRight').click(function ()
    {
        // Get the slideshow content list
        var list = jQuery(this).parent().find('.startPageV2SlideshowContent ul');

        // Check whether we are able to scroll to the left
        if (!startPageV2AnimationActive)
        {
            startPageV2AnimationActive = true;

            if (parseInt(list.css('margin-left')) - 660 > -(list.find('li').length * 660))
            {
                // Animate the content
                list.animate({ marginLeft: parseInt(list.css('margin-left')) - 660 }, 250, function () { startPageV2AnimationActive = false; startPageV2SlideshowUpdateScrollDots(); });
            }
            else
            {
                // Animate the content
                list.animate({ marginLeft: 0 }, 250, function () { startPageV2AnimationActive = false; startPageV2SlideshowUpdateScrollDots(); });
            }


        }
    });


    jQuery('#startPageV2BoxCenter a').click(function ()
    {
        jQuery('#startPageV2VideoOverlay').fadeIn(200);

        return false;
    });

    var temp = function ()
    {
        jQuery('#startPageV2VideoOverlay').fadeOut(200, function ()
        {
            var parent = jQuery('#startPageV2VideoOverlay').parent();

            var video = jQuery('#startPageV2VideoOverlay').clone();

            jQuery('#startPageV2VideoOverlay').remove();

            parent.append(video);


            jQuery('#startPageV2VideoOverlayClose').click(temp);
        });


        return false;
    };

    jQuery('#startPageV2VideoOverlayClose').click(temp);





    // Add some slideshow stuff
    jQuery('#startPageV2FooterRightReferences').append
    (
        jQuery('<span></span>').addClass('startPageV2ReferencesSlideshowScrollLeft')
    )
    .append
    (
        jQuery('<span></span>').addClass('startPageV2ReferencesSlideshowScrollRight')
    );

    jQuery('.startPageV2ReferencesSlideshowScrollLeft').click(function ()
    {
        // Get the slideshow content list
        var list = jQuery(this).parent().find('ul');

        // Check whether we are able to scroll to the left
        if (!startPageV2AnimationActive)
        {
            startPageV2AnimationActive = true;

            if (parseInt(list.css('margin-left')) < 0)
            {
                // Animate the content
                list.animate({ marginLeft: parseInt(list.css('margin-left')) + 310 }, 250, function () { startPageV2AnimationActive = false; startPageV2SlideshowUpdateScrollDots(); });
            }
            else
            {
                // Animate the content
                list.animate({ marginLeft: -((list.find('li').length - 1) * 310) }, 250, function () { startPageV2AnimationActive = false; startPageV2SlideshowUpdateScrollDots(); });
            }


        }
    });

    jQuery('.startPageV2ReferencesSlideshowScrollRight').click(function ()
    {
        // Get the slideshow content list
        var list = jQuery(this).parent().find('ul');

        // Check whether we are able to scroll to the left
        if (!startPageV2AnimationActive)
        {
            startPageV2AnimationActive = true;

            if (parseInt(list.css('margin-left')) - 310 > -(list.find('li').length * 310))
            {
                // Animate the content
                list.animate({ marginLeft: parseInt(list.css('margin-left')) - 310 }, 250, function () { startPageV2AnimationActive = false; startPageV2SlideshowUpdateScrollDots(); });
            }
            else
            {
                // Animate the content
                list.animate({ marginLeft: 0 }, 250, function () { startPageV2AnimationActive = false; startPageV2SlideshowUpdateScrollDots(); });
            }


        }
    });


});

var startPageV2SlideshowUpdateScrollDots = function ()
{
    jQuery('#startPageV2Footer .startPageV2Slideshow .startPageV2SlideshowContent ul').each(function (index)
    {
        var index = Math.abs(parseInt(jQuery(this).css('marginLeft'))) / 660;
        
        jQuery(this).parent().parent().find('.startPageV2DotList li').removeClass('selected').eq(index).addClass('selected');

    });
};
