var click_params = "";
var fields = new Hash();
var layout_calc = new Array();

var control_info = new Element('div',{'class':'control_info frame'});

/*document.body.observe('load',function(e){
    
})*/

var scale = function(rahmen,xscale,yscale,parent) {

    var e = $(rahmen);
    var w = e.getWidth();
    var h = e.getHeight();    
    e.setStyle({"width":w*xscale});
    e.setStyle({"height":h*yscale});
    if(parent) e.up('div').setStyle({"width":w*xscale});
}

var scale_to_target = function(rahmen, xsize, ysize)
{
    var e = $(rahmen);
    var d = e.getDimensions();
    var sf;
    if(d.width>0) {
    alert(d.width);
    if(d.height>d.width) {
        sf = ysize/d.height;
    } else {
        sf = xsize/d.width;
    }
    alert('SF:'+sf);
    e.setStyle({"width":(d.width*sf)});
    e.setStyle({"height":(d.height*sf)});
    }
}

var ReCalcLayout = function() {    
    layout_calc.each(function(item) {       
        switch(item.T) {
            case 'Y':_FrameMoveY(item.C,item.P,item.D,true);break;
            case 'X':_FrameMoveX(item.C,item.P,item.D);break;
            case 'R':_Resize(item.C);break;
        }
    });
}

var _ReCalcLayout = function() {
    layout_calc.each(function(item) {
        switch(item.T) {
            case 'Y':_FrameMoveY(item.C,item.P,item.D,false);break;
            case 'X':_FrameMoveX(item.C,item.P,item.D);break;
            case 'R':_Resize(item.C);break;
        }
    });
}

var _FrameMoveY = function(child,parent,distance,shrink) {
    if(($('L'+parent) != null)&&($('L'+child))) {
        if($('L'+parent).visible()) {
            dist = parseInt($('L' + parent).style.top) + parseInt($('L'+parent).getHeight()) + parseInt(distance);
            if(!shrink) {
                if(parseInt($('L'+child).style.top)<dist)
                    $('L'+child).style.top = dist;
                    _Resize('L' + child);
            } else {
                $('L'+child).style.top = dist;
            }
        }
    }
}

var FrameMoveY = function(child, parent, distance) {
    layout_calc[layout_calc.size()] = {'T':'Y','C':child,'P':parent,'D':distance};
    _FrameMoveY(child,parent,distance,false);
}

var _FrameMoveX = function(child, parent, distance) {
    if(($('L'+parent) != null)&&($('L'+child))) {
        dist = parseInt($('L' + parent).style.left) + parseInt($('L'+parent).getWidth()) + parseInt(distance);
        if(parseInt($('L'+child).style.left)<dist) $('L'+child).style.left = dist;
    }
}

var FrameMoveX = function(child, parent, distance) {
    layout_calc[layout_calc.size()] = {'T':'X','C':child,'P':parent,'D':distance};
    _FrameMoveX(child,parent,distance);
}

var _Resize = function(rahmen) {
    var frame = $(rahmen);
	if(frame==null) frame = $('L'+rahmen);
	if(frame!=null) {
    var parent = frame.getOffsetParent();
    if(parent!=null) {
        var pdimension = parent.getDimensions();
        var dimensions = frame.getDimensions();
        if(frame.visible()&&(parent.style.overflow!="scroll")&&(parent.style.overflow!="auto")) {
            if(pdimension.height<dimensions.height+parseInt(frame.style.top)) {
                parent.setStyle({'height':(dimensions.height+parseInt(frame.style.top))});                
            }
            if(pdimension.width<dimensions.width+parseInt(frame.style.left)) parent.setStyle({'width':(dimensions.width+parseInt(frame.style.left))});
        }
    }
	}
    /*
     *

    var parent = $('L'+rahmen);
    var height = parent.getHeight();
    var width = parent.getWidth();
    var frame = parent;    
    if(parent.down()!=null) {
        if(parent.down().id.startsWith('F')) {
            frame = $('C'+rahmen).up();
        }
    }
    frame.immediateDescendants().each(function(item) {
        if(item.visible()) {
        //Resize(item);
            h = parseInt(item.positionedOffset().top)+item.getHeight();
            w = parseInt(item.positionedOffset().left)+item.getWidth();
            if(height<h) height = h;
            if(width<w) width = w;
        }
    });
    if((width>0)&&(height>0)) {
        parent.setStyle({'width':width});
        parent.setStyle({'height':height});
    }
    */
}

var Resize = function(rahmen) {
    if($('C'+rahmen)!=null) {
        layout_calc[layout_calc.size()] = {'T':'R','C':'C'+rahmen,'P':0,'D':0};
        _Resize('C' + rahmen);
    }
    if($('SC'+rahmen)!=null) {
        layout_calc[layout_calc.size()] = {'T':'R','C':'SC'+rahmen,'P':0,'D':0};
        _Resize('SC' + rahmen);
    }
    if($('L'+rahmen)!=null) {
        layout_calc[layout_calc.size()] = {'T':'R','C':'L'+rahmen,'P':0,'D':0};
        _Resize('L' + rahmen);
    }
}
function Produktlink(productid)
{
  if(click_params=="") {click_params="?";} else {click_params+="&";} 
  click_params += "pid="+productid;
  window.location.href = click_params;
}

function OpenWin(productid, width, height) {
  window.open("index.php?pid="+productid,"Info","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width="+width+",height="+height+"");
}

function OpenWinLink(link) {
  window.open(link,"Info","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,width=700,height=700");
}

var SetParam = function(form, param, value)
{    
    var f = $(form);
    f.down('form').getElements().each(function (i) {
       if(i.name==param) i.setValue(value);
    });
}

var updateControl = function(form,sendfields)
{
    var f = $(form);
    if(tooltip_window!=null) stopTooltip(tooltip_window);
    if(! f.hasClassName('update_ctrl')) {
        var params = f.down('form').serialize();
        params = params + '&sendfields=' + sendfields;
        f.addClassName('update_ctrl');
        f.update('<div style=\"width:100%; height:100%; ></div>');
        new Ajax.Updater(f,'control.php', {
            evalScripts: true,
            parameters: params,
            onSuccess: function(r) {
                f.removeClassName('update_ctrl');
                _ReCalcLayout();
                //ReCalcLayout();
                //f.update(r.responseText);
                /*
                if(sendfields) {
                    fields.get(form).keys().each(function (field) {
                        fields.each(function (fo) {
                            if(fo.key != form) {
                                fo.value.each(function(fi) {
                                    if(fi.key==field) {
                                        updateControl(fi.value,false);
                                    }
                                });
                            }
                        });
                    });
                }
                */
            }
        });
    }
}

var changedField = function(form, field)
{
    fields.each(function (fo) {
       if(fo.key != form) {
           fo.value.each(function(fi) {
              if(fi.key==field)  {
                  updateControl(fi.value,"1");
              }
           });
       }
    });
}

var registerField = function(formname, field)
{    
    var a = fields.get(formname);
    if(a==null) {
        a = new Hash();
    }
    a.set(field,formname);
    fields.set(formname,a);    
}

var toggleClassnames = function(elem,old_classname,new_classname)
{    
    if($(elem).hasClassName(old_classname)) {
        $(elem).removeClassName(old_classname);
        $(elem).addClassName(new_classname);
    }
	var d = Element.descendants(elem);
	d.each(function(item) {
		if(item.hasClassName(old_classname)) {
			item.removeClassName(old_classname);
			item.addClassName(new_classname);
		} else {
			if(item.hasClassName('L'+old_classname+old_classname+old_classname)) {
	            item.removeClassName('L'+old_classname+old_classname+old_classname);
	            item.addClassName('L'+new_classname+new_classname+new_classname);
			}
		}
	});
}

var SetCheckboxes = function(layername,value)
{
    var formname = layername.down('form');
    for (j=0;j<formname.elements.length;j++){
        e=formname.elements[j];
        if(e.type=="checkbox"){
            if(e.checked!=value) {
                $(e).click();
            }
        }
    }
}

function JaNein(sprachetext) {
   Check = confirm(sprachetext);
   if(Check == false){
      Laden = false;
      return false;
   } else {
      return true;
   }
}

var PopOn = function(rahmen) {
    var element = $('L'+rahmen);
    if(element!=null) {
        element.show();
        //setZIndex(element);
    }
    //ReCalcLayout();
}

var PopOff = function(rahmen) {
    var element = $('L'+rahmen);
    if(element!=null) {
        element.hide();
    }
    //ReCalcLayout();
}

var sendValue = function(element,key) {    
    $(element).addClassName('update');
    new Ajax.Request('updateKey.php', {
        parameters: {'prodakey': key,
                      'keyvalue': element.value
                    },
        onSuccess: function(r) {
            element.removeClassName('update');
            element.value = r.responseText.evalJSON(true);
            element.addClassName('saved');
            setTimeout(function() {
                element.removeClassName('saved');
            }, 500, null, null)
        },
        onFailure: function(r) {
            element.removeClassName('update');
            element.setStyle({"background":"url('sys/img/exclamation.png') no-repeat center right"});
        }

    });
}

var sendForm = function(element) {
    $(element).select('input').each(function(i) {
       if( i.hasClassName('mark')) {
           i.removeClassName('mark');
           sendValue(i,i.readAttribute('pk'));
       }
    });
    $(element).select('textarea').each(function(i) {
       if( i.hasClassName('mark')) {
           i.removeClassName('mark');
           sendValue(i,i.readAttribute('pk'));
       }
    });
}

var scrollToElement = function(form,element) {
    
    if(( $(form) != null ) && ($(element) != null)) {
        $(form).scrollTop = parseInt($(element).positionedOffset().top)-(parseInt($(form).getHeight())/2);
    }
    
}

var scrollToElementLeft = function(form,element) {
    
    if(( $(form) != null ) && ($(element) != null)) {
        $(form).scrollLeft = parseInt($(element).positionedOffset().left)-(parseInt($(form).getWidth())/2);
    }
    
}

var showControlInfo = function(form, info) {    
    document.body.appendChild(control_info);
    control_info.clonePosition($(form), {
       'offsetLeft': $(form).getWidth(),
       'setWidth':false,
       'setHeight':false
    });
    control_info.show();
    control_info.update(info);
}

var hideControlInfo = function() {
    control_info.hide();
}

var hideCheckboxesinRow = function(layername,value,row,anzahl) {
    var i;
    if(value==true) {
        for(i=2;i<=anzahl+1;i++) {
            $(layername).down('tr',row).down('input',i).show();
        }
    } else {
        for(i=2;i<=anzahl+1;i++) {
            $(layername).down('tr',row).down('input',i).hide();
            $(layername).down('tr',row).down('input',i).checked=false;
        }
    }  
}

var SetRightCheckboxes = function(value)
{
    $$('.rightoverwrite').each( function(item) {
        if(item.checked!=value) {
            item.click();
        }
    });
}

var setZIndex = function(target)
{
   $$('div').each(function(f) {       
       f.setStyle({'zIndex':1});
   });
   if(target!=null) {
       $(target).setStyle({'zIndex':255});
       $(target).select('div').each(function(fra) {
          fra.setStyle({'zIndex':1000});
       });
   }
}

function Externerlink(link)
{
  window.location.href = link;
}

var ticks = 101;
var tooltip_url;
var tooltip_window;
var tooltip_openevent;

var showTooltip = function(tw,param,event)
{
    tooltip_url = param;
    tooltip_window = $(tw);
    tooltip_openevent = event;
    ticks = 0;
}

var stopTooltip = function(tw)
{    
    if($(tw)==tooltip_window) {
        tooltip_window.hide();
        ticks = 51;
    } else {
        $(tw).hide();
        //stopObserving('click');
    }
}

var startTooltipTicker = function()
{
    ticks=ticks+1;
    if (ticks==50) {
        getTooltip(tooltip_window,tooltip_url);
    }
    if (ticks>51) ticks=51;
    setTimeout('startTooltipTicker()',10);
}

startTooltipTicker();

var initTooltip = function(tw)
{
    document.observe('mousemove',function(e) {
        $(tw).setStyle({'top':e.clientY+5+document.viewport.getScrollOffsets()['top'], 'left':e.clientX+5+document.viewport.getScrollOffsets()['left']});
    });    
}

var getTooltip = function(tw,param)
{
    
    document.observe('click', function(e){
        stopTooltip(tw);
        return true;
    });

    tw.show();        
    //tw.setStyle({'right':document.viewport.getWidth(),'bottom':document.viewport.getHeight()});
    $(tw).update('<img src="sys/img/copy_wait.gif">');
    $(tw).setStyle({zIndex:10006});
    new Ajax.Updater(tw,param);
}

var startUpload = function(target,layer)
{
    f = $(target);
    l = $(layer);

    l.select('div').each(function (i) {
       i.setStyle({'display':'none'});
    });
    oldcontent = f.innerHTML;
    l.addClassName('upload_ctrl');
    $('upload_target').observe('load',function(e) {              
       l.removeClassName('upload_ctrl');
       //f.update('importieren');
       $('upload_target').stopObserving('load');       
       //f.innerHTML = oldcontent;
        
        if(! l.hasClassName('update_ctrl')) {
            var params = l.down('form').serialize();
            //params = params + '&sendfields=' + sendfields;
            l.addClassName('update_ctrl');
            l.update('<div style=\"width:100%; height:100%; ></div>');
            new Ajax.Updater(l,'control.php', {
                evalScripts: true,
                parameters: params,
                onSuccess: function(r) {
                    l.removeClassName('update_ctrl');                    
                }
            });
        }               
   });
}

var showMessage = function(msgdiv) {

    container = document.body.appendChild(new Element('div',{'class':'transparent', 'style':'position:absolute; top:0px; left:0px; width:100%; height:100%; background-color:#333;z-index:10005'}));    
    msg_container = document.body.appendChild(new Element('div',{'style':'position:absolute; top:50%; left:50%; z-index:10006; '})).appendChild(new Element('div',{'style':'padding:5px; left:-300px;top:-200px; width:600px; height:400px;border:1px solid black;background-color:#fff;z-index:10006'}));
    //if(($(msgdiv))!=null) {
        msg_container.update(msgdiv);
    //}
    msg_container.observe('click', function(e) {
       
       container.remove();
       msg_container.remove();
       
    });
}

var sendBasketValue = function(conti, feld, index) {
     
    new Ajax.Request('prepareBasket.php', {
        parameters: {
                     'bpid': feld[index],
                     'max': feld.length,
                     'akt': index+1
                    },    
        onSuccess: function(r) {
            conti.update(r.responseText);
            if(feld.length > index+1) {
               sendBasketValue(conti, feld, index+1);
            } else {
               if(feld.length == index+1) sendBasketValue(conti, feld, index+1);
            }   
        },
        onFailure: function(r) {
            conti.update('<img src="sys/img/exclamation.png">Error');
        }
    });
}

var prepareBasket = function(element) {
    feld = Array();
    $(element).select('input').each(function(i) {    
        feld.push(i.value);
    });
    
    container = document.body.appendChild(new Element('div',{'class':'transparent', 'style':'position:absolute; top:0px; left:0px; width:100%; height:100%; background-color:#333;z-index:10005', 'id':'IDX0'}));    
    msg_container = document.body.appendChild(new Element('div',{'style':'position:absolute; top:50%; left:50%; z-index:10006;', 'id':'IDX1'})).appendChild(new Element('div',{'style':'padding:5px; left:-300px;top:-200px; width:600px; height:150px;border:1px solid black;background-color:#fff;z-index:10006'}));                
    
    msg_container.update('<img src="sys/img/copy_wait.gif">');

    sendBasketValue(msg_container,feld,0);
    
    msg_container.observe('click', function(e) {  
       container.remove();     
       msg_container.remove();       
    }); 

}

function Sprachauswahl(languageid,productid)
{
  if(click_params=="") {click_params="?";} else {click_params+="&";}
  if (document.getElementById) {
    click_params += "pid="+productid+"&languageid="+languageid;
  } else {
    click_params += "pid="+productid+"&languageid="+languageid;return;
  }
  document.location.href= "index.php" + click_params;
}

function Waehrungsauswahl(waehrungid,productid)
{
  if(click_params=="") {click_params="?";} else {click_params+="&";}
  if (document.getElementById) {
    click_params += "pid="+productid+"&currencyid="+waehrungid;
  } else {
    click_params += "pid="+productid+"&currencyid="+waehrungid;return;
  }
}

var LogOut = function() {
    document.location.href="index.php?reset=1";
}

function Bestellen(productid)
{
	document.location.href="index.php?productid=" + productid + "&action=9";

}
