/*
 *  JavaScript
 *  Datum: 12.02.2008
 *  New Release: 07.12.2009
 */
 window.onload = init;
  
 function init(){
  /* Check JavaScript Enabled */
  if($('javascriptAlert')) {$('javascriptAlert').className = 'hidden'};

  if($('activateButton')) {$('activateButton').observe('click',activateUser);}
  if($('deleteMsgButton')) {$('deleteMsgButton').observe('click',deleteMessage);}
  if($$('#catMenu a.pointer')) {
    for(var i=0; i < $$('#catMenu img.pointer').length; i++){
      $$('#catMenu img.pointer')[i].observe('click',editCategories);
    }
  }
  if($('clearForm')) {$('clearForm').observe('click',clearForm);}
  if($('closeFormular')) {$('closeFormular').observe('click',closeFormularNewProduct);}
  if($('closeMessageBox')) {$('closeMessageBox').observe('click',closeMessageBox);}
  if($('closeRecommandBox')) {$('closeRecommandBox').observe('click',closecloseRecommandBox);}

  if($('messageto')) {$('messageto').observe('click',openContactFormular);}  
  if($('suspectProduct')) {$('suspectProduct').observe('click',suspectProduct);}
   
  var inputs = $$('form#newReg input[type=radio]');
  for(var i=0; i < inputs.length; i++){
  inputs[i].observe('click',getLogoLoader);
  } 

  var productLinks = $$('.product, .product *');
  for(var i=0; i < productLinks.length; i++){
    if(!productLinks[i].match('a')){
      productLinks[i].observe('click',openProduct);
    }
  }
  var productLinksWide = $$('.productWide, .productWide *');
  for(var i=0; i < productLinksWide.length; i++){
    if(!(productLinksWide[i].match('a') || productLinksWide[i].match('img.verified'))){
      productLinksWide[i].observe('click',openProductWide);
    }
  }

  var mainCategoryLink = $$('.catMenu li a');
  for(var i=0; i < mainCategoryLink.length; i++){
   mainCategoryLink[i].observe('click',loadingPage);
  }

  if($('navigationBarSearch')) {
  var navigationLinks = $$('div#navigationBarSearch a');
    for(var i=0; i < navigationLinks.length; i++){
      navigationLinks[i].observe('click',getSearchPage);
    } 
  }
   
  if($('openMorePictures')) {$('openMorePictures').observe('click',openMorePictures);}

  if($('simpleSearch')) {$('simpleSearch').observe('click',simpleSearch);}
  if($('advanceSearch')) {$('advanceSearch').observe('click',advanceSearch);}
  if($('companySearch')) {$('companySearch').observe('click',companySearch);}

  /*
  if($$('div.productDetail').length > 0){
   loadProducts.delay(10);
  }
  */
  
  /*
  if(navigator.appName != 'Microsoft Internet Explorer'){
    if($$('div.indexProducts').length > 0){
      window.setInterval('loadProductsIndex()',15000);
    }  
  }
  */
  
  if($('newestProductLeft')) {$('newestProductLeft').observe('click',newestProductLeft);}
  if($('newestProductRight')) {$('newestProductRight').observe('click',newestProductRight);}

  /* Externe Links */
  var outlinks = $$('a[rel=external]');
  for(var i=0; i < outlinks.length; i++){
    outlinks[i].writeAttribute('target','_blank');
  }
  
  /* Administration */
  var setAccountings = $$('table#adminAccounting input[type~=button]');
  for(var i=0; i < setAccountings.length; i++){
    setAccountings[i].observe('click',setAccounting);
  }
}
 
 function activateUser(){
   var userID = $('userID').value;
   var url = '../ajax/setUserActive.php';
   new Ajax.Request(url,
    {
      method:'post',
      parameters: {id: userID},                                                                      
      onSuccess: function(r){ 
        if(r.responseText == 'true'){
          document.location.href = 'index.php';
        } else {
          fail(lng_userActivationFail);
        }
      },
      onFailure: ajaxFail
    });
 }

 function openContactFormular(event){
  $('suspectedProduct').className = 'hidden';
  $('message').className = 'visible';
 }
 function suspectProduct(event){
  $('message').className = 'hidden';      
  $('suspectedProduct').className = 'visible';
 }
 
 function getLogoLoader(event){
  var value = event.element(event).readAttribute('value');
  if(value == 'businessReg' || value == 'business'){
    $('businessOptions').className = 'visible';
  } else {
    $('businessOptions').className = 'hidden';
  }
 }
 
 function ajaxFail(){
   alert(lng_ajaxFail);
 }
 function fail(msg){
   alert(msg); 
 }
 
 function submitFormular(event){
  event.element(event).up('form').submit();
 }
 
/* NEW */
function openProduct(event){
  var obj = event.element(event);
  if(obj.hasClassName('product')){
    var id = obj.readAttribute('id').split('_');
  } else {
    var id = obj.up('.product').readAttribute('id').split('_');  
  }
  document.location.href = 'productdetail.php?pid=' + id[1];
}
function openProductWide(event){
  var obj = event.element(event);
  if(obj.hasClassName('productWide')){
    var id = obj.readAttribute('id').split('_');
  } else {
    var id = obj.up('.productWide').readAttribute('id').split('_');  
  }
  document.location.href = 'productdetail.php?pid=' + id[1];
}

function openMorePictures(){
  if($('morePictures').hasClassName('visible')){
    $('morePictures').className = 'hidden';
    $('openMorePictures').down('img',0).writeAttribute('src','style/gfx/icons/application_cascade.png');
  } else {
    $('morePictures').className = 'visible';
    $('openMorePictures').down('img',0).writeAttribute('src','style/gfx/icons/layers.png');
  }
}
function simpleSearch(event){
  var obj = event.element(event);
  
  var form = new Element('form',{'id':'formSearch','action':'search.php','method':'post'});
  var p = new Element('p');
  var label = new Element('label',{'for':'search'}).update(lng_productSearch);
  var input = new Element('input',{'id':'search','name':'search','type':'text'});
  var inputHide = new Element('input',{'id':'searchMethod','name':'searchMethod','type':'hidden','value':'simple'});
  var submit = new Element('input',{'type':'submit','value':lng_search});
  p.insert({bottom:label});
  p.insert({bottom:input});
  p.insert({bottom:submit});
  p.insert({bottom:inputHide});
  form.insert({bottom:p});
  Element.replace('formSearch',form);
  
  var buttons = $$('div#mainMenueButtons div');  
  for(var i=0; i < buttons.length; i++){
    buttons[i].className = 'inactiveMenue';
  }
  obj.up('div',0).className = 'activeMenue';
  
}
function advanceSearch(event){
  var obj = event.element(event);
  
  var form = new Element('form',{'id':'formSearch','action':'search.php','method':'post'});
  var p = new Element('p');
  var label = new Element('label',{'for':'searchAdvance'}).update(lng_productSearch);
  var input = new Element('input',{'id':'searchAdvance','name':'searchAdvance','type':'text'});
  
  var selectCountry = new Element('select',{'id':'country','name':'country'});
  var selectCat = new Element('select',{'id':'cat','name':'cat'});
  var optionLoad = new Element('option',{'value':''}).update('Loading...');
  var optionLoad2 = new Element('option',{'value':''}).update('Loading...');
  selectCountry.insert({bottom:optionLoad});
  selectCat.insert({bottom:optionLoad2});
  
  var inputHide = new Element('input',{'id':'searchMethod','name':'searchMethod','type':'hidden','value':'advance'});
  var submit = new Element('input',{'type':'submit','value':lng_search});
  p.insert({bottom:label});
  p.insert({bottom:input});
  p.insert({bottom:selectCountry});
  p.insert({bottom:selectCat});
  p.insert({bottom:submit});
  p.insert({bottom:inputHide});
  form.insert({bottom:p});
  Element.replace('formSearch',form);  
  
  var buttons = $$('div#mainMenueButtons div');
  for(var i=0; i < buttons.length; i++){
    buttons[i].className = 'inactiveMenue';
  }
  obj.up('div',0).className = 'activeMenue';
  
  /* Fill the select items with content */
  new Ajax.Request('ajax/getTopCategories.php',
    {
      onSuccess: function(r){
        var xml = r.responseXML;
        var data = xml.getElementsByTagName('data')[0];
        var options = data.getElementsByTagName('option');
        $('cat').down('option',0).update(lng_allCategories);
        for(i=0; i < options.length; i++){
          var option = new Element('option',{'value':options[i].getAttribute('id')}).update(options[i].getAttribute('value'));
          $('cat').insert({bottom:option});
        }    
      },
      onFailure: ajaxFail
    });
  new Ajax.Request('ajax/getCountries.php',
    {
      onSuccess: function(r){
        var xml = r.responseXML;
        var data = xml.getElementsByTagName('data')[0];
        var options = data.getElementsByTagName('option');
        $('country').down('option',0).update(lng_allCountries);
        for(i=0; i < options.length; i++){
          var option = new Element('option',{'value':options[i].getAttribute('id')}).update(options[i].getAttribute('value'));
          $('country').insert({bottom:option});
        }    
      },
      onFailure: ajaxFail
    });
  
  /* ********************************** */
  
}
function companySearch(event){
  var obj = event.element(event);  
  
  var form = new Element('form',{'id':'formSearch','action':'search.php','method':'post'});
  var p = new Element('p');
  var label = new Element('label',{'for':'searchCompany'}).update(lng_companySearch);
  var input = new Element('input',{'id':'searchCompany','name':'searchCompany','type':'text'});
  var inputHide = new Element('input',{'id':'searchMethod','name':'searchMethod','type':'hidden','value':'company'});
  var submit = new Element('input',{'type':'submit','value':lng_search});
  p.insert({bottom:label});
  p.insert({bottom:input});
  p.insert({bottom:submit});
  p.insert({bottom:inputHide});
  form.insert({bottom:p});
  Element.replace('formSearch',form);
  
  var buttons = $$('div#mainMenueButtons div');  
  for(var i=0; i < buttons.length; i++){
    buttons[i].className = 'inactiveMenue';
  }
  obj.up('div',0).className = 'activeMenue';
}

function getSearchPage(event){
  var obj = event.element(event);
  var page = 1;
  if(obj.readAttribute('rel') != ''){
    var page = obj.readAttribute('rel');  
  }
  var action = $('formSearch').readAttribute('action');
  $('formSearch').writeAttribute('action',action + '?page=' + page);
  $('formSearch').submit();
}

function loadProducts(){
  var ownerid = $('productID').value;
  new Ajax.Request('ajax/getProductPreview.php',
    {
      method:'post',
      parameters: {id: ownerid},                                                                      
      onSuccess: function(r){
        var xml = r.responseXML;
        var data = xml.getElementsByTagName('data')[0];
        var products = data.getElementsByTagName('product');
        var pixelToScroll = 0;
        for(i=0; i < products.length; i++){
          var currentLength = $$('div#moreProductPreview div.product').size();
          
          var toClone = $('moreProductPreview').down('div.product',0).cloneNode(true);
          $('moveWindow').insert({bottom:toClone});
          var productID = products[i].getAttribute('id');
          
          var catid = products[i].getAttribute('catid');
          
          var display_name = (text = products[i].getElementsByTagName('display_name')[0].firstChild)? text.data:'';
          var accesslevel = (text = products[i].getElementsByTagName('accesslevel')[0].firstChild)? text.data:'';
          var title = (text = products[i].getElementsByTagName('title')[0].firstChild)? text.data:''; 
          var shortDescription = (text = products[i].getElementsByTagName('shortDescription')[0].firstChild)? text.data:''; 
          var uvp = (text = products[i].getElementsByTagName('uvp')[0].firstChild)? text.data:'0';
          uvp = parseFloat(uvp).toFixed(2); 
          var minPrice = (text = products[i].getElementsByTagName('minPrice')[0].firstChild)? text.data:'0'; 
          minPrice = parseFloat(minPrice).toFixed(2);
          var image = (text = products[i].getElementsByTagName('image')[0].firstChild)? text.data:''; 
          var currency = (text = products[i].getElementsByTagName('currency')[0].firstChild)? text.data:''; 
          var country = (text = products[i].getElementsByTagName('country')[0].firstChild)? text.data:'';
          var online = (text = products[i].getElementsByTagName('online')[0].firstChild)? text.data:'';
          var isVerified = (text = products[i].getElementsByTagName('isVerified')[0].firstChild)? text.data:'';
          /* Daten einfügen und anzeigen */
          var product = $$('div#moreProductPreview .product');
          product[currentLength].writeAttribute('id','pid_' + productID);
          product[currentLength].down('img.productFlag',0).writeAttribute('src','style/gfx/Flags/' + country + '.png');
          product[currentLength].down('div.productImage img',0).writeAttribute('src',image);
          product[currentLength].down('h3',0).update(title);
          product[currentLength].down('p.shortDescription',0).update(shortDescription);
          //product[currentLength].down('span.spanUVP',0).update('UVP ' + currency + ' ' + uvp);
          if($$('div#loginArea form').length == 0){
            product[currentLength].down('span.spanMinPrice',0).update('<b>ab ' + currency + ' ' + minPrice + '</b>');  
          }
          userInformation = '';
          userInformation = '<b>' + display_name + '</b><br />';
          if(online == '1'){
            userInformation += '<img src="style/gfx/icons/user_green.png" alt="" />online';
          } else {
            userInformation += '<img src="style/gfx/icons/user_alpha.png" alt="" />offline';
          }
          if(isVerified == 1){
            userInformation += '| <img class="verified" src="style/gfx/icons/lockSmall.png" alt="" />verified';
          } 
          product[currentLength].down('p.userInformationPreview',0).update(userInformation);
          product[currentLength].observe('click',openProduct);
          var productLinks = product[currentLength].select('*');
          for(var j=0; j < productLinks.length; j++){
            if(!productLinks[j].match('a')){
              productLinks[j].observe('click',openProduct);
            }
          }
          pixelToScroll += 115;
        }
        /* scroll up */ 
        scrollUp(pixelToScroll);
        
        window.setTimeout('loadProducts()',30000);   
      },
      onFailure: ajaxFail
    });
}

function scrollUp(scrollPixel){
  if($('moveWindow').getStyle('top') == null){
    oldPos = 0;
  } else {
    oldPos = $('moveWindow').getStyle('top').gsub('px','');
  }
  if(oldPos > 0 || oldPos == '' || oldPos == null){
    oldPos = 0;
  }
  $('moveWindow').setStyle({
    top: (oldPos-1) + 'px'
  });
  if(scrollPixel >= 0){
    scrollUp.delay(0.05,scrollPixel-1);  
  }
}

function previewImage(event){
  var obj = event.element(event);
  var images = obj.up('div.myAccountImages',0).select('img.myAccountImage');
  for(i=0; i < images.length; i++){
    if(images[i].readAttribute('src').endsWith('uploadImage.jpg')){
      images[i].writeAttribute('src','images/uploadedImage.jpg');
      break;
    }
  }
}

function setAccounting(event){
  var obj = event.element(event);
  var tr = obj.up('tr',0);
  var text = tr.select('[name="text"]')[0].getValue();
  var amount = tr.select('[name="amount"]')[0].getValue();
  var currency = tr.select('[name="currency"]')[0].getValue();
  var state = tr.select('[name="state"]')[0].getValue();
  if(tr.select('[name="user"]').length > 0){
    var user = tr.select('[name="user"]')[0].getValue();
    document.location.href = "accounting.php?user=" + user + "&text=" + text + "&amount=" + amount + "&state=" + state + "&currency=" + currency;  
  } else {
    var id = tr.select('[name="id"]')[0].getValue();
    document.location.href = "accounting.php?id=" + id + "&text=" + text + "&amount=" + amount + "&state=" + state + "&currency=" + currency;  
  }
}

function loadingPage(event){
  var div = $('loadingInfo');
  div.setStyle({
    display: "block"
  });
}

function loadProductsIndex(){
  var cats = $$('div.indexProducts');
  for(var box=0; box < cats.length; box++){
    if(cats[box].down('div.productWide',1)){
      var idArray = cats[box].getAttribute('id').split('_');
    
      var divLoading = new Element('div',{
        className: 'loading'
      });
      divLoading.setStyle({
        height: '230px',
        textAlign: 'center'
      });
      
      var img = new Element('img',{
        src: '/images/loading.gif'
      });
      img.setStyle({
        paddingTop: '100px'
      });
      divLoading.insert(img);
                                         
      cats[box].down('div.productWide',0).addClassName('hidden');
      cats[box].down('div.productWide',1).addClassName('hidden');
      
      cats[box].insert(divLoading);
      
      loadProductOnTopSite(idArray[1],cats[box]);
      
      window.setTimeout('viewResult(' + box + ')',1000);  
    }
  }
}

function viewResult(boxID){
  var cats = $$('div.indexProducts');
  
  cats[boxID].down('div.loading').remove();
  cats[boxID].down('div.productWide',0).removeClassName('hidden');
  cats[boxID].down('div.productWide',1).removeClassName('hidden');
}

function loadProductOnTopSite(catid,divElement){
  new Ajax.Request('ajax/getProductPreviewStartsite.php',
  {
    method:'post',
    parameters: {id: catid},                                                                      
    onSuccess: function(r){
      
      var xml = r.responseXML;
      var data = xml.getElementsByTagName('data')[0];
      var products = data.getElementsByTagName('product');
      var pixelToScroll = 0;
      for(i=0; i < products.length; i++){
        var productID = products[i].getAttribute('id');
        var catid = products[i].getAttribute('catid');
        
        var display_name = (text = products[i].getElementsByTagName('display_name')[0].firstChild)? text.data:'';
        var accesslevel = (text = products[i].getElementsByTagName('accesslevel')[0].firstChild)? text.data:'';
        var title = (text = products[i].getElementsByTagName('title')[0].firstChild)? text.data:''; 
        var shortDescription = (text = products[i].getElementsByTagName('shortDescription')[0].firstChild)? text.data:''; 
        var minPrice = (text = products[i].getElementsByTagName('minPrice')[0].firstChild)? text.data:'0'; 
        minPrice = parseFloat(minPrice).toFixed(2);
        var image = (text = products[i].getElementsByTagName('image')[0].firstChild)? text.data:''; 
        var currency = (text = products[i].getElementsByTagName('currency')[0].firstChild)? text.data:''; 
        var country = (text = products[i].getElementsByTagName('country')[0].firstChild)? text.data:'';
        var online = (text = products[i].getElementsByTagName('online')[0].firstChild)? text.data:'';
        var isVerified = (text = products[i].getElementsByTagName('isVerified')[0].firstChild)? text.data:'';
        /* Daten einfügen und anzeigen */
        var product = divElement.down('div.productWide',i);
        product.writeAttribute('id','pid_' + productID);
        product.down('img.productFlag',0).writeAttribute('src','style/gfx/Flags/' + country + '.png');
        product.down('div.productImage img',0).writeAttribute('src',image);
        product.down('h3',0).update(title);
        product.down('p.shortDescription',0).update(shortDescription);
        //product[currentLength].down('span.spanUVP',0).update('UVP ' + currency + ' ' + uvp);
        if($$('div#loginArea form').length == 0){
          product[currentLength].down('span.spanMinPrice',0).update('<b>ab ' + currency + ' ' + minPrice + '</b>');  
        }
        userInformation = '';
        userInformation = '<b>' + display_name + '</b><br />';
        if(online == '1'){
          userInformation += '<img src="style/gfx/icons/user_green.png" alt="" />online';
        } else {
          userInformation += '<img src="style/gfx/icons/user_alpha.png" alt="" />offline';
        }
        if(isVerified == 1){
          userInformation += '| <img class="verified" src="style/gfx/icons/lockSmall.png" alt="" />verified';
        } 
        product.down('p.userInformationPreview',0).update(userInformation);
        product.observe('click',openProduct);
        var productLinks = product.select('*');
        for(var j=0; j < productLinks.length; j++){
          if(!productLinks[j].match('a')){
            productLinks[j].observe('click',openProduct);
          }
        }
      }
      
      return true;
    },
    onFailure: reloadStartSite
  });
}

function reloadStartSite(){
  document.location.href = '/index.php';
}

function newestProductLeft(event){
  var leftPositionText = $('newestProducts').down('div',0).getStyle('left');
  var leftPosition = parseInt(leftPositionText.substr(0,leftPositionText.length-2));
  if(leftPosition < 0){
    $('newestProducts').down('div',0).setStyle({
      left: (leftPosition+345) + 'px'
    });
  }
}
function newestProductRight(event){
  var leftPositionText = $('newestProducts').down('div',0).getStyle('left');
  var leftPosition = parseInt(leftPositionText.substr(0,leftPositionText.length-2));
  if(leftPosition > -1665){
    $('newestProducts').down('div',0).setStyle({
      left: (leftPosition-345) + 'px'
    });
  }
}