 
// footer is closed at first 
var footerOpen = false;

// url get parameter
var get_parameters = getUrlVars(window.location.href);

// tool tip class
var domTT_styleClass = 'domTTOverlib';

// parameter for flash videos
var flashParams = {
  allowScriptAccess: 'always', 
  wmode: 'transparent',
  play: 'false'
};  

// gets called after document loaded
document.observe("dom:loaded", function() 
  {
    // bei Bestellbestätigung die beiden Links ändern
    $$('ul.bemerkung-check-items a').each(function(e)
    {
      e.setAttribute('onclick', 'show_footer(\'agb\'); return false;');
    });

    // wrap textfeldboxes in container for nifty corners to work
    $$('input.textfeldbox').each(function(e) 
      {
        var clone = e.cloneNode(true);
        var div = new Element('div', {'class': 'textfeldboxContainer'});
        e.replace(div);
        div.appendChild(clone);
    });

    if($('SelectSortBez') != null) {
      $('SelectSortBez').remove();
    }

    // if no search results have been found
    if(get_parameters['s'] == 6 && $$('div.OverviewContainer').size() == 0)
    {
      $('center_content').insert({bottom: '<div id="center_image"><div id="no_results_image">&nbsp;</div></div>'});
    }

    var cat_id = get_parameters['cat_id'];
    var bread_nodes = $$('a.Breadcrump');
    // var parent_cat_id = cat_id;

    // if(bread_nodes.length > 2) 
    // {
    //  
    //   var bread_parameter = getUrlVars(bread_nodes[1].readAttribute('href'));
    //   parent_cat_id = bread_parameter['cat_id'];
    // }

    // embedd flash
    swfobject.embedSWF('/flash/header.swf', 'headerVideo', '810', '360', '9.0.0', null, null, flashParams, {id: 'headerVideo'});
    swfobject.embedSWF('/flash/brand_selector.swf', 'brand_selector', '120', '130', '9.0.0', null, null, null, {id: 'brandSelector'});
    swfobject.embedSWF('/flash/category_selector.swf', 'category_selector', '120', '130', '9.0.0', null, null, null, {id: 'categorySelector'});
    // swfobject.embedSWF('/flash/color_selector.swf', 'color_selector', '120', '112', '9.0.0', null, null, flashParams, {id: 'colorSelector'});
    // swfobject.embedSWF('/flash/size_selector.swf', 'size_selector', '120', '130', '9.0.0', null, null, flashParams, {id: 'sizeSelector'});

    // when there are any variants
    if($$('div.OverviewContainer').length > 0) 
    {
      showProductVariants(); 
    }
    
    // if we are on a details page
    if($('flashProductContainer') != null) 
    {
      showProductDetailsPage();
    }

    // nifty corners
    Nifty("div#center_image","normal");
    Nifty("div#productSearchField","normal");
    Nifty("div#produktbeschreibung","normal");
    Nifty("div.OverviewContainer","normal");
    Nifty("div.rollmopsBack","normal");
    Nifty("div.textfeldboxContainer","small");
    Nifty("#boxLoginForm","big");
    Nifty("#bezahlbox","big");
});

document.observe("userhandle:variantChanged", function(event) 
{
  document.body.style.cursor = "wait";

  //show_product_video();
  window.setTimeout(show_product_video, 1500);
  //show_details_variants();
  window.setTimeout(show_details_variants, 1600);
});

function getCategory() 
{
  return get_parameters['cat_id'];
}

// PRODUCT DETAILS PAGE
function showProductDetailsPage() 
{
  document.body.style.cursor = "wait";

  window.setTimeout(selectCorrectVideoID, 1500);
  // window.setTimeout(show_product_video, 2250);
  // window.setTimeout(show_details_variants, 2250);
}

function getFarbSelector() 
{
  var node = null;

  $$('div#AuswahlBoxenAussen select').each(function(e)
    {
      if(e.up().previous().innerHTML == "Farbe:")
      {
        node = e;
      }
    });

  if(node == null)
  {
    $$('div#AuswahlBoxenAussen input').each(function(e)
      {
        if(e.up().previous().innerHTML == "Farbe:")
        {
          node = e;
        }
      });
  }

  return node;
}

function selectCorrectVideoID() 
{
  var getColor = get_parameters['FARBID'];
  var selector = getFarbSelector();

  if(selector != null && selector.onchange != null)
  {
    selector.childElements().each(function(e, i) 
    {
      var optionColor = e.value.replace(/\W/g, '').toUpperCase();
      if(getColor == optionColor) 
      {
        e.selected = true;
        selector.selectedIndex = i;
      }
    });

    selector.onchange();
  } else 
  {
    window.setTimeout(show_product_video, 2250);
    window.setTimeout(show_details_variants, 2250);
  }
}

function resizeFlash() 
{
  $('flashProductView').style.height = '296px';
}

function get_selected_color() 
{
    var selector = getFarbSelector();
    var selectedColor = '';

    if(selector != null)
    {
      return selector.getValue().replace(/\W/g, '').toUpperCase()
    }

    return 'NOCOLOR';
}

function color_is_available(farbID) 
{
  var selector = getFarbSelector();
  var available = false;;

  if(selector != null)
  {
    selector.childElements().each(function(el) 
    { 
      if(el.readAttribute('value').replace(/\W/g, '').toUpperCase() == farbID) 
      { 
        available = true; 
      }
    });
  }

  return available;
}

function selectAndSubmit(farbID)
{
  var selector = getFarbSelector();

  if(selector != null)
  {
    selector.childElements().each(function(e, i) 
    {
      var optionColor = e.value.replace(/\W/g, '').toUpperCase();
      if(farbID == optionColor) 
      {
        e.selected = true;
        selector.selectedIndex = i;
      }
    });

    selector.onchange();
  }
}

// SHOW PRODUCT FLASH VIDEO IN PRODUCT DETAILS VIEW
function show_details_variants() 
{
  $("flashProductVariants").update('');

  var artikelnummer = $('artikelnummer').innerHTML;
  var selectedColor = get_selected_color();

  var added = 0;

  for(var farbID in products[artikelnummer]) 
  {
    if(farbID != selectedColor && color_is_available(farbID))
    {
      added++;
      //var url = get_parameters['FARBID'] == undefined ? window.location.href + '&FARBID=' + farbID : window.location.href.replace(get_parameters['FARBID'], farbID);
      $("flashProductVariants").insert('<div class="VariantsContainer"><div class="OverviewImage">|' +
        '<img onclick="selectAndSubmit(\'' + farbID + '\')" src="/content/' + artikelnummer + "/" + products[artikelnummer][farbID][0] + '_s.jpg" />|</div></div>');
    }
  }

  if(added > 0)
  {
    $("flashProductVariants").insert('<div style="clear: both;"> &nbsp; </div>');
    Nifty("div#flashProductVariants","normal");
  }
}

function show_product_video() 
{
  document.body.style.cursor = "default";

  if ($('artikelnummer')) {

    var artikelnummer = $('artikelnummer').innerHTML;

    // delete every non word character and make it uppercase
    //var selectedColor = $('M2').value.replace(/\W/g, '').toUpperCase();

    var selectedColor = get_selected_color();

    if(products[artikelnummer] && products[artikelnummer][selectedColor]) 
    {
        $("flashProductContainer").update('<div id="flashProductView"> </div>');
        swfobject.embedSWF("flash/produktvideo.swf?video_id=content/" + artikelnummer + "/" + products[artikelnummer][selectedColor][0], "flashProductView", "250", "444", "9.0.0", null, null);        
    } else if (products[artikelnummer]) 
    {

      for(var i in products[artikelnummer]) 
      {
        var height = products[artikelnummer][i][2] + 20;
        
        $("flashProductContainer").update('<div style="margin: 10px; text-align: center;">' +  
          '<img  alt="kein Bild" src="/content/' + artikelnummer + "/" + products[artikelnummer][i][0] + '_l.jpg" />' + 
          'Leider ist für die gewählte Farbvariante des Artikels kein Bild verfügbar. Bitte wähle  ' +
          'eine andere Größe oder eine andere Farbvariante des Artikels mittels der nebenstehenden Größen- und Farbauswahl.</div>');
        $$('div#flashProductContainer img')[0].setOpacity(0.2);
        break;
      }
    } else 
    {
      $("flashProductContainer").update('<div style="margin: 10px;"><img style="margin: 10px" alt="kein Bild" src="/img/keinBild.png" /></div>');
    }

    Nifty("div#flashProductContainer","normal");
  }  
}

function show_product_video_white_overlay() {
}
// END SHOW PRODUCT FLASH VIDEO IN PRODUCT DETAILS VIEW

// END PRODUCT DETAILS PAGE

// FOOTER

function show_footer(site) 
{
    $('footerScrollBarHandle').style.top = "0px";
    $('footerContentText').style.top = "0px";

    if(footerOpen == false) 
    {
        footerOpen = true;

        $('footerContainer').setStyle({ 'background': 'inherit' });
        $('footerContainer').morph('height: 474px;');
        $('footer').morph('background:#000;');

        //$('footerContentText').scrollTop = $('footerContentText').scrollHeight;
        Effect.ScrollTo('bottom', { afterFinish: function() { $('footerContent').appear(); } });

        //scrollDist = Math.round(scroller.scrollAreaH - scroller.scrollH);
        Drag.init($('footerScrollBarHandle'), null, 0, 0, 0, 354);

        $('footerScrollBarHandle').onDrag = function (x, y) 
          {
            var scrollY = parseInt($('footerScrollBarHandle').style.top);
            var docY = 0 - (scrollY * ($('footerContentText').offsetHeight - 360) / 354);
            $('footerContentText').style.top = docY + "px";
          }
    }

    new Ajax.Request('text/' + site + '.html', { method: 'get', onSuccess: function(transport) 
      { 
        $('footerContentText').update(transport.responseText); 
      }});
}

function hide_footer() 
{
    footerOpen = false;
    $('footerContent').hide();
    $('footer').morph('background:#000;');
    $('footerContainer').morph('height: 53px;', { afterFinish: function() { $('footerContainer').setStyle({ 'background': 'url(../img/footer.png) no-repeat' }); } });
    Effect.ScrollTo('bottom', { offset: -1000 });
}

// END FOOTER

function enlarge_header() 
{
  $('header').morph('height: 355px;');
}

function downsize_header() 
{
  $('header').morph('height: 91px;');
}

// PRODUCT VARIANT VIEWER IN PRODUCTS OVERVIEW
function showProductVariants() 
{
  var counter = 0;
  var elements = new Array();
  var height = 0;

  $$('div.OverviewContainer').each(function(e) 
    {
       var artnr = e.getElementsBySelector("div.ArtikelNr")[0].innerHTML;
       if(products[artnr]) 
       {
         for(var i in products[artnr]) 
         {
           var clone = e.cloneNode(true);
           e.insert({before: clone}); 

           var img = clone.getElementsBySelector("img")[0];
           var a = img.up();
           var container = a.up();

           img.writeAttribute("src", "http://rollmops.com/content/" + artnr + "/" + products[artnr][i][0] + "_m.jpg");

           var href = a.readAttribute('href');
           a.writeAttribute("href", href + "&FARBID=" + i);

           if(products[artnr][i][2] > height) 
           {
             height = products[artnr][i][2];
           }

           counter++;
           elements.push(container);

           if(counter % 4 == 0) 
           {
             elements.each(function(element) 
             {
                 element.setStyle({height: (height + 10) + 'px', lineHeight: (height + 10) + 'px'});
               });
             height = 0;
             elements = new Array();
           }
         }
         e.remove();
       } else 
       {
    	   e.remove();
       }
    });
  
  elements.each(function(element) 
  {
    element.setStyle({height: (height + 10) + 'px', lineHeight: (height + 10) + 'px'});
  });
}
// END PRODUCT VARIANT VIEWER IN PRODUCTS OVERVIEW

// COMMON

// read a page's GET URL variables and return them as an associative array.
function getUrlVars(url) 
{
    var vars = [], hash;
    var hashes = url.slice(url.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }

    return vars;
}


