﻿
var inEditMode = getParameterByName('idkeep');

function getParameterByName(name) {
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if (results == null)
		return "";
	else
		return decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(document).ready(function () {
    $('.showDetails').click(function () {
        $('.moreDetails').slideToggle('slow', function () {
            // Animation complete.
        });
    });
});
$(document).ready(function () {
    $('.underlying').jScrollPane(
		{
		    showArrows: true,
		    horizontalGutter: 30,
		    verticalGutter: 30
		}
	);
});
$(document).ready(function () {
    //Get querysting parameter 'idkeep', if the value of the parameter
    //is set to 'true' it means that we're in EPiServer edit mode
    //Don't run these functions if we're in EPiServer edit mode
    if (!inEditMode) {
        StartDateTime(true);
        StartTicker();
    }
    
    LoadCustomDropDowns();
    LoadMenus();
    LoadPopups();
    LoadPrint(".print");
    $("input[type='password']").focus(function () {
        $(this).select();
    });
    $(".validationError").click(function () {
        $(this).hide();
    });
});

function OpenPopup(e, w) {
    var left;

    left = ($("#Content").width() / 2) - (w / 2) - 15;

    $("#PopupSmallContent").load(e + " .innerContent", $("#PopupSmall").css({ 'display': 'block', 'width': w + 'px', 'left' : left + 'px' }));
    $("#PopupSmall").draggable();
}

function LoadPopups() {
        $(".closer").click(function () {
        $(this).parent(".popup").hide();
    });


}

function SetCurrentPageIndex(item) {
    var currentPageIndex = $('#CurrentPageIndex');
    if (currentPageIndex) {
        //var index = $(item.element).index('.item') + 1;
        //currentPageIndex.html(index);
        currentPageIndex.html($(item.element).index('.item') + 1);
    }
}

function OpenLink(item) {
    //var pageLink = $(item.content).attr('alt');
    //window.location.href = pageLink;
    window.location.href = $(item.content).attr('alt');
}

function ShowProductInfo(item, language) {
    //var pageId = $(item.element).attr("id").replace("i", "");
    //SetProductInfo(pageId, '.productInfoContainer');
    SetProductInfo($(item.element).attr("id").replace("i", ""), '.productInfoContainer', language);
}



function LoadFancyDropDowns() {
    //$('#PageFlowFilter').css('visibility', 'visible');
    
    $('.fancyDropdown').selectbox({
        containerClass: 'selectBox',
        inputClass: 'selectInput'
    });
}

function StartTicker() {
    $(".tickers").show();
	$("#IndexTicker").smoothDivScroll({ autoScroll: "always", autoScrollDirection: "endlessloopright", autoScrollStep: 1, autoScrollInterval: 15 });
}

// -------------------------------------
// iWant menu
// -------------------------------------
var timeout = 500;
var closetimer = 0;
var iwantmenuitem = 0;

function iwant_open() {
	iwant_canceltimer();
	iwant_close();
	iwantmenuitem = $(this).find('ul').css('visibility', 'visible');
}

function iwant_close()
{ if (iwantmenuitem) iwantmenuitem.css('visibility', 'hidden'); }

function iwant_timer()
{ closetimer = window.setTimeout(iwant_close, timeout); }

function iwant_canceltimer() {
	if (closetimer) {
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}


function LoadCustomDropDowns() {
    $('#QuickLinks_pnlDdlWant').hide();
    $('#IWant').show();
    $('.langButtonSelected').show();
    $('.languagesJS').attr('id', 'Language');
    $('#Language').show();
    $('#IWant > li').bind('mouseover', iwant_open)
    $('#IWant > li').bind('mouseout', iwant_timer)
    $('#Language > li').bind('mouseover', language_open)
    $('#Language > li').bind('mouseout', language_timer)

        $('.search input[type="text"]').each(function () {
            $(this).focus(function () {
                if (this.value == this.defaultValue) {
                    this.value = '';
                }

                if (this.value != this.defaultValue) {
                    this.select();
                }
            });

            $(this).blur(function () {

                if ($.trim(this.value) == '') {
                    this.value = (this.defaultValue ? this.defaultValue : '');
                }
            });
        });

    $('.txtClear').show();
    $('.txtShow').hide();

    $('.txtClear').focus(function () {
        $(this).hide();
        $(this).next().show().focus();
    });

    $('.txtShow').blur(function () {
        if ($.trim(this.value) == '') {
            $(this).prev().show();
            $(this).hide();
        }
    });

}
document.onclick = iwant_close;
document.onclick = language_close;

// -------------------------------------
// language menu
// -------------------------------------
var languagemenuitem = 0;

function language_open() {
	language_canceltimer();
	language_close();
	languagemenuitem = $(this).find('ul').css('visibility', 'visible');
}

function language_close()
{ if (languagemenuitem) languagemenuitem.css('visibility', 'hidden'); }

function language_timer()
{ closetimer = window.setTimeout(language_close, timeout); }

function language_canceltimer() {
	if (closetimer) {
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// -------------------------------------
// Menus
// -------------------------------------
var mainMenu = null;
var subMenu = null;
var subMenuTimer = null;
var index = -1;

function LoadMenus() {
    mainMenu = $('.mainMenu ul');
    subMenu = $('.subMenu');
    var selectedMainMenuItem = $('.mainMenu ul li a.selected');
    
    //If the submenu is visible then position it relative to the selected item in the mainmenu
    if (subMenu.is(':visible')) {
        //Add 14px correction for padding
        PositionSubMenu(mainMenu, selectedMainMenuItem, subMenu, 14);
    }
    else {
        LoadMainMenuWithHover();
    }
    //Remove border on last item in submenu
    $(".subMenu ul li:last a").css('border', 'none');
}

function LoadMainMenuWithHover() {
	$(".mainMenu ul li").hover(
        function () {
        	CancelSubMenuTimer();

        	//Get index of the current item in the list
        	var currentIndex = $(this).index();

        	//Check if the current item is in a submenu 
        	var isSubMenu = $(this).parent('ul.2').size() > 0;

        	//If the current item is in a submenu use the existing index
        	if (isSubMenu) {
        		currentIndex = index;
        	}

        	//Check if the index has changed
        	var indexChanged = currentIndex != index;

        	//Don't do anything if the index has not changed
        	if (!indexChanged) {
        		return;
        	}

        	//Hide the submenu
        	if (subMenu != null) {
        		subMenu.hide();
        	}

        	//Set the new index
        	index = currentIndex;

        	//Render the submenu
        	subMenu = $("ul", this);
        	subMenu.children('li:last').children().css('border', 'none');
        	subMenu.show();
        	PositionSubMenu(mainMenu, $(this), subMenu, 0);
        },
        function () {
        	subMenu = $("ul", this);
        	StartSubMenuTimer();
        }
    );
}

function HideSubMenu() {
	if (subMenu) {
		subMenu.fadeOut('fast');
		index = -1;
	}
}

function StartSubMenuTimer() {
	if (!subMenuTimer) {
		subMenuTimer = setTimeout(HideSubMenu, 600);
	}
}

function CancelSubMenuTimer() {
	if (subMenuTimer) {
		clearTimeout(subMenuTimer);
		subMenuTimer = null;
	}
}

function PositionSubMenu(mainMenu, selectedMainMenuItem, selectedSubMenu, correction) {
	//Reset position to avoid errors when calculating width
	selectedSubMenu.css('left', 0);

	var mainMenuPositionLeft = mainMenu.position().left;
	var mainMenuPositionRight = mainMenuPositionLeft + mainMenu.width();
	var subMenuWidth = selectedSubMenu.width();
	var mainMenuItemPositionLeft = selectedMainMenuItem.position().left;

	var leftPosition = mainMenuItemPositionLeft - (subMenuWidth / 3);

	//If the submenu outside to the left of the mainmenu
	if (leftPosition < mainMenuPositionLeft) {
		leftPosition = mainMenuPositionLeft;
	}

	//If the submenu outside to the right of the mainmenu
	if (leftPosition + subMenuWidth > mainMenuPositionRight) {
	    //Remove 14px for padding
	    leftPosition = mainMenuPositionRight - subMenuWidth - 14;
	}
	
	//Add correction to position if specified    
	leftPosition = leftPosition + correction;

	selectedSubMenu.css('left', leftPosition);
}

// -------------------------------------
// DateTimeTicker
// -------------------------------------
var _timeout;
var _showClock;

var _h1Current = -1;
var _h2Current = -1;
var _m1Current = -1;
var _m2Current = -1;
var _d1Current = -1;
var _d2Current = -1;
var _monthCurrent = -1;

function StartDateTime(showClock) {
	_showClock = !showClock;
	SwitchDateTime();

	setInterval('SwitchDateTime()', switchInterval);
}

function SwitchDateTime() {
	clearTimeout(_timeout);

	if (_showClock) {
		UpdateDate();
		$('#TimeTicker').hide();
		$('#DateTicker').show();

		_timeout = setInterval('UpdateDate()', 1000);
		_showClock = false;
	}
	else {
		UpdateTime();
		$('#DateTicker').hide();
		$('#TimeTicker').show();

		_timeout = setInterval('UpdateTime()', 1000);
		_showClock = true;
	}
}

function UpdateTime() {
	var now = new Date();
	var hours = now.getHours();
	var minutes = now.getMinutes();

	// Pad the hours and minutes with leading zeros, if required
	hours = (hours < 10 ? "0" : "") + hours;
	minutes = (minutes < 10 ? "0" : "") + minutes;

	var h1 = hours.substring(0, 1);
	var h2 = hours.substring(1, 2);
	var m1 = minutes.substring(0, 1);
	var m2 = minutes.substring(1, 2);

	if (h1 != _h1Current) {
		$('#HourFirst').attr("src", GetImageSource("", h1));
		$('#HourFirst').attr("alt", h1);
		_h1Current = h1;
	}
	if (h2 != _h2Current) {
		$('#HourSecond').attr("src", GetImageSource("", h2));
		$('#HourSecond').attr("alt", h2);
		_h2Current = h2;
	}
	if (m1 != _m1Current) {
		$('#MinuteFirst').attr("src", GetImageSource("", m1));
		$('#MinuteFirst').attr("alt", m1);
		_m1Current = m1;
	}
	if (m2 != _m2Current) {
		$('#MinuteSecond').attr("src", GetImageSource("", m2));
		$('#MinuteSecond').attr("alt", m2);
		_m2Current = m2;
	}
}

function UpdateDate() {
	var now = new Date();
	var date = now.getDate();
	var month = now.getMonth();

	// Pad the date with leading zeros, if required
	date = (date < 10 ? "0" : "") + date;

	var d1 = date.substring(0, 1);
	var d2 = date.substring(1, 2);

	// Get the current language, fallback to swedish
	var lang = getCookie('epslang');
	if (lang == "") lang = "sv";

	if (d1 != _d1Current) {
		$('#DayFirst').attr("src", GetImageSource("", d1));
		$('#DayFirst').attr("alt", d1);
		_d1Current = d1;
	}
	if (d2 != _d2Current) {
		$('#DaySecond').attr("src", GetImageSource("", d2));
		$('#DaySecond').attr("alt", d2);
		_d2Current = d2;
	}
	if (month != _monthCurrent) {
		$('#Month').attr("src", GetImageSource(lang, month));
		$('#Month').attr("alt", month);
		_monthCurrent = month;
	}
}

function GetImageSource(subfolder, number) {
	return "/Templates/Images/DateTimeTicker/" + subfolder + "/" + number + ".png";
}

function getCookie(cookieName) {
	if (document.cookie.length > 0) {
		var cookieStart = document.cookie.indexOf(cookieName + "=");
		if (cookieStart != -1) {
			cookieStart = cookieStart + cookieName.length + 1;
			var cookieEnd = document.cookie.indexOf(";", cookieStart);
			if (cookieEnd == -1) cookieEnd = document.cookie.length;
			return unescape(document.cookie.substring(cookieStart, cookieEnd));
		}
	}
	return "";
}

// -------------------------------------
// Products
// -------------------------------------
function SetProductInfo(pageId, elementId, language) {
    if (pageId == '' || pageId == 'undefined' || pageId == undefined) {
        return;
    }

    if (language == null || language == undefined || language == 'undefined' || language == '') {
        language = 'sv';
    }

    var productInfoContainer = $(elementId);
    if (!productInfoContainer) {
        return;
    }

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: '/Templates/Pages/ProductListPage.aspx/GetProductInfo',
        data: "{'pageId':'" + pageId + "', 'language':'" + language + "'}",
        dataType: "json",
        success: function (msg) {
            if (msg != null) {
                productInfoContainer.html(msg.d)
            }
        },
        error: function (xhr, status, error) {
            //alert(error + '\n' + status + '\n' + xhr.statusText);
        }
    });
}

// -------------------------------------
// Product listing
// -------------------------------------

function LoadFilters() {
    $('.noJSDropDownFix').hide();
    $('#PageFlowFilter').show();
    $('.productListPadding').show();
    $('.listLink').hide();
    $('.listName').show();
 }

 function SetView(e) {
     if (e == '#ListContent') {
        $('#PageFlowContent').hide();
        $('#ListContent').show();
    }

    else {
        $('#ListContent').hide();
        $('#PageFlowContent').show();
    }
}

function LoadView() {

    $('#PageFlowView').click(function () {
        SetView('#PageFlowContent');
        window.location.hash = '#PageFlowContent';
        //FilterCoverFlow("", "");
        //window.location.href = window.location.pathname + $.query.toString() + "#PageFlowContent";
        
    });

    $('#ListView').click(function () {
        SetView('#ListContent');
        window.location.hash = '#ListContent';
        //FilterCoverFlow("", "");
        //window.location.href = window.location.pathname + $.query.toString() + "#ListContent";
    });
}

var currentCurrency = "SEK";
var currentCategory = "";
var portfolioMode = false;

function MakeActiveDropDownList(item) {
    $('.selectInput, .filterButton').removeClass('selected');

    var input = $(item).parent().find('input');
    input.addClass('selected');
}

function MakeActiveButton(item) {
    $('.selectInput, .filterButton').removeClass('selected');
    $(item).addClass('selected');
}

//s
//function FilterCurrencyNew(currency) {
//    if (currency == "") {
//        return;
//    }

//    currentCurrency = currency;

//    if (portfolioMode) {
//        GetPortfolios();
//    }
//    else {
//        FilterProducts(currentCurrency, currentCategory);
//    }
//} 

function FilterCategory(category) {
    if (category == "") {
        return;
    }

    portfolioMode = false;
    currentCategory = category;
    FilterProducts(currentCurrency, currentCategory);
}

function FilterProducts(currency, category) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: '/Templates/Pages/ProductListPage.aspx/GetNewProductsByCurrencyAndCategory',
        data: "{'currency':'" + currency + "', 'category':'" + category + "'}",
        dataType: "json",
        success: function (msg) {
            if (msg != null) {
                LoadProducts(msg.d);
            }
        },
        error: function (xhr, status, error) {
            //alert(error + '\n' + status + '\n' + xhr.statusText);
        }
    });
}

function ShowPortfolios() {
    portfolioMode = true;
    GetPortfolios();
}

function GetPortfolios() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: '/Templates/Pages/ProductListPage.aspx/GetPortfolios',
        data: "{'currency':'" + currentCurrency + "'}",
        dataType: "json",
        success: function (msg) {
            if (msg != null) {
                LoadProducts(msg.d);
            }
        },
        error: function (xhr, status, error) {
            //alert(error + '\n' + status + '\n' + xhr.statusText);
        }
    });
}

function LoadProducts(pages) {
    var pageFlowItems = new Array();
    var listItems = new Array();

    //Create new html elements for each product
    $.each(pages, function (index, page) {
        pageFlowItems[index] = CreatePageFlowItem(page);
        listItems[index] = CreateListItem(page);
    });

    //Remove all existing items from pageflow
    for (var i = pageFlow.getNumberOfItems(); i > 0; i--) {
        pageFlow.rmItem(i);
    }

    //Remove all existing items from list (don't remove header)
    $('#ListContent table').find("tr:gt(0)").remove();

    //Update the number of items in pageflow
    var lblPageCount = $('#lblPageCount');
    if (lblPageCount) {
        lblPageCount.html(pageFlowItems.length);
    }

    //Remove existing content if no items are found
    if (pageFlowItems.length == 0) {
        $('.productInfoContainer').empty();
        $('.caption').empty();

        var currentPageIndex = $('#CurrentPageIndex');
        if (currentPageIndex) {
            currentPageIndex.html('0');
        }

        return;
    }

    //Add the new items to pageflow
    for (var i = 0; i < pageFlowItems.length; i++) {
        pageFlow.addItem(pageFlowItems[i], 'last');
    }

    //Add the new items to the list
    $('#ListContent table').append($(listItems));
}

function CreatePageFlowItem(page) {
    var flowItem = document.createElement('div');
    flowItem.setAttribute('class', 'item');
    flowItem.setAttribute('id', "i" + page.PageLink.ID);

    var flowImage = document.createElement('img');
    flowImage.setAttribute('class', 'content');
    flowImage.setAttribute('src', page.FlowImage);
    flowImage.setAttribute('alt', page.LinkURL);

    var flowCaption = document.createElement('div');
    flowCaption.setAttribute('class', 'caption');

    var flowHeadingLink = document.createElement('a');
    flowHeadingLink.setAttribute('href', page.LinkURL);
    flowHeadingLink.appendChild(document.createTextNode(page.FlowHeading));

    var flowDescriptionLink = document.createElement('a');
    flowDescriptionLink.setAttribute('href', page.LinkURL);
    flowDescriptionLink.appendChild(document.createTextNode(page.FlowShortDescription));

    var flowHeading = document.createElement('h3');
    flowHeading.appendChild(flowHeadingLink);

    flowCaption.appendChild(flowHeading);
    flowCaption.appendChild(flowDescriptionLink);

    flowItem.appendChild(flowImage);
    flowItem.appendChild(flowCaption);

    return flowItem;
}

function CreateListItem(page) {
    var listItem = document.createElement('tr');
    listItem.setAttribute('id', "i" + page.PageLink.ID);
    listItem.setAttribute('class', 'details');

    var firstColumn = document.createElement('td');
    firstColumn.innerHTML = page.PageName;

    var secondColumn = document.createElement('td');
    var lastRegDate = new Date(parseInt(page.LastRegDate.substr(6)));
    secondColumn.innerHTML = lastRegDate.getFullYear() + '-' + (lastRegDate.getMonth() + 1) + '-' + lastRegDate.getDate();

    listItem.appendChild(firstColumn);
    listItem.appendChild(secondColumn);

    return listItem;
}


// -------------------------------------
// Product listing. Accordion + sort
// -------------------------------------

function LoadDateAndAccordion() {

    $('.details').addClass('highlightable');
    $('#ListContent').addClass('accordionTable');
    

    var tr;
    var choosenDate;
    var productId;

        //Get possible saved values from asp:hiddenfields
        productId = $("#accordionID").val();
        choosenDate = $("#selectedDate").val();

        //Bind datepicker to inputcontrol with given settings
        $("#datepicker").datepicker({ showOn: 'both', nextText: '>', prevText: '<',
            onClose: function (dateText, inst) {
                if (dateText != "") {
                    $("#selectedDate").val(dateText);
                    $("#accordionID").val(productId);
                    $("#savedTR").val($("#description"));
                    $("#selectedDate").val(dateText);
                    $("#datepicker").val(dateText);
                    $("#datepicker").change();
                }
            },
            dateFormat: 'yy-mm-dd',
            buttonImage: "/Templates/Images/CalenderIcon.png",
            buttonImageOnly: true
         });

        //Check if there was a saved choosendate. If true then set that date, else set todays date
        if (choosenDate != "" && choosenDate != null) {
            $('#datepicker').datepicker('setDate', choosenDate);
        }
        else {
            $('#datepicker').datepicker('setDate', new Date());
        }


        //Bind accordion remover/saver to table headers (To be able to remove/save accordion before sorting the table)
        $(".accordionTable a").click(function () {
            //if an accordion exist save it to tr
            if ($("#description") != null) {
                tr = $("#description");
            }
            //remove tr before sorting
            $("#description").remove();
        });

        //Bind accordion method to table rows
        $(".accordionTable tr.details").click(function () {
            var currentRow = $(this);
            var pageId = currentRow.attr('id').replace("li", "");
            $(".details").removeClass('accordionTableHighlight');
            currentRow.addClass('accordionTableHighlight');


            //If an accordion exist at same row remove it
            if ($(this).next().is("#description")) {
                $("#description").remove();
                productId = "";
                $(this).removeClass('accordionTableHighlight');

            }
            //If an accordion exist but not for this row then remove accordion and add a new one for this row
            //If no accordion exist add a new one after this row
            else {
                $("#description").remove();
                $(this).after("<tr ID='description'><td ID='descriptionTd' colspan='8'> </td></tr>");
                productId = pageId;
                SetProductInfo(pageId, '#descriptionTd', currentLanguage);
            }
            
        });
    

        //Bind table sort function with given settings
        $("#ExpiredProducts").dataTable({ "bStateSave": true, "bPaginate": false, "bFilter": false, "bInfo": false, "oLanguage": { "sEmptyTable": "No search results" }, "fnDrawCallback": function () {
            if (productId != "") {
                $('#' + productId).after(tr);
            }
        }
        });
        //Bind table sort function with given settings
        $("#OngoingProducts").dataTable({ "bStateSave": true, "bPaginate": false, "bFilter": false, "bInfo": false, "oLanguage": { "sEmptyTable": "No search results" }, "fnDrawCallback": function () {
            if (productId != "") {
                $('#' + productId).after(tr);
            }
        }
        });

        //if both tr and product id are saved then insert a accordion <tr> after productid row
        if (tr != "" && productId != "") {
            $('#' + productId).after("<tr ID='description'><td ID='descriptionTd' colspan='8'> </td></tr>");
            $('#' + productId).addClass('accordionTableHighlight');
            SetProductInfo(productId, '#descriptionTd');
        }
    }


//--------------------------------------------------------
//Used on ProductListPage
//Build products querystring based on klick in menu 
//Dependency  jquery.query-2.1.7.js
//--------------------------------------------------------
function FilterCoverFlow(sKey, sValue) {
    //Get base url 
    var url = window.location.pathname;

    //Get current url
    var q = $.query.toString();

    //Get current anchor
    var ahor = window.location.hash.toString();

    //Check if its a value if not remove key and return
    if (sValue == "") {
        q = $.query.REMOVE(sKey);
    }
    else {
        if (sKey == "category") {
            q = $.query.REMOVE("protection").REMOVE("portfolio").set(sKey, sValue);
        } else if (sKey == "protection") {
            q = $.query.REMOVE("category").REMOVE("portfolio").set(sKey, sValue);
        } else if (sKey == "currency") {
            q = $.query.REMOVE("category").REMOVE("protection").REMOVE("portfolio").set(sKey, sValue);
        } else if (sKey == "portfolio") {
            q = "?" + sKey + "=" + sValue;
        }
    }

    //go to new url
    window.location.href = url + q + ahor;
}
function FilterCoverFlow2(sKey, sValue) {
    //alert(sKey + "=" + sValue);
    //Get base url 
    var url = window.location.pathname;

    //Get current anchor
    var ahor = window.location.hash.toString();

    // portfolio should not contain other parameters
    if (sKey == "portfolio") {
        window.location.href = url + "?" + sKey + "=" + sValue + ahor;
        return;
    }

    var q;

    if (!sValue) {
        q = $.query.Remove(sKey);
    } else {
        q = $.query.set(sKey, sValue);
    }
    alert(q);
    
    // otherwise set sKey and currency if exists
//    var currency = $.query.get('currency');
//    var currencyParam = "";
//    if (currency) {
//        currencyParam = "&currency=" + currency;
//    }
    window.location.href = url + q + ahor;
}

/*function LoadPopup(e, i, t) { //Creates a standard popup with an element, a trigger and a title

    $(e).dialog({ autoOpen: false, width: 450, resizable: true, modal: true, minHeight: 200, closeText: 'x', zIndex: 120000 });
        $(e).dialog('option', 'title', [t]);

        $(i).click(function () {
            $(e).dialog('open');
            return false;
        });
    }*/
    function LoadPrint(e) {
        $(e).show();
        $(e).click(function () {
            window.print();
            return false; 
        });
    }

    function LoadFixedTableHead() {
        var o = $('.fixedTableHead').offset();
        var t = $(".marketValuesTable").position;

        $(window).resize(function () {
            Fix();
        });

        $(window).scroll(function () {
            Fix();
        });

        function Fix() {

            var p = $(this).scrollTop();
            if (o.top > $(this).scrollTop()) {
                $('.fixedTableHead').removeClass('scrolling');// .css({ 'position' : 'relative', 'background' : 'none' });
                p = (o.top);
                // Column fix for IE
                if ($.browser.msie) {
                    $('.fixedTableHead th').each(function()
                    {
                        $(this).width($(this).width() + 2);
                    });
                }
            }
            else {
                $('.fixedTableHead').addClass('scrolling'); //.css({ 'position': 'absolute', 'background' : 'transparent url(\'/Images/ProduktBg.png\') repeat-y -25px' });
                p = p - o.top;
            }

            $('.fixedTableHead').css('top', p + 'px');
        }
    }


    function LoadAccordion() {

        var exp = $("#hdnExpanded").val().split("#");

        for (var i in exp) {
            var e = exp[i];
            if (e != "") {
                e = "#" + e;
                $(e).removeClass("expandable");
                $('a[href=' + e + ']').val("expanded");
                $('a[href=' + e + ']').addClass("expanded");
            }
        }

        $(".expandable").hide();
        $(".expander").addClass("icon");
        //alert($.query.get("ProductPageReference"));
        $("input[value=" + $.query.get('ProductPageReference') + "]").parent("td").parent("tr").find("input[type='text']").focus().select();

        $(".expander").click(function () {
            var s = $(this).attr("href");
            $(s).toggle();

            if ($(this).val() != "expanded") {
                $(this).val("expanded");
                $(this).addClass("expanded");

                if ($("#hdnExpanded").val().indexOf(s) == -1) {
                    $("#hdnExpanded").val($("#hdnExpanded").val() + s);
                }

            }
            else {
                $(this).val("");
                $(this).removeClass("expanded");
                $("#hdnExpanded").val("");
                for (var i in exp) {
                    var e = exp[i];
                    if (e != "") {
                        e = "#" + e;
                        if (e == s) {
                            exp.splice(i, 1);
                        }
                        else {
                            $("#hdnExpanded").val($("#hdnExpanded").val() + e);
                        }
                    }
                }
            }
            return false;
        });

    }

    function LoadExpandFromHdn() {
        
        var exp = $("#hdnExpanded").val().split('#');
        
        for (var i in exp) {
            var e = exp[i];
            if (e != "") {
                e = "#" + e;
                $(e).show();alert(e);
                $('a[href=' + e + ']').val("expanded");
                $('a[href=' + e + ']').addClass("expanded");
            }
        }
    }

    function LoadPageTreeCF() {

        var containerWidth = 670;

        var sub = $('.chapterList ul li ul').html();
        if (sub != null) {
            $('.chapterList.subChapters').html("<ul>" + $('.chapterList ul li ul').html() + "</ul>");
            $('.chapterList.chapters ul li ul').hide();
            $('.chapterContainer.subChapters').show();
            $('.chapterContainer.subChapters ul li .chapterLink:last').css('border', 'none'); 
            $('.chapterContainer.chapters .chapterLink:last').css('border', 'none');
        }

        var left;
        var speed = 180;
        var chapterScroll = 0;
        var subScroll = 0;
        var chapterWidth = $(".chapterLink").size();
        var subWidth = $(".chapterList.subChapters .chapterLink").size();

        var chapterWidth = chapterWidth - (subWidth*2);

        chapterWidth = chapterWidth * 185;
        subWidth = subWidth * 150;

        $(".chapterList.chapters").width(chapterWidth);
        $(".chapterList.chapters").height(52);
        $(".chapterList.subChapters").width(subWidth);
        

        $('.chapterContainer').css('overflow', 'hidden');
        $('.subChapterContainer').css('overflow', 'hidden');

        
        if (chapterWidth > (containerWidth + 80)) {
            
            if ($(".chapterList.chapters .chapterLink.expanded").size() > 0) {
                var position = $(".chapterList.chapters .chapterLink.expanded").position();
                left = position.left;
                left = left - (left * 2);
                chapterScroll = left;
                $('.chapterList.chapters').css("left", left)
            }
            $(".chapterContainer.chapters").width(containerWidth);
            $('.chapterContainer.chapters').css('padding', '0 30px');
            $('.chapterContainer.chapters .buttonContainer').show();
        }

        if (subWidth > (containerWidth+80)) {

            if ($(".chapterList.subChapters .chapterLink.expanded").size() > 0) {
                var subPosition = $(".chapterList.subChapters .chapterLink.expanded").position();
                left = subPosition.left;
                left = left - (left * 2);
                subScroll = left;
                $(".chapterList.subChapters").css("left", left);
            }
            $(".chapterContainer.subChapters").width(containerWidth);
            $(".chapterContainer.subChapters").css("padding", "0 30px"); 
            $(".chapterContainer.subChapters .buttonContainer").show();
        }


        
        $("#BtnChapterPrev").click(function () {
            if (chapterScroll < 0) {
                chapterScroll += speed;
                var s = chapterScroll;
                $('.chapterList.chapters').animate({ left: s + "px" }, 150);
            }
           return false;
        });
        
        $("#BtnChapterNext").click(function () {
            if (chapterScroll > (chapterWidth + 185) - (chapterWidth * 2)) {
                chapterScroll -= speed;
                var s = chapterScroll;
                $('.chapterList.chapters').animate({ left: s + "px" }, 150);
            }
            return false;
        });
        
        $('#BtnSubChapterPrev').click(function () {
            if (subScroll < 0) {
                subScroll += speed;
                var s = subScroll;
                $('.chapterList.subChapters').animate({ left: s + "px" }, 150);
            }
            return false;
        });

        $('#BtnSubChapterNext').click(function () {

            if (subScroll > (subWidth + 150) - (subWidth * 2)) {
                subScroll -= speed;
                var s = subScroll;
                $('.chapterList.subChapters').animate({ left: s + "px" }, 150);
            }
            return false;
        });
    }






