/**
 * @author jr
 */
// globale Variablen
variantes = new Object();
farbe     = new Object();
groesse   = new Object();

// onload
$(function(){

	//Cufon.replace('h1,h2,#info_content h3');
   $('.zoom').jqzoom({zoomWidth:300,zoomHeight:300,title:false});
    
    // Navi-Anpassung
   // $("#menu a.first ~ .section").hover(
   //     function() { $("#menu a.first span").addClass("spanAct") },
   //     function() { $("#menu a.first span").removeClass("spanAct") }
   // );
    
    // footer-Anpassung    
  //  $("#footerNav a:last").css("border","0");
    
    // Suche
    $("#searchInput").keypress(function (e) {
      if( e.which == 13 ) {
        doAjaxSearch(); 
        return false;
      }       
    });
    
    $("#searchBtn").click(function() {      
        doAjaxSearch(); 
        return false;
    });            
    
    // Detailseite (info_content ist Erkennungsmerkmal fuer Detailseiten)
    if( $("#info_content").length > 0 ) {                                                         
        $("#formError").hide();
        // Farben,Gr��en,Varianten
        addDetailAttributes();                
    }        
    
    // Produkt�bersicht (#thumbSize ist Erkennungsmerkmal fuer Produkt�bersicht)
    if ($("#thumbSize").length > 0) {
        //addProdColors();        
    }
    
    // reduzierte Preise - Farben anpassen
//    colorizeOffers();
       
});

/* --- colorizeOffers ---
 * Berichtigung der Farben f�r Angebote und Normalpreise
 */
function colorizeOffers() {
/*    $(".price").css("color","#005baa");
    
    $(".price").find(".oldPrice").css("color","#005baa");    
    $(".price").find(".oldPrice").parent().css("color","#ff0000");
    
    $(".priceCross").find(".oldPrice").css("color","#005baa");    
    $(".priceCross").find(".oldPrice").parent().css("color","#ff0000");*/
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
    eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
    if (restore) selObj.selectedIndex=0;
}

/* --- validEMail ---
 * pruefen, ob Mailadresse gueltig ist (Detailseite)
 */
function validEMail(s) {
    var a = false;
    var res = false;
    if(typeof(RegExp) == 'function') {
        var b = new RegExp('abc');
        if(b.test('abc') == true){a = true;}
    }
    if(a == true) {
        reg = new RegExp('^([a-zA-Z0-9\\-\\.\\_]+)'+ '(\\@)([a-zA-Z0-9\\-\\.]+)' + '(\\.)([a-zA-Z]{2,4})$');
        res = (reg.test(s));
    } else {
        res = (s.search('@') >= 1 && s.lastIndexOf('.') > s.search('@') && s.lastIndexOf('.') >= s.length-5)
    }
    return(res);
}

/* --- subRemind ---
 * Funktion, die beim Submitten von Remind-Form ausgefuehrt wird (Detailseite)
 */
function subRemind() {
    var isComplete = true;
    $("#customers_remind :text").each( function() {
        if( $(this).val().length < 3 ) {
            $(this).css("background","#EF7777");
            isComplete = false;
        } else {
            $(this).css("background","#ffffff");
        }
        if( $(this).attr("name") == "customers_input_email" ) {
            if( ! validEMail( $(this).val() )  ) {
                isComplete = false;
                $(this).css("background","#EF7777");
            }
        }
    });
    if( !isComplete ) {
        $("#formError").html( "<strong>Alle Eingabefelder m&uuml;ssen ausgef&uuml;llt sein und die E-Mail Adresse muss g&uuml;ltig sein<\/strong>").show();
        return false;
    }  
    document.forms['customers_remind'].submit();
}

/* --- getBestand ---
 * zust�ndig f�r die Item-Preisdarstellung
 * und Ein- und Ausblenden von Warenkorb-Button
 */
function getBestand ( ean ) { 
    url = "/fdi_check_bestand.php?ean=" + ean;

    $.getJSON( url ,  function(json){  
        try {
            var diffPrice = 0;
            var currentPrice = parseFloat( $("#currentPrice").val() );            
            currentPrice = Math.round(currentPrice * 100) / 100;            
            var betrag = parseFloat( json.betrag );
            var itemPrice = currentPrice;
            var changedItemPrice = false;
            var oldPrice = currentPrice;
            // Preis anpassen
            if( json.prefix == "+" && json.betrag != "0.0000" ) {
                var itemPrice = currentPrice + betrag;
                itemPrice = Math.round(itemPrice * 100) / 100;
                changedItemPrice = true;
            }
            if( json.prefix == "-" && json.betrag != "0.0000" ) {
                var itemPrice = currentPrice - betrag;
                itemPrice = Math.round(itemPrice * 100) / 100;
                changedItemPrice = true;
            }
            // backup item-Wert alt
            if( json.vkzuschlag > 0 ) {
                currentPrice += json.vkzuschlag;
            }
            
            // reduzierter Produktpreis
            // *** Produkt-Sonderpreis ***
            if( $("#priceDiff").val() != "zero" ) {
                diffPrice = parseFloat( $("#priceDiff").val() );
                // modifizierter Item-Preis
                if( changedItemPrice ) {
                    oldPrice = itemPrice + diffPrice;                    
                    $(".price")[0].innerHTML = '<span class="oldPrice">' + oldPrice.toFixed(2) + ' &euro;<\/span> ' + itemPrice.toFixed(2) + ' &euro;';
                } else {
                    // Item normal
                    oldPrice = currentPrice + diffPrice;                    
                    $(".price")[0].innerHTML = '<span class="oldPrice">' + oldPrice.toFixed(2) + ' &euro;<\/span> ' + itemPrice.toFixed(2) + ' &euro;';
                }                
            } 
            else {
                // *** Item-Sonderpreis ***                
                if( changedItemPrice && itemPrice < currentPrice  ) {
                    // Item-Sonderpreis bzw. Reduzierung bei Item
                    $(".price")[0].innerHTML = '<span class="oldPrice">' + currentPrice.toFixed(2) + ' &euro;<\/span> ' + itemPrice.toFixed(2) + ' &euro;';                    
                } else {
                    // Normale Preisdarstellung des Items
                    $(".price")[0].innerHTML = itemPrice.toFixed(2) + ' &euro;';    
                }                                
            }
            colorizeOffers();
        } catch(e) {
            $("#content").prepend('<!-- FEHLER: Preis konnte nicht gesetzt werden. -->')
        }

        // Bestellbutton anzeigen/ausblenden je nach Bestand
        if (  json.bestand < 1 ) { 
            $('.button_cart').hide();
            $('#break').hide();    
            $('#novariante').show();           
        } else {
            $('.button_cart').show();
            $('#break').show();    
            $('#novariante').hide();           
        }
    });
}

/* --- setHiddenVariante ---
 * [PL] Benutzer Oberfl�che unterstuetzt den WC Attribute Model (Detail- und Produktuebersicht)
 */
function setHiddenVariante()  { 
    sel_vf = $('.product_color_active').attr('alt');    
    
    if (navigator.appVersion.indexOf("MSIE 8.0") == -1) {
        var sel_vg = $('#groesse').val();
    }
    else {
        var sel_ind = document.getElementById("groesse").selectedIndex;
        var sel_vg = document.getElementById("groesse").options[sel_ind].value;
    }
    try {        
        $('#SelectedVarianteId').val(variantes[sel_vf + "_" + sel_vg][0]);
        $('#pean').empty();        
        getBestand(variantes[sel_vf + "_" + sel_vg][4]);        
        $('#pean').append(variantes[sel_vf + "_" + sel_vg][4]);
        $('#itemId').val($.trim($("#pean").text()));
        $('#pfehler').empty();
    } 
    catch (Err) {
        $('#pfehler').empty();
        $('.button_cart').hide();
        $('#break').hide();
        $('#novariante').show();
    }
} 

/* --- setFarbe ---
 * Zum Aktivieren einer Farbe bei der Detailseite
 * dadurch andere Gr��en in der Auswahl
 */
function setFarbe( colorCode, domId ) {
    var found = false, i = '', j = 0, textToInsert = [], fa = '';    
    $('#groesse').empty();  // select leeren
    for( var gr in groesse ) {      
        // select mit passenden Gr��en f�llen
        found = false;                                
        for( var k in variantes ) {
            i = variantes[k];
            if( i[1] == gr ) { 
                fa = 'img_'+ i[2].replace( / /g, "");                 
                if( fa == domId ) {
                    found = true;
                }
            }
        }                              
        if( found ) {  
            textToInsert[j++] = '<option  id ="g' + gr + '">' + gr  + '<\/option>';            
        }
    }
    $('#groesse').append( textToInsert.join('') );
        
    // Select the Attribute Farbe Checkbox
    $(".product_color_active").each( function() { 
        $(this).removeClass('product_color_active').addClass('product_color');
    });    
    $('#' + domId).addClass('product_color_active');
 
    try {
      // Bildwechsel
      eval( $('.color_id_'+ colorCode + ' a').attr('href').substring( 'javascript:'.length) );  
      $('.minibild div').hide();                   
      $('.color_id_' + colorCode ).show(); 
    } catch(e) {    
    }                   
  
}

/* --- addProdColors ---
 * Hinzufuegen der Farbbilder bei der Produktuebersicht
 */
function addProdColors() {
    var farbId; 
      $("div[id^=info]").each( function() {
         var $this = $(this); 
         var farbId = $(this).attr("id").replace( /.*?[a-zA-Z]+([0-9]+)$/, "$1");
         var url = location.protocol + "//" + location.host + "/fdi_get_product_attributes.php?pid=" + farbId + "&action=getCol";

         $.getJSON( url, function(json){
             var textToInsert = [];
             for( i=0; i<json.data.length; i++ ) {
                textToInsert[i] = '<img src="templates/schoeffel/colors/' + json.data[i] + '" />&nbsp;';
             }
             $this.append( textToInsert.join('') );
         });    
      }); 
}

/* --- addDetailAttributes ---
 * Hinzufuegen der Produkteigenschaften in Produktdetailseite: Farbe, Gr��e
 */
function addDetailAttributes() {
    var prodID = $("#prodID").val();
    var url = location.protocol + "//" + location.host + "/fdi_get_product_attributes.php?pid=" + prodID + "&action=getAtt";
    $.getJSON( url, function(json) {
        var i = 0, tmpfarbe = '', tmp = ''; sel_bildnummer = '', sel_bildId = '', bildnummer = '', bildId = '', textToInsert = [];        
        // globale Variablen variantes,farbe,groesse fuellen
        for( i=0; i<json.data.groesse.length; i++ ) {            
            variantes[ json.data.fullattr[i] ] = [ json.data.optionid[i], json.data.groesse[i], json.data.farbe[i], ' ', json.data.eans[i] ];            
            farbe  [ json.data.farbe[i] ] = json.data.farbe[i];
            groesse[ json.data.groesse[i] ] = json.data.groesse[i];             
        }        
      // Farben in Detailseite einfuegen
        ImgCounter = 0;
        for( var fa in farbe ) {       
            bildnummer = fa.replace( /.*?([a-zA-Z0-9]+)\s.*/, "$1") ;
            bildId = 'img_' + fa.replace( / /g, "" );
            if( !sel_bildId ) {
                sel_bildnummer = bildnummer;
                sel_bildId = bildId;
            }     
            
            if( bildnummer != "0" ) {
                textToInsert[i++] = '<img src="templates/schoeffel/colors/' + bildnummer + '.gif" title="' 
                    + fa + '"  alt="' + fa + '" id="' + bildId  + '" class="product_color_active" onclick="javascript:setFarbe(\'' + bildnummer + '\',\'' + bildId + 
                    '\');setHiddenVariante();"/>&nbsp;';                 
            }
            ImgCounter ++;
            if (ImgCounter == 6) {
               textToInsert[i++] = '<br />';
               ImgCounter = 0;
            }
        }
        $("#detailColor").append( textToInsert.join('') );
                            
        // Groessen in Detailseite einfuegen
        tmp = '<select id="groesse" onchange="setHiddenVariante()"> ';            
        for( var gr in groesse ) {
            // ID = g + groesse
            tmp += '<option  id="g' + gr + '">' + gr + '<\/option>';                                   
        }
        $("#detailSize").append( tmp + "<\/select>" );
        
        // Farbe aktivieren
        setHiddenVariante(); 
        setFarbe ( sel_bildnummer , sel_bildId  );
        
        //wenn mehr als eine Farbe Hauptproduktbild raus,
        //sonst einblenden und bei onload aktivieren   
        if( $("img[class^='product_color']").length > 1 ) {
            $("#mainProdPic").remove(); 
        } else {
            eval( $("#mainProdPic a").attr("href").substring(11) ); 
			$("#mainProdPic").remove(); 
        }    
    });    
}

// alter ausgelagerter JS-Code

// swapImg
function swapImg(className,swappedImg,swappedLink) {
   $("img." + className ).attr("src",swappedImg);
   var popupImg = swappedImg.replace("info_images", "zoom_images");   
   $("a." + className ).attr("href", popupImg );
   $("a[name=popup]").attr("href", 'javascript:popupWindow(\''+swappedLink+'\')' );
}

var selected;
var submitter = null;

function submitFunction() {
$(function() {
    submitter = 1;
});
}

// Engelhorn payment iframe
function resizeIFrame() {
    var thename = window.name;
    var iframe = parent.document.getElementById(thename);
    if (iframe == null)
        iframe = window.parent.frames[thename];
    if (iframe != null) {
        if (iframe.contentDocument && iframe.contentDocument.body.offsetHeight) {
            iframe.height = 250;
            iframe.height = Math.min(iframe.contentDocument.body.scrollHeight,100000);
        } else {
            if (iframe.Document && iframe.Document.body.scrollHeight) {
                iframe.height = Math.min(iframe.Document.body.scrollHeight, 100000) + 2;
            }
        }
    }
}


function popupWindow(url) {
  window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=100,height=100,screenX=150,screenY=150,top=150,left=150')
}  

function selectRowEffect(object, buttonSelect) {
$(function() {
  if (!selected) {
    if (document.getElementById) {
      selected = document.getElementById('defaultSelected');
    } else {
      selected = document.all['defaultSelected'];
    }
  }

  if (selected) selected.className = 'moduleRow';
  object.className = 'moduleRowSelected';
  selected = object;

// one button is not an array
  if (document.getElementById('payment'[0])) {
    document.getElementById('payment'[buttonSelect]).checked=true;
  } else {
    //document.getElementById('payment'[selected]).checked=true;
  }
});
}

function rowOverEffect(object) {
$(function() {
  if (object.className == 'moduleRow') object.className = 'moduleRowOver';
});
}

function rowOutEffect(object) {
$(function() {
  if (object.className == 'moduleRowOver') object.className = 'moduleRow';
});
}

function popupImageWindow(url) {
$(function() {
  window.open(url,'popupImageWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,width=100,height=100,screenX=150,screenY=150,top=150,left=150')
});
}
