$(document).ready(function() {




/**
 *  Version 2.1
 *      -Contributors: "mindinquiring" : filter to exclude any stylesheet other than print.
 *  Tested ONLY in IE 8 and FF 3.6. No official support for other browsers, but will
 *      TRY to accomodate challenges in other browsers.
 *  Example:
 *      Print Button: <div id="print_button">Print</div>
 *      Print Area  : <div class="PrintArea"> ... html ... </div>
 *      Javascript  : <script>
 *                       $("div#print_button").click(function(){
 *                           $("div.PrintArea").printArea( [OPTIONS] );
 *                       });
 *                     </script>
 *  options are passed as json (json example: {mode: "popup", popClose: false})
 *
 *  {OPTIONS} | [type]    | (default), values      | Explanation
 *  --------- | --------- | ---------------------- | -----------
 *  @mode     | [string]  | ("iframe"),"popup"     | printable window is either iframe or browser popup
 *  @popHt    | [number]  | (500)                  | popup window height
 *  @popWd    | [number]  | (400)                  | popup window width
 *  @popX     | [number]  | (500)                  | popup window screen X position
 *  @popY     | [number]  | (500)                  | popup window screen Y position
 *  @popTitle | [string]  | ('')                   | popup window title element
 *  @popClose | [boolean] | (false),true           | popup window close after printing
 *  @strict   | [boolean] | (undefined),true,false | strict or loose(Transitional) html 4.01 document standard or undefined to not include at all (only for popup option)
 */
(function($) {
    var counter = 0;
    var modes = { iframe : "iframe", popup : "popup" };
    var defaults = { mode     : modes.iframe,
                     popHt    : 500,
                     popWd    : 400,
                     popX     : 200,
                     popY     : 200,
                     popTitle : '',
                     popClose : false };

    var settings = {};//global settings

    $.fn.printArea = function( options )
        {
            $.extend( settings, defaults, options );

            counter++;
            var idPrefix = "printArea_";
            $( "[id^=" + idPrefix + "]" ).remove();
            var ele = getFormData( $(this) );

            settings.id = idPrefix + counter;

            var writeDoc;
            var printWindow;

            switch ( settings.mode )
            {
                case modes.iframe :
                    var f = new Iframe();
                    writeDoc = f.doc;
                    printWindow = f.contentWindow || f;
                    break;
                case modes.popup :
                    printWindow = new Popup();
                    writeDoc = printWindow.doc;
            }

            writeDoc.open();
            writeDoc.write( docType() + "<html>" + getHead() + getBody(ele) + "</html>" );
            writeDoc.close();

            printWindow.focus();
            printWindow.print();

            if ( settings.mode == modes.popup && settings.popClose )
                printWindow.close();
        }

    function docType()
    {
        if ( settings.mode == modes.iframe || !settings.strict ) return "";

        var standard = settings.strict == false ? " Trasitional" : "";
        var dtd = settings.strict == false ? "loose" : "strict";

        return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01' + standard + '//EN" "http://www.w3.org/TR/html4/' + dtd +  '.dtd">';
    }

    function getHead()
    {
        var head = "<head><title>" + settings.popTitle + "</title>";
        $(document).find("link")
            .filter(function(){
                    return $(this).attr("rel").toLowerCase() == "stylesheet";
                })
            .filter(function(){ // this filter contributed by "mindinquiring"
                    var media = $(this).attr("media");
                    return (media.toLowerCase() == "" || media.toLowerCase() == "print")
                })
            .each(function(){
                    head += '<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" >';
                });
        head += "</head>";
        return head;
    }

    function getBody( printElement )
    {
    	 var logo = '<img src="http://www.catrice.eu/fileadmin/templates/main/imgs/catrice_cosmetics.png" alt="" class="printlogo" />';
    
        return '<body>' + logo + '<div class="' + $(printElement).attr("class") + '">' + $(printElement).html() + '</div></body>';
    }

    function getFormData( ele )
    {
        $("input,select,textarea", ele).each(function(){
            // In cases where radio, checkboxes and select elements are selected and deselected, and the print
            // button is pressed between select/deselect, the print screen shows incorrectly selected elements.
            // To ensure that the correct inputs are selected, when eventually printed, we must inspect each dom element
            var type = $(this).attr("type");
            if ( type == "radio" || type == "checkbox" )
            {
                if ( $(this).is(":not(:checked)") ) this.removeAttribute("checked");
                else this.setAttribute( "checked", true );
            }
            else if ( type == "text" )
                this.setAttribute( "value", $(this).val() );
            else if ( type == "select-multiple" || type == "select-one" )
                $(this).find( "option" ).each( function() {
                    if ( $(this).is(":not(:selected)") ) this.removeAttribute("selected");
                    else this.setAttribute( "selected", true );
                });
            else if ( type == "textarea" )
            {
                var v = $(this).attr( "value" );
                if ($.browser.mozilla)
                {
                    if (this.firstChild) this.firstChild.textContent = v;
                    else this.textContent = v;
                }
                else this.innerHTML = v;
            }
        });
        return ele;
    }

    function Iframe()
    {
        var frameId = settings.id;
        var iframeStyle = 'border:0;position:absolute;width:0px;height:0px;left:0px;top:0px;';
        var iframe;

        try
        {
            iframe = document.createElement('iframe');
            document.body.appendChild(iframe);
            $(iframe).attr({ style: iframeStyle, id: frameId, src: "" });
            iframe.doc = null;
            iframe.doc = iframe.contentDocument ? iframe.contentDocument : ( iframe.contentWindow ? iframe.contentWindow.document : iframe.document);
        }
        catch( e ) { throw e + ". iframes may not be supported in this browser."; }

        if ( iframe.doc == null ) throw "Cannot find document.";

        return iframe;
    }

    function Popup()
    {
        var windowAttr = "location=yes,statusbar=no,directories=no,menubar=no,titlebar=no,toolbar=no,dependent=no";
        windowAttr += ",width=" + settings.popWd + ",height=" + settings.popHt;
        windowAttr += ",resizable=yes,screenX=" + settings.popX + ",screenY=" + settings.popY + ",personalbar=no,scrollbars=no";

        var newWin = window.open( "", "_blank",  windowAttr );

        newWin.doc = newWin.document;

        return newWin;
    }
})(jQuery);








 

	$.ajaxSetup({
	    cache: false
	});
	
	loadMerkzettel();



	checkURLParams();
	



	  $(function()
	    {
	      $('#content_lightbox').jScrollPane();
	      $('#second_tabcontent').jScrollPane();
	    //     $('#textpane').jScrollPane();
	    });
	  
	  
	//$(function()
	//{
	//  $('#textpane').jScrollPane(
	//    {
	//      verticalDragMinHeight: 20,
	//      verticalDragMaxHeight: 20
	//    }
	//  );
	//});
	  
	
	
	
	// initialize all expanding textareas
	  jQuery("textarea").TextAreaExpander();
	
	
	//Tooltip Chargen-Nr.
	$(".batch_hover").mouseover(function() {
	$(".batch_tooltip").css("display","block");
	}).mouseout(function(){
	$(".batch_tooltip").css("display","none");
	}); 
	
	
	//$('#textpane').keypress(function() {
	//
	//$(function()
	//{
	//  $('#textpane').jScrollPane(
	//    {
	//      verticalDragMinHeight: 20,
	//      verticalDragMaxHeight: 20
	//    }
	//  );
	//});
	
	
	
	
  //ACCORDION BUTTON ACTION (ON CLICK DO THE FOLLOWING)
  $('.accordionButton').click(function() {

    //REMOVE THE ON CLASS FROM ALL BUTTONS
    $('.accordionButton').removeClass('on');
      
    //NO MATTER WHAT WE CLOSE ALL OPEN SLIDES
     $('.accordionContent').slideUp('normal');
   
    //IF THE NEXT SLIDE WASN'T OPEN THEN OPEN IT
    if($(this).next().is(':hidden') == true) {
      
      //ADD THE ON CLASS TO THE BUTTON
      $(this).addClass('on');
        
      //OPEN THE SLIDE
      $(this).next().slideDown('normal');
     } 
      
   });

	    
	  
	  
	  /********************************************************************************************************************
	  CLOSES ALL S ON PAGE LOAD
	  ********************************************************************************************************************/  
	  $('.accordionContent').hide();
	  
	
	
	  
	/*** Language Menue ***/  
	
	$('.links-list-header').hover(function() { 
	//$('#overlay-lang').slideDown(100);
	$('#overlay-lang').show();
	$('.tx-srlanguagemenu-pi1').addClass('over');
	});
	
	$('.tx-srlanguagemenu-pi1').mouseleave(function(){
	//$('#overlay-lang').slideUp(100);
	$('#overlay-lang').hide();
	$('.tx-srlanguagemenu-pi1').removeClass('over');
	});
	
	
	/*** Merkzettel ***/  
	
	$('#merkzetteltrigger').hover(function() { 
	//$('#merkzettelwrap').slideDown(100);
	//loadMerkzettel();
	$('#merkzetteltrigger').css("color","#ffffff");
	$('#merkzettelwrap').show();
	$('.tx-nbcatriceproducts-pi3').addClass('over');
	
	});
	
	$('.tx-nbcatriceproducts-pi3').mouseleave(function(){
	//$('#merkzettelwrap').slideUp(100);
	$('#merkzetteltrigger').css("color","#494949");
	$('#merkzettelwrap').hide();
	$('.tx-nbcatriceproducts-pi3').removeClass('over');
	});
	    
	
//	/*** Top Navigation ***/  
//	
//	$('#topnavigation ul li').hover(function() {
//	$(this).addClass('over');
//	});
//	
//	$('#topnavigation ul li').mouseleave(function(){
//	$(this).removeClass('over');
//	});
      
      
      
      
      
      
	/*** ################################################################### ***/
    /*** Merkzettel Stuff Start***/
    
    function parseResponse(data){
		$("#merkzettelinhalt").html(data.cart);
	}
    function parseResponseEmail(data){
		$("#cartmailer").html(data.cart);
	}
    function parseResponse2(data){
    	var emptymessage = $("#emptycartmessagetmp").html();

    	var action = data.action;
    
    	var tmp = '<div id="flyoutheader"></div><table class="cartflyout" >';
    	
    	var print = '<div id="printlist"></div><table class="cartflyout" >';
    	
		var newheader = 1;
		var currentheader = '';
		var totalitems = data.cart.length;
		
		for (var i=0; i<data.cart.length; i++) {
		   
		   //6 = number of items in fly out 
		   if (i < 6){ 
			    
						    
			    if ((newheader == 0) && (currentheader != data.cart[i]["category"])){
					newheader = 1;
					tmp = tmp + '<tr>';
				}
		
		
				if (newheader == 1){
					tmp = tmp + '</table><table class="cartflyout">';
					tmp = tmp + '<tr>';
					//table header mit subcategory
					
					
					tmp = tmp +'<th colspan="4" class="category">' + data.cart[i]["category"] + '</th>';
					tmp = tmp + '</tr><tr>';
					
					
					newheader = 0;
					
					currentheader = data.cart[i]['category'];
				}
			
			
				tmp = tmp + '<td class="col1">' + '<img src="' + data.cart[i]["imagepath"] + '" alt="" /></td>';
				tmp = tmp + '<td class="col2">' + data.cart[i]["parentproductname"] + '</td><td class="col3">' + data.cart[i]["colorname"] + '</td>';
				tmp = tmp + '<td class="col4"><a class="deletenotepad" rel="' + data.cart[i]["productnumber"] + '"></a></td>';
				
				
				tmp = tmp + '</tr>';
		   }
		   
		   // print:
			
		}
		
		
		
		
		tmp = tmp + '</table><div id="flyoutfooter"></div>';
		
		if (i==0){
			$("#merkzettelinhalt").html(emptymessage);
			$("#merkzettelfunktionen").hide();
			$("#merkzettelwrap").addClass("empty");
			var leer = "";
			$("#numberitems").html(leer);
			
		} else {
		
			var numberitems = '&nbsp;(' + i + ')';
			$("#numberitems").html(numberitems);
			
			$("#merkzettelinhalt").html('').html(tmp);
			$("#merkzettelwrap").removeClass("empty");
			$("#merkzettelfunktionen").show();
		}
		//alert(tmp);
		
		
		//listenansicht refresh
		if (action == "deletefromlist"){
		
			/*
			old_url = location.href;
			
			var new_url = old_url.substring(0, old_url.indexOf('&'));

			location.href=new_url;
			*/
			
			location.reload();
		}
		
		
		//add number of items to trigger in top menu list:
		$("#merkzettelitems").html($("#numberitems").html());
		 
		
		
		
	}
		
	
	function loadMerkzettel(){
		//$("#merkzettelwrap").toggle(function(){});
	
		//if ($('#merkzettelwrap').is(':visible')) {
		//alert("show");
			$.getJSON("index.php?eID=cart", {"action" : "load"}, parseResponse2); 	
		//}			
	}
	
	function checkURLParams(){
		//get-parameters controlling action / print-send
		var actionvar = getUrlVars()["action"];
		if (actionvar == "print"){
			$(".tx-nbcatriceproducts-pi7").printArea();
			//alert("get-var: print");		
		}			
	}
	
	
		
	//produkt zum merkzettel hinzufuegen
	$(".addnotepad").click(function() {	
		productnumber = $(this).attr('rel');
		productURL = encodeURIComponent(window.location);
		$.getJSON("index.php?eID=cart", {"action" : "add", "productnumber" : productnumber, "productURL" : productURL, "language" : language}, parseResponse2);
		$('#merkzetteltrigger').css("color","#B13690");
					
	});
	
	
	//merkzettel leeren
	$("#cartclear").click(function() {		
		$.getJSON("index.php?eID=cart", {"action" : "clear", "language" : language}, parseResponse2);
		//$("#merkzettelwrap").toggle(function(){}); 					
	});


	$("#printlist").click(function() {	
		
		$(".tx-nbcatriceproducts-pi7").printArea();			
	});
	


	$("#sendcart").click(function() {
		var recipient = $("#recipientemail").val();	

		var recipientname = $("#recipientname").val();
		var recipientsurname = $("#recipientsurname").val();	
	
			
		$.getJSON("index.php?eID=cart", {"action" : "send", "recipient" : recipient,"name" : recipientname,"surname" : recipientsurname, "language" : language }, parseResponseEmail);
			
	});
	


     $(".deletenotepad").live('click', function() {
          productnumber = $(this).attr('rel');
		//alert(productnumber);
		$.getJSON("index.php?eID=cart", {"action" : "delete", "productnumber" : productnumber, "language" : language}, parseResponse2);
		
     });




	 	
     $(".deletenotepadlist").live('click', function() {
          productnumber = $(this).attr('rel');
		//alert(productnumber);
		$.getJSON("index.php?eID=cart", {"action" : "deletefromlist", "productnumber" : productnumber, "language" : language}, parseResponse2);
		
		
		
		 
		//$(this).parent().parent().remove();
     });
	
	
	
	
	
	
	 /* Send Cart via email */
	 
	 function checksendbutton(){
	 
	 		var email = $("#recipientemail").val();
			var name = $("#recipientname").val();
			var surname = $("#recipientsurname").val();
		
			if(email != 0 && name != 0 && surname != 0)
			{
				if(isValidEmailAddress(email))
				{
					$("#sendcart").removeAttr('disabled');
					$("#sendcart").show();
				} else {			
					
					
					$("#sendcart").attr('disabled', 'disabled');
					$("#sendcart").hide();
				}
			} 
			
			else {
				$("#sendcart").attr('disabled', 'disabled');	
				$("#sendcart").hide();	
			}	 
	 }
	 
	 
	$("#recipientemail").keyup(function(){		
		checksendbutton();		
	});
	
	
	$("#recipientemail").live('input paste',function(e){
    	checksendbutton();
	});

	$("#recipientname").keyup(function(){		
		checksendbutton();		
	});
	
	
	$("#recipientname").live('input paste',function(e){
    	checksendbutton();
	});
	
	
	$("#recipientsurname").keyup(function(){		
		checksendbutton();		
	});
	
	
	$("#recipientsurname").live('input paste',function(e){
    	checksendbutton();
	});	
	
	
	
	// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.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;
}


	
	
	
	function isValidEmailAddress(emailAddress) {
 		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
 		return pattern.test(emailAddress);
	}	 
	 /* ------------------- */
	


		
	
	/*** ################################################################### ***/
    /*** Merkzettel Stuff End***/	
    
    
/*** Overlay Startseite ***/  

$("#collage").hide(0).delay(2000).fadeIn(1500);



  
$('.triggeroverlay').hover(function() { 
  $('#bg,#collage').clearQueue();
    $('#bg,#collage').fadeTo('normal', 0.5, function() {
        
    });
  $(this).next().css("display","inline");
     
  
  });
  
  $('.overlay').mouseleave(function(){
       
    $('#bg,#collage').fadeTo('normal', 1, function() {
    	$('#bg,#collage').clearQueue();
    
      });
      
     $('.overlay').css("display","none");
    
  });

  
  $("div.linkoverlay").click(
    function()
    {
    window.location = $(this).attr("url");
    });
    
    
    
  
});




