/**
 * Created on 16.06.2009
 *
 * $Id: garpa_functions.js 21 2009-06-24 11:18:58Z cschaefer $
 * $Rev: 21 $
 * $Date: 2009-06-24 13:18:58 +0200 (Mi, 24. Jun 2009) $
 * $Author: cschaefer $
 * (c) trigonon GmbH
 * @author: cschaefer
 */

/** Helper **/
function insertFormInputHiddenField(form, name, value) {
  var elem;

  elem = document.createElement("input");
  elem.type = 'hidden';
  elem.name = name;
  elem.value = value;
  form.appendChild(elem);

  return elem;
}

function getWinSize(win) {
  if (!win)
    win = window;
  var s = new Object();
  if (typeof win.innerWidth != 'undefined') {
    s.width = win.innerWidth;
    s.height = win.innerHeight;
  } else {
    var obj = document.body; 
    s.width = parseInt(obj.clientWidth);
    s.height = parseInt(obj.clientHeight);
  }
  return s;
}

function getDocHeight() {
  var D = document;
  return Math.max(
      Math.max(D.body.scrollHeight, D.documentElement.scrollHeight), Math.max(
          D.body.offsetHeight, D.documentElement.offsetHeight), Math.max(
          D.body.clientHeight, D.documentElement.clientHeight));
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;

  if (typeof (window.pageYOffset) == 'number') {
    // Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if (document.body
      && (document.body.scrollLeft || document.body.scrollTop)) {
    // DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if (document.documentElement
      && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
    // IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function disableEnterKey(e) {
  var key;
  if(window.event)
    key = window.event.keyCode; //IE
  else
   key = e.which; //firefox
   return (key != 13);
}

function addHiddenField($form, elemName, elemVal) {
   s = '<input type="hidden" name="'+ encodeURIComponent(elemName)
       + '" value="'+ encodeURIComponent(elemVal)
       + '" />';
   $(s).appendTo($form);
}

function selectChangeByFormID(parameterstring, formID) {
  form = $("#" + formID);
  addHiddenField(form,parameterstring, 'XXX');
  form.submit();
  return false;
}

function selectChange(parameterstring, form) {
  insertFormInputHiddenField(form, parameterstring, 'XXX');
  form.submit();
}

function submitAndDisable(submitName, button) {
  selectChange(submitName, button.form);
  button.disabled = true;
  return false;
}

/**
* handler
**/

$(document).ready(function() {
  addToMultiHandler();    // Hinweise beim Hinzufuegen  von Artikeln in den Warenkorb/Merkzettel
  matrixPreviewHandler(); // Vorschau der Muster- und der Produktbilder in der Matix
  informationSliderHandler();     // Garten-Kollektion
  imageGalleryHandler();     // Gartenmöbel
  imagePreviewHandler();       // Stühle
  enterFormSubmit();
  disableEnterKeyHandler();
});

function disableEnterKeyHandler() {
  $("input.amount").keypress(function(e) {
    return disableEnterKey(e);
  });
}

/**
* gardenfurniture
**/

function imageGalleryHandler() {
  $gallery = $("#imggal_garden_furniture");
  var cnt = 1;
  var amount = parseInt($("#amountImage").text());
  replaceImage($gallery, cnt);

  $("a#switch_previous_image").click(function(){
    if(cnt == 1) {
      cnt = (amount +1);
    }
    replaceImage($gallery, --cnt);
    return false;
  });
  $("a#switch_next_image").click(function(){
    if(cnt == amount)
      cnt = 0;
    replaceImage($gallery, ++cnt);
    return false;
  });
}

function replaceImage($gallery, cnt) {
  if(cnt > 0) {
  //  $image = $("li#image_" + cnt + " .imageHtml").clone();
     // Slogan erzeugen
    $imageTitel = $("li#image_" + cnt + " .imageHtml .bildtitel").text();
    $imageURL   = $("li#image_" + cnt + " .imageHtml .bildurl").text();
    $image = '<img src="'+$imageURL+'" alt="'+$imageTitel+'" style="display: none;" title="'+$imageTitel+'" />';

    if(navigator.userAgent.indexOf('MSIE 7')>0)  {
      $(".image a#switch_next_image").css("margin","0 5px");  // sonst verschiebt sich das Bild im IE7 :(
      $(".image a#switch_previous_image").css("marginRight","-5px");  // sonst verschiebt sich das Bild im IE7 :(
     }
    
       // Evtl. Link um das Bild
    $linkText = $("li#image_" + cnt + " .imageHtml .linktext").text();
    if($linkText != '') {
      $linkURL = $("li#image_" + cnt + " .imageHtml .linkurl").text();
      $image = '<a href="'+$linkURL+'" title="'+$linkText+'">'+ $image +'</a>';
    }
    $image = '<div class="imageHtml">'+$image+'</div>';

     // Slogan erzeugen
    $slogantitel = $("li#image_" + cnt + " .product_slogan .slogantitel").text();
    $sloganURL   = $("li#image_" + cnt + " .product_slogan .sloganurl").text();
    if($sloganURL == '') 
     $sloganURL = "images/slogan_blank.jpg";
    $imageSlogan = '<div class="product_slogan"><img src="'+$sloganURL+'" alt="'+$slogantitel+'" style="display: none; margin-left: -56px;" title="'+$slogantitel+'" /></div>';

    $hoverBoxen = $("li#image_" + cnt + " .hover");
    $imageText = $("li#image_" + cnt + " .imagetext").text();
    $categoryLink = $("li#image_" + cnt + " .nextCategoryLink a");

      // Bild austauschen
    $(".doublecol .imageHtml").remove();
    $(".doublecol").prepend($image).find("img").fadeIn(1500);
      // Sloganbild austauschen
      
      $(".triplecol").html($imageSlogan).find("img").fadeIn(1500);
      // Beschreibung austauschen
    $("#link_next .imagetext").text($imageText);
      // Beschreibungslink austauschen
    $("#link_next").attr({
                         href: $categoryLink.attr("href"),
                         title: $categoryLink.attr("title"),
                         alt: $categoryLink.attr("title")
                         });
    $("#link_next .semi_grey img").attr({
                         title: $categoryLink.attr("title"),
                         alt: $categoryLink.attr("title")
                         });

      // Hover Infotexte austauschen
    $(".doublecol .effectbar").each(function(cnt) {
      $hoverBox = $hoverBoxen.eq(cnt);
      if($(".infoText", $hoverBox).text() != '') {
        $(".flow", this).html($(".hoverbox", $hoverBox).html());
        $(".grey", this).text($(".infoText", $hoverBox).text());
        setTimeout("showHoverBox("+cnt+")", 1250);
      }else {
        $(this).addClass("hidden");
      }
    });


      // Zähler hochzählen
    $("#currentImage").text(cnt);
  }
}

function showHoverBox(cnt) {
 $(".doublecol .effectbar").eq(cnt).removeClass("hidden");
}

/**
 *  cart
 */

function enterFormSubmit() {
  $(".middle_column_no_padding .editfield").keypress(function(e){
    if(e.keyCode==13){
      $id = $(this).attr("id");
      refNr = $id.substr(($id.length-4), $id.length);
      addHiddenField($("#table_overflow_container form:first"), "action_5_"+refNr, "Übernehmen");
      $("#table_overflow_container form:first").submit();
      return false;
    }
  });
}

var $action = $(document).getUrlParam("action");

//  Produkt hinzufügen zum Merkzettel/Warenkorb
function addToMultiHandler() {
  // ($action == 29 || $action == 32) &&

 // if(refNr != null && refNr.length >= 0) {
    if((typeof productsToCartArr != "undefined" || typeof productsToNotepadArr != "undefined")) {

      refNr = $(document).getUrlParam("referenceno");
      arrOfProducts = (typeof productsToCartArr != "undefined") ? productsToCartArr: productsToNotepadArr;

      color = "#707173";
      cnt = 1;
      $sideNr = (typeof $("#sideNr").attr("value") != "undefined") ? $("#sideNr").attr("value") : null;
      $isSonderlayout = ($("input[name='sonderlayout']").val() == "sonderlayout") ? true: false;
      $isShoppingCart = ($("input[name='shoppingcartpage']").val() == "shoppingcart") ? true: false;
      $reflist = ($("input[name='reflist']").val() != '') ? true: false;
      $cushionReflist = ($("input[name='cushionRefList']").val() != '') ? true: false;

      if(!$isShoppingCart) {
        arrCnt = 1;
        $.each(arrOfProducts, function(id, value) {
          if($isSonderlayout) {
            if(arrCnt%2 != 0 ) { // zahl ungerade => Produkt
             $productText =  $("#pageheadline h1").text().toUpperCase() + " (" + $("#name_"+id).text() + ")";
             $productImage =$("#name_"+id).parents().parents().find("img").attr("src");
            }else if($cushionReflist) { // zahl gerade && cusionList => Auflage
              $typ = $("#product_view_accessory_"+ id).parent().find("h1").text();
              $productText =  $typ + ' ' + $("#product_view_accessory_"+ id).find("h2").text();
              $productImage = $("#product_view_accessory_"+ id).find("img").attr("src");
            }else{
              $productText =  $("#pageheadline h1").text().toUpperCase() + " (" + $("#name_"+id).text() + ")";
              $productImage =$("#name_"+id).parents().parents().find("img").attr("src");
            }
          }else if($sideNr == 1 && $reflist) {
            if(arrCnt == 1) {
              $productText = $("#pageheadline h1").text() + ' ' + $("#pageheadline div:first").text();
              $productImage = null;
            }else{
              $productText = $("#product_view_accessory_"+ id).find("h2").text();
              $productImage = $("#product_view_accessory_"+ id).find("img").attr("src");
            }
          }else if($action == 1 || $action == 2) {
            $productText = $("#product_"+ refNr).find("h2").text();
            $productText = ($productText.length == 0) ? "Ref. " + refNr: $productText;
            $productImage = null;
          }else if($action == 9 || $action == 10) {
            $productText = $("#pageheadline h1").text() + ' ' + $("#pageheadline div:first").text();
            $productImage = null;
          }else if($sideNr == 5 || $sideNr == 6) {
            $productText = $(".productInfo").find("h2").text();
            $productImage = $(".productInfo").find("img").attr("src");
          }else {
            $productText = $("#product_view_accessory_"+ id).find("h2").text();
            $productImage = $("#product_view_accessory_"+ id).find("img").attr("src");
          }

          msg = value.replace("#ARTIKEL#", $productText);
          showHint(msg, color, $productImage, $sideNr, $isSonderlayout);
          arrCnt++;
        }); // close each
      }
    }
 // }
} // addToMultiHandler

function showHint($msg, $color, $image, $sideNr, $isSonderlayout) {
  $.jGrowl($msg, {
      life: 10000,
      beforeOpen: function(e,m) {
      if($sideNr == 3 || $sideNr == 5 || $isSonderlayout || ($image != null)) {
        $("div.jGrowl-notification", this).eq(cnt).css("background-image", "url("+$image+")");

      }
      cnt++;
     // $("div.message", this).css("background-color", $color);
     }
  });
}

/**
* chairs
**/

var inProgress = false;
function imagePreviewHandler() {

  $(".product_thumb").hover(function(){
    if(inProgress == false) {
      inProgress = true;
      var productInfo = $(".product_preview_info", this);
      var productPreview = $("#product_preview,#product_preview_portrait,#product_preview_first_row,#product_preview_portrait_first_row");
      var producttitel = $("a img", this).attr("title");
     // var imgSrc = "url(" + $(".product_image", productInfo).text() + ")";
     // productPreview.css("background-image", imgSrc);

     changePreview(productInfo, productPreview, producttitel);
    }
  });
}

function changePreview(productInfo, productPreview, producttitel) {
  $(".backgrd_image", productPreview).attr({
                                            title: producttitel,
                                            alt:producttitel,
                                            src: $(".product_image", productInfo).text()
                                          });
 // var imageWidht = $(".backgrd_image", productPreview).width();
 // $(".overlay", productPreview).css("width", (parseInt(imageWidht) + 12));
  $("h2", productPreview).text($(".overlay_text", productInfo).text());
  inProgress = false;
}

// Alternative zu changePreview
function fadePreview(productInfo, productPreview, producttitel) {
  $(".backgrd_image", productPreview).fadeOut(200, function(){
      $(this).attr({title: producttitel, alt:producttitel});
      $(this).attr("src", $(".product_image", productInfo).text()).fadeIn(200, function(){
      var imageWidht = $(".backgrd_image", productPreview).width();
     //  var imageHeight = $(".backgrd_image", productPreview).height();
     //  $(productPreview).height(imageHeight);
      $(".overlay", productPreview).css("width", (parseInt(imageWidht) + 12));
      $("h2", productPreview).text($(".overlay_text", productInfo).text());
    });
     inProgress = false;
  });
}

/**
* dynamic_product_preview
**/

function matrixPreviewHandler() {
  $("tr td.third_column a").hover(function(){
    $row = $(this).parent().parent();
    if($row.hasClass("serialView")) {
      imageName = $(this).attr("id") + ".jpg";
      imagePath = "../shopimages/serial/";
    }else if($row.hasClass("dessinView")) {
      imageName = $(this).attr("class") + ".jpg";
      imagePath = "../shopimages/product/cushion/105x100/";
    }else if($row.hasClass("productView")) {
      imageName = $(this).attr("class") + ".jpg";
      imagePath = "../shopimages/product/matrix/";
    }else if($row.hasClass("parasolView")) {
      imageName = $(this).attr("id") + ".jpg";
      imagePath = "../shopimages/matrix/parasol/product/";
    }else if($row.hasClass("tableView")) {
      imageName = $(this).attr("id") + ".jpg";
      imagePath = "../shopimages/matrix/table/product/";
    }
    var imageTitle = $(this).text();
    $target = $row.find(".first_column .bg_image"); //

    removeAllThumps();
    highlightActive($(this));
    placeThumb($target, imageName, imagePath, imageTitle);
  });
}

function highlightActive($active) {
  $("td.third_column a").removeClass("active");
  $active.addClass("active");
}

function placeThumb($target, imageName, path, imageTitle) {
  var imgUrl = "url(" + path + imageName + ")";
  $target.css("background-image", imgUrl).attr("title", imageTitle);
}

function removeAllThumps() {
  emptyImgUrl = "url()";
  $(".first_column .bg_image").css("background-image", emptyImgUrl);
}

/**
* gardencollection
**/

var fadingList = new Array();

function informationSliderHandler() {
  function FadingObj(id, listPos)
  {
      this.id = id;
      this.listPos = listPos;
  }

  $(".information_slider").mouseenter(function(){
    //alert($("a", this).attr("id"));
    if(!fadingList.containsFadingObj($("a", this).attr("id"))) {
      fObj = new FadingObj($("a", this).attr("id"), fadingList.length);

      // alert("Obj: "+  fObj.id);
      fadingList.push(fObj);
      //isSliding = true;
      flowElem = $(this).parent().find("div.flow");
      flowElem.css("opacity", 0.85);
      fadeFlowText(flowElem, fObj.id);
    }
  });
} // informationSliderHandler

function fadeFlowText(flowElem, id) {
  flowElem.fadeIn(1250);
  $(".effectbar").mouseleave(function(){
    flowElem.fadeOut(1000, function(){
      fadingList.popFadingObj(id);
     // $(".effectbar").unbind("mouseleave");
    });
  });
}

Array.prototype.popFadingObj = function(id) {
  var i;
  for (i=0; i<this.length; i++) {
    fobj = this[i];
    if (fobj.id === id) {
      //alert("loschen: " + i);
      this.deleteValue(i);
      break;
    }
  }
};

Array.prototype.deleteValue = function(position) {
  for (var x = 0; x < this.length; ++x) {
    if (x >= position) {
      this[x] = this[x + 1];
    }
  } this.pop();
};


Array.prototype.containsFadingObj = function(id) {
  var i, listed = false;
  for (i=0; i<this.length; i++) {
    fobj = this[i];
    if (fobj.id === id) {
    //  alert("contains: " +i);
      listed = true;
      break;
    }
  }
  return listed;
};

function routeFocus(element) {
     if (element.value == element.defaultValue) {
       element.value = '';
     }
   }
   function routeBlur(element) {
     if (element.value == '') {
       element.value = element.defaultValue;
     }
   }
   
 /*------jcarousellite-------*/

$(document).ready(function() {
        $(".carousel_slider").jCarouselLite({
            btnNext: ".carousel_next",
            btnPrev: ".carousel_prev",
            visible: 2.67
        });
      });
      
/*------myGallery-by-CSc-------*/
      
$(document).ready(function() {
   myGallery();
});
      
function myGallery() {
  $("#thumbnails .thumb").click(function() {
    var $elem = $(this);
    changePicture($elem);
  });
  
  $('.next').click(function() {
    $currentPic =  $('#thumbnails .thumb span:contains("'+$('#mainImage img').attr('src')+'")');
    $nextPic = $currentPic.parents().next("div.thumb");         
    if($nextPic.length == 0)
      $nextPic = $('#thumbnails .thumb:first');
    changePicture($nextPic);
  });
  
  $('.prev').click(function() {
    $currentPic =  $('#thumbnails .thumb span:contains("'+$('#mainImage img').attr('src')+'")');
    $prevPic = $currentPic.parents().prev("div.thumb");     
    if($prevPic.length == 0)
      $prevPic = $('#thumbnails .thumb:last');
    changePicture($prevPic);
  });
}

function changePicture($elem) {
    $('#mainImage img').fadeOut('fast', function() { 
      $(this).remove();
       $('#mainImage').append('<img title="'+$('img', $elem).attr('title')+'" alt="'+$('img', $elem).attr('alt')+'" src="'+$('.ref_image', $elem).text()+'" style="display: inline;">').fadeIn('fast');     
    });  
}
      
      
/*------Startseiten-Galerie------*/

$(document).ready(function() {
  
  if(!$("body").hasClass("hideSlideInBox")){
    var tmp = false;
    $(window).scroll(function() {
      var total = getDocHeight();
      var currentHeight = getScrollXY();
      var winSize = getWinSize(window);
      current = currentHeight[1] + winSize.height;
      if (currentHeight[1] != 0) {
        if (((100 / total) * current) > 50) {
          tmp = true;
          if (!$("#slideInBox").is(":visible") && currentHeight[1] != 0) {
            $('#slideInBox').show();
             $('#slideInBox').animate({
                marginRight: "20px"
             }, 500);
          }
        } else {
          if ($("#slideInBox").is(":visible") && tmp == true) {
             $('#slideInBox').animate({
                marginRight: "-320px"
             }, 500, function(){
                $(this).after().hide();
             });
          }
          ;
          tmp = false;
        }
      } else {
        $('#slideInBox').animate({
            marginRight: "-320px"
          }, 500, function(){
            $(this).after().hide();
        });
      }
    });
  }

  $('.nextImg').click(function() {
    $liElem = $('#img_array li.selected').length > 0 ? $('#img_array li.selected') : $('#img_array li:first');
    $liElem.removeClass('selected');
    $nextLiElem = $liElem.next();
    if($nextLiElem.length == 0) {
      $nextLiElem = $('#img_array li:first');
    }
    $nextLiElem.addClass('selected');    
    
    changeImage($('#img_array li.selected').html());
  });
  
  $('.prevImg').click(function() {     
    $liElem = $('#img_array li.selected');
    if($liElem.length > 0) {
      $liElem.removeClass('selected');
      $prevLiElem = $liElem.prev();
    }else {
      $prevLiElem = $('#img_array li:last');
    }    
    
    if($prevLiElem.length == 0) {
      $prevLiElem = $('#img_array li:last');
    }
    $prevLiElem.addClass('selected');
    changeImage($('#img_array li.selected').html());
  });  
  
  
  function checkCatalogueDivExists(){
    if(($('#mainImage div').children('div#catalogContainer').length != 0)){
      $('#ordertext').hide();
      $('#catalogue').hide();
      $('.prevImg').hide();
    }else{
      $('#ordertext').show();
      $('#catalogue').show();
      $('.prevImg').show();
    }
  }
  
  checkCatalogueDivExists();
  
  function changeImage(imgHtml) {
      $('#mainImage div').fadeOut('fast', function() {
        $(this).empty();
         $('#mainImage div').html(imgHtml).fadeIn('fast');
         checkCatalogueDivExists();
      });
  }  
});

