AbstractResponseParser = function() {};
var ResponseXmlParser = Class.create();
ResponseXmlParser.prototype = Object.extend(new AbstractResponseParser(), {
    initialize: function() {
        this.type = "xml";
    },

    load: function(request) {
        this.content = request.responseXML;
        this.parse();
    },

    parse: function() {
        var root = this.content.documentElement;
        var responseNodes = root.getElementsByTagName("response");
        this.itemList = new Array();
        if (responseNodes.length > 0) {
            var responseNode = responseNodes[0];
            var itemNodes = responseNode.getElementsByTagName("item");
            for (var i=0; i<itemNodes.length; i++) {
                var nameNodes = itemNodes[i].getElementsByTagName("name");
                var valueNodes = itemNodes[i].getElementsByTagName("value");
                if (nameNodes.length > 0 && valueNodes.length > 0) {
                    var name = nameNodes[0].firstChild.nodeValue;
                    var value = valueNodes[0].firstChild.nodeValue;
                    this.itemList.push(new Array(name, value));
                }
            }
        }
    }
});

function changeListingList() {
    var path = "?listcustomer=" + $F('listcustomer') + "&instrType=" + $F('instrType') + "&market=" + $F('market');
    var styleProvided = window.location.href.match(/style=(\w*)/);
    if(styleProvided) {
        path += "&style=" + styleProvided[1];
    }
    var periodProvided = window.location.href.match(/period=(\d)/);
    if(periodProvided) {
        path += "&period=" + periodProvided[1];
    }
    window.location.href = path;
}
function changeList() {
    var path = "?listcustomer=" +  $F('listcustomer');
    var styleProvided = window.location.href.match(/style=(\w*)/);
    if(styleProvided) {
        path += "&style=" + styleProvided[1];
    }
    var periodProvided = window.location.href.match(/period=(\d)/);
    if(periodProvided) {
        path += "&period=" + periodProvided[1];
    }

    window.location.href = path;
}
function changeInstrumentTypeBox() {
    //showProgressbar();
    new Ajax.Request("stockprices/jspf/listingList.jspf", {
        parameters: {list:$F('instrType'),owner:'group'},
        onSuccess: function(response) {
            fillSelectBox("market",response);
            changeMarketBox();
        }
    });
}
function changeMarketBox() {
    new Ajax.Request("stockprices/jspf/listingList.jspf", {
        parameters: {list:$F("market"),owner:'group',outputCustomer:'true'},
        onSuccess: function(response) {
            fillSelectBox("listcustomer",response);
            changeListingList();
        }
    });
}
function fillSelectBox(box,response) {
    var parser = new ResponseXmlParser();
    parser.load(response);
    var itemList = parser.itemList;
    var options = "";
    for(var i = 0; i < itemList.length; i++) {
        options += "<option value='" + itemList[i][1] + "'>" + itemList[i][0] + "<\/option>";
    }
    $(box).update(options);
    if (navigator.userAgent.toLowerCase().indexOf("msie")>-1) {
        $("market").setStyle({width:'14em'});
    }
    new Effect.Highlight(box,{startcolor:'#FFFFFF', endcolor:'#FFFFCC'})
}
var cacheDummy = 0;
function changeOverviewChart(tabdiv,id,listings,site){
    changeChart("stockprices/jspf/overviewChart.jspf",tabdiv,id,listings,"",site,200,280);
}
function changeDetailChart(tabdiv,id,listings,period,height,width){
    changeChart("detail/jspf/detailChart.jspf",tabdiv,id,listings,period,"",height,width);
}
function changeChart(page,tabdiv,id,listings,period,site,height,width){
    $('chartimg').innerHTML = '<img style="padding-top:80px;"  src="images/ajax-loader.gif"/>';
    cacheDummy++;
    new Ajax.Updater(id,page, {
        method: 'get',
        parameters:{chartid:tabdiv,width:width,height:height,vcharth:0,listings:listings,site:site,period:period,count:cacheDummy,mstyle:'9,1',href:'charts/jspf/chart.jspf?listings='+listings}
    });
}
function changeDetailChartExternal(tabdiv,id,listings,period,height,width){
    changeChart("external/suedostschweiz/detail/detailChart.jspf",tabdiv,id,listings,period,"",height,width);
}
function changeChartExternal(page,tabdiv,id,listings,period,site,height,width){
    $('chartimg').innerHTML = '<img style="padding-top:80px;"  src="images/ajax-loader.gif"/>';
    new Ajax.Updater(id,page, {
        method: 'get',
        parameters:{chartid:tabdiv,width:width,height:height,vcharth:0,listings:listings,site:site,period:period,mstyle:'9,1',href:'charts/jspf/chart.jspf?listings='+listings}
    });
}
function setCookie(name,value,path) {
    var ablauf = new Date();
    var in360Tagen = ablauf.getTime() + (360 * 24 * 60 * 60 * 1000);
    ablauf.setTime(in360Tagen);
    var cookieString = name + "=" + value + "; expires=" + ablauf.toGMTString();
    if(path) {
        cookieString += ";path=" + path;
    }else {
        cookieString += ";path=/";
    }
    document.cookie = cookieString;
}
//chart-functions
function submitChartFormular() {
    if($F('listings').indexOf($F('index'))==-1) {
        $('listings').value = $('listings').value + ";" + $('index').value;
    }
    return true;
}
function removeChartListing(listingID) {
    $('listings').value = $F('listings').replace(new RegExp(listingID + "[;]*","g"),"").replace(new RegExp(";$","g"),"");
    $('chartForm').submit();
}
function changeChartOptions() {
    if($F('period')=='AVAIL' || $F('period')=='TODAY') {
        $('chartStyle').hide();
        $('analyzeNotIntraday').hide();
    }else {
        $('chartStyle').show();
        $('analyzeNotIntraday').show();
    }
}
function expand(element1,element2) {
    if(element1.src.indexOf('plus')>-1) {
        element1.src = element1.src.replace('plus.gif','minus.gif');
        $(element2).show();
    }
    else {
        element1.src = element1.src.replace('minus.gif','plus.gif');
        $(element2).hide();
    }
}
//news functions
var time_to = new Array();
var date_to = new Array();
function getNews(timeTo, dateTo, paging) {
    var params = $('newsSelection').serialize(true);
    if (timeTo) params['time_to'] = timeTo;
    if (dateTo) params['date_to'] = dateTo;
    var path = "news.html?" + $H(params).toQueryString();
    if (timeTo && dateTo) path += "&paging=forward";
    if ($F('date_to') != "") path += "&daterefresh=yes";
    if ($F('time_to') != "") path += "&timerefresh=yes";
    //if(paging=='forward'){
    if($('extendedSearch').style['display']!='none'){
        path +=  "&extended=true";
    }else{
        path +=  "&extended=false";
    }
    //}
    window.location.href = path;
}
function submitIfEnter(event) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (event) keycode = event.which;
    else return true;
    if (keycode == 13) {
        getNews();
    }
}
function getStory(rowid,id,hl,date,time) {
    var row = $(rowid).up().childElements();
    for(var i = 0; i < row.length; i++) {
        row[i].removeAttribute("class");
        row[i].removeClassName("selected")
    }
    $(rowid).addClassName("selected");
    new Ajax.Updater("story","news/jspf/story.jspf", {
        method:'get',
        parameters:{id:id,hl:hl,date:date,time:time}
    });
}


// box code for titeldetail
var tmplWidgetMinMax = new Template("<span class=\"#{iconClass}\"><img onclick=\"#{onclick}\" src=\"#{src}\"></span>");
function changeBoxState(element, minimise,iconClass)
{
    if (!iconClass)
    {
        var iconClass = "boxIcon";
    }
    var params; var url;
    if (minimise)
    {
        new Effect.BlindUp($(element).down('.box_content', 0), {duration: 0.2});
        params = {
            onclick: "changeBoxState($('"+element.id+"'),false,'"+iconClass+"')",
            src: "images/plus.gif",
            iconClass : iconClass
        };
        setCookie(element.id, "min");
    }
    else
    {
        new Effect.BlindDown($(element).down('.box_content', 0), {duration: 0.2});
        params = {
            onclick: "changeBoxState($('"+element.id+"'),true,'"+iconClass+"')",
            src: "images/minus.gif",
            iconClass: iconClass
        };
        setCookie(element.id, "max");
    }
    $(element).down('.'+iconClass, 0).remove();
    new Insertion.Bottom($(element).down(), tmplWidgetMinMax.evaluate(params));
}
function forwardIntraday(listing,start,order){
    var lasttime = $$('.time').last().firstChild.nodeValue;
    var counter = 0;
    $$('.time').each(function(element) {
        if(element.innerHTML.match(lasttime)) counter++;
    });
    if(counter==30) {counter += parseInt(start) - 1;}
    var limitPar = 'time_to';
    if(order == 'asc'){
        limitPar = 'time_from'
    }
    if($F('t_to') != '' && $F('t_from') != ''){
        limitPar = 'time_to='+$F('t_to')+'&time_from';
    }
    window.location.href = 'intraday.html?'+limitPar+'=' + lasttime + "&start=" + (counter + 1) + "&len=" + (30 + counter) + "&listing=" + listing + "&t_to=" + $F('t_to')+ "&t_from=" + $F('t_from')+"&order="+order;
}
function chooseTimeIntraday(listing) {
    var par_tt = '&time_to=' + $F('t_to');
    var par_tf = '';
    var order = 'desc';
    if($F('t_from') != ''){
        par_tf = '&time_from=' + $F('t_from');
        order= 'asc';
    }
    window.location.href = 'intraday.html?listing=' + listing + par_tt +par_tf+ "&t_to=" + $F('t_to')+ "&t_from=" + $F('t_from')+"&order="+order;
}
function searchInstrForChart() {
    window.location.href='search.html?search=' + $F('chartInstrSearch') + '&forward=chart.html' + "&forwardparam=" + encodeURIComponent($('chartForm').serialize());
}


//heatmap
function showHeatmapListingInfo(element,listingid,contextPath,period) {
    var div = $(element).down(".heatmapPopup");
    if(!div.visible()) {
        var offset = $(element).cumulativeOffset();
        var scrollOffset = $(element).cumulativeScrollOffset();
        if(offset[1] - scrollOffset[1] + div.getHeight() + element.getHeight() * 1.5 < getViewPortHeight()) {
            div.setStyle({position:'absolute',top:offset[1] + element.getHeight() * 1.5 +'px',left:offset[0] + 'px'});
        }else {
            div.setStyle({position:'absolute',top:offset[1] - div.getHeight() * 1.1 +'px',left:offset[0] + 'px'});
        }
        div.setOpacity(0.95);
        div.show();
        new Ajax.Updater(div,contextPath + "/stockprices/jspf/heatmapListingInfo.jspf", {
            parameters:{listingid:listingid,period:period}
        });
    }
}
function showDescription(element) {
    if($(element).descendants() == 0) {
        $(element).insert("<div>hi</div>");
    }
    
}

function isWithin(event, element) {
    var delta = 2; //necessary if the movement of the mouse is slow to be sure to be outside element
    var offset = element.cumulativeOffset();
    var scrollOffset = element.cumulativeScrollOffset();
    return event.clientX - delta > offset[0] - scrollOffset[0] &&
            event.clientX + delta < offset[0] -scrollOffset[0] + element.getWidth()  &&
            event.clientY - delta > offset[1] - scrollOffset[1] &&
            event.clientY + delta< offset[1] - scrollOffset[1] + element.getHeight();
}
function getViewPortHeight() {
    var viewportheight;
    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    if (typeof window.innerWidth != 'undefined')  {
        viewportheight = window.innerHeight
    }
    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    else if (typeof document.documentElement != 'undefined'
            && typeof document.documentElement.clientWidth !=
            'undefined' && document.documentElement.clientWidth != 0)  {
        viewportheight = document.documentElement.clientHeight
    }
    // older versions of IE
    else  {
        viewportheight = document.getElementsByTagName('body')[0].clientHeight
    }
    return viewportheight;
}
function hideHeatmapListingInfo(event,element) {
    if(event && isWithin(event,element)) {
    } else {
        element.down(".heatmapPopup").hide();
    }
}

function printPDF() {
    $('printcontext').value = $('container').innerHTML;
    $('printform').submit();
}
function formatStr(newValue, oldValue) {
    //var valueTemplate = /^[+,-]?\d*[\.]?\d*[%]?$/;
    var valueTemplate = /^[+,-]?[\d*[']*\d*]*[\.]?\d*[%]?$/;
    var voidTemplate = /---/;
    if(valueTemplate.test(oldValue)) {
        if(newValue != null && newValue.indexOf(".")==1) {
            newValue += ".00";
        }
        if(oldValue.indexOf(".")>-1) {
            var numOfDigits = oldValue.substring(oldValue.indexOf(".")+1).length;
            if(oldValue.indexOf("%")>-1) numOfDigits -= 1;
            newValue = parseFloat(newValue).toFixed(numOfDigits);
        }
        if(oldValue.indexOf("%")>-1)  newValue += "%";
    }else if(voidTemplate.test(oldValue) && valueTemplate.test(newValue)) {
        newValue = parseFloat(newValue).toFixed(2);
    }
    var sign = '';
    if(newValue.length > 1){
        if(newValue.substring(0,1) == '-' || newValue.substring(0,1) == '+'){
            sign = newValue.substring(0,1);
            newValue = newValue.substring(1,newValue.length);
        }
    }
    if(newValue > 1000){
        newValue = newValue+'';
        var sepNewValue = newValue.split('.');
        sepNewValue[0] = formatBigNumbers(sepNewValue[0]);
        if(sepNewValue.length > 1){
            var sepOld = oldValue.replace(/^\s*|\s*$/g,'').split('.');
            if(sepOld.length > 1){
                if(sepOld[1].length < sepNewValue[1].length){
                    sepNewValue[1] = sepNewValue[1].substring(0,sepOld[1].length);
                }else{
                    var counter = sepOld[1].length - sepNewValue[1].length;
                    for(i = 0; i < counter; i++){
                        sepNewValue[1] += '0';
                    }
                }
            }
            sepNewValue[0] = sepNewValue[0]+'.'+sepNewValue[1];
        }
        newValue = sepNewValue[0];
    }
    newValue = sign+newValue;
    return newValue;
}
function formatBigNumbers(number) {
    number = '' + number;
    if (number.length > 3) {
        var mod = number.length % 3;
        var output = (mod > 0 ? (number.substring(0,mod)) : '');
        for (i=0 ; i < Math.floor(number.length / 3); i++) {
            if ((mod == 0) && (i == 0))
                output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
            else
            // hier wird das Trennzeichen festgelegt mit '.'
                output+= "'" + number.substring(mod + 3 * i, mod + 3 * i + 3);
        }
        return (output);
    }
    else{
        return number;}
}


function generateID() {
    var heute = new Date();
    return heute.getTime();
}
function toggleStyles() {
    $('stylesView').toggle();
    var image = $('stylesViewImg');
    if(image.src.indexOf('plus')>-1) {
        image.src=image.src.replace("plus","minus");
    }else {
        image.src=image.src.replace("minus","plus");
    }
}
var types = new Array("simple","bonds","stocks","warrants","struct");
function display(type){
    $(type+'Options').show();$('modus').value=type;$(type+'Tab').addClassName('active')
    for (var i = 0; i < types.length; i++) {
        if(type != types[i] ){
            $(types[i]+'Tab').removeClassName('active')
            if(types[i] != 'simple'){
                $(types[i]+'Options').hide();
            }
        }
    }
}
//style-management
function styleRename(path,question) {
    var newName = window.prompt(question,"");
    if(newName != null){
        window.location.href = path + "?id=" + $F('style2Edit') + "&newName=" + newName + "&do_pp=no";
    }
}
function styleDelete(path) {
    window.location.href = path + "?id=" + $F('style2Edit') + "&do_pp=no";
}
function selectStyleField(element) {
    $(element).toggleClassName("selected");
}
function moveStyleField(element) {
    var li = $(element).up(0)
    var liInnerHTML = li.innerHTML;
    var liClass = li.className;
    var nextLi;
    if($(element).hasClassName('down')) {
        nextLi = $(element).up(0).next();
    }else{
        nextLi = $(element).up(0).previous();
    }
    li.update(nextLi.innerHTML);
    li.className = nextLi.className;
    nextLi.update(liInnerHTML);
    nextLi.className = liClass;
    adaptOddEven();
    adaptUpDown();
}
function adaptOddEven() {
    $('myStyle').childElements().each(function(el,index) {
        if(index % 2 == 1) {
            if(!$(el).hasClassName('even')) $(el).addClassName('even');
        }else {
            if($(el).hasClassName('even')) $(el).removeClassName('even');
        }
    });
}
function adaptUpDown() {
    var numbOfStyleEl = $('myStyle').childElements().size();
    $('myStyle').childElements().each(function(el,index) {
        if(index==0) el.childElements()[1].hide();el.childElements()[0].show();
        if(index==numbOfStyleEl-1) el.childElements()[0].hide();
        if(index>0 && index < numbOfStyleEl-1) {
            el.childElements()[0].show();
            el.childElements()[1].show();
        }
    });
}

function addStyleFields(select) {
    var numbOfStyleEl = $('myStyle').childElements().size();
    $(select).childElements().each(function(el) {
        if(el.selected) {
            var styleEl = "<li class='";
            if(numbOfStyleEl % 2 == 1) {
                styleEl += "even " + el.value + "'>"
            }else {
                styleEl += el.value + "'>"
            }
            styleEl += el.text + "<img class='down' src='images/arrowDown.gif' alt='down'>";
            styleEl += "<img class='up' src='images/arrowUp.gif' alt='up'></li>";
            $('myStyle').insert(styleEl);
            numbOfStyleEl++;
        }
    });
    adaptOddEven();
    adaptUpDown();
}
function removeStyleFields(element) {
    $(element).childElements().each(function(el) {
        if($(el).hasClassName('selected')) {
            $(el).remove();
        }
    });
    adaptOddEven();
    adaptUpDown();
}
function saveStyle(path,forwardpath) {
    var style = "";
    $('myStyle').childElements().each(function(el) {
        style += el.className.replace("even","").replace(" ","") + ";";
    });
    new Ajax.Request(path, {
        parameters:{id:decodeURIComponent($F('styleid').replace('&#64;','@')),fields:style,do_rd:'no',set:'yes'},
        onSuccess: function(transport) {
            if(forwardpath != 'null'){
                window.location.href = forwardpath+'?style='+$F('styleid').replace('&#64;','@') + '&styleOwner=user';
            }
        }
    });
}
function changeStyle2Edit() {
    window.location.href = "?styleid=" + $F('styleid').replace('&#64;','@') + "&modus=edit";
}
function savePolicyInfos(path) {
    var sitepol = $('sitepolicy').checked;
    var swisscit = $('swisscitizen').checked;
    if(sitepol) window.location.href = path + "?sitepolicy=" + sitepol + "&swisscitizen=" + swisscit + "&modus=" + $F('modus') ;
}
function saveValue(path,saveparams,link){
    var url = path+'?'+saveparams+"&do_rd=no";
    new Ajax.Request( url, {
        method: 'get',
        onSuccess:function() {
            if(link){
                window.location.href = link;
            }
        }
    });

}
function chancePolicyInfos(path,field) {
    var sitepol = $(field).checked;
    if(field == 'sitepolicy') {
        new Ajax.Request(path , {
            parameters:{sitepolicy:sitepol,do_rd:'no'}
        });
    }else {
        new Ajax.Request(path , {
            parameters:{'swisscitizen':sitepol,do_rd:'no'}
        });
    }
}
var imgCount = 0;
function updateChart(){
    imgCount++;
    if($('cimg')) {
        $('cimg').src = $('cimg').src+'&c='+imgCount;
    }
}

function openScreenerPopup(titel){

    if(Windows.getFocusedWindow() != null) {
        Windows.getFocusedWindow().destroy();
    }

    var master = new Window("master", {className: "dialog",
        width:430,
        minWidth:250,
        height:500,
        minHeight:150,
        title:''});

    new Ajax.Updater('myContent','detail/jspf/detailScreenerHelpPopup.jspf',{
        parameters: { part: titel }
    });

    master.setContent($('myContent'));
    master.setDestroyOnClose();
    master.showCenter();

    myObserver = {
        onDestroy: function(eventName, win) {
            if (win == master) {
                $(titel).style.display="none";
                contentWin = null;
                Windows.removeObserver(this);
            }
        }
    }
    Windows.addObserver(myObserver);
}

var MyList = {
    version: '1.0',
    path: 'jspAction/setProfileValues/',
    saveAndDisplayStyle: function(prefix) {
        if(prefix == undefined) {
            prefix = "watchlist";
        }
        var params = prefix + "&" + prefix;

        if(prefix == "watchlist") {
            params  += "&watchliststyle=" + this.getStyle();
            params  += "&watchliststyleowner=" + this.getStyleOwner(prefix);
        }
        else {
            params  += "&portfoliostyle=" + this.getStyle();
            params  += "&portfoliostyleowner=" + this.getStyleOwner(prefix);
        }
        saveValue(this.path,  params, this.getLink(prefix));
    },
    saveAndDisplayList: function(prefix) {
        if(prefix == undefined) prefix = "watchlist";
        if(prefix=="watchlist") params = "watchlistlist=" + this.getList();
        if(prefix=="portfolio") params = "portfolioid=" + this.getList();
        saveValue(this.path, params, this.getLink(prefix));
    },
    saveAndDisplayGrouping: function(prefix) {
        if(prefix=="portfolio") {
            params = "groupPortfolioBy=" + this.getGrouping();
            saveValue(this.path, params, this.getLink());
        }
    },
    getLink: function(prefix) {
        var link = "?list=" + this.getList() + "&style=" + this.getStyle() + "&styleOwner=" + this.getStyleOwner(prefix);
        if(this.getGrouping() != null) {
            link += "&grouping=" + this.getGrouping();
        }
        return link;
    },
    getStyle: function() {
        return $('styleSelector').getValue();
    },
    getList: function() {
        return $('listSelector').getValue();
    },
    getStyleOwner: function(prefix) {
        var userIndex = 5;
        if(prefix == "watchlist") {
            userIndex = 4;
        }
        return $('styleSelector').selectedIndex >= userIndex ? 'user' : 'group';
    },
    getGrouping: function() {
        return ($('groupSelector') != null) ? $('groupSelector').getValue() : null;
    }
};

