
var $j = jQuery.noConflict();


$j(function($) {

  // ignore these keys
  var ignore = [8,9,13,33,34,35,36,37,38,39,40,46];

  // use keypress instead of keydown as that's the only
  // place keystrokes could be canceled in Opera
  var eventName = 'keypress';

  // handle textareas with maxlength attribute
  $j('textarea[maxlength]')

    // this is where the magic happens
    .live(eventName, function(event) {
      var self = $j(this),
          maxlength = self.attr('maxlength'),
          code = $j.data(this, 'keycode');

      // check if maxlength has a value.
      // The value must be greater than 0
      if (maxlength && maxlength > 0) {

        // continue with this keystroke if maxlength
        // not reached or one of the ignored keys were pressed.
        return ( self.val().length < maxlength
                 || $j.inArray(code, ignore) !== -1 );

      }
    })

    // store keyCode from keydown event for later use
    .live('keydown', function(event) {
    	$j.data(this, 'keycode', event.keyCode || event.which);
    });

});


$j(document).ready( function() {	
	

	var gift = {
		textCounter: function (which, rel) {
				if ( $j(which).val() != 'Geben Sie hier ihre persönliche Grußbotschaft an.' ) {
					var maxCountVal 	= $j('#maxZeichen'+rel).text();
					var text			= $j(which).val();
					var currentCount	= text.length;
					var count 			= maxCountVal - currentCount;
					
					if ( count >= 0 ) {
						var displayhere = $j('#maxCounterDisplay'+rel);
						displayhere.text(count);
					}
				}
		 }
	
	};
	// add zoom to click on image not only zoom "lupe" START
	/*
	var productImg	= $j('p.product-image img');
	var imgZoom		= $j('#img_zoom');
	
	productImg.css('cursor', 'pointer');
	productImg.click(function(){
		imgZoom.trigger('click');
	})
	*/
	// add zoom to click on image not only zoom "lupe" END
	
	
	// get allowd character count for sleected giftwrap START
	var mySelect = $j('#item_styleselection');
	mySelect.live('change', function() {
		var block		= $j(this).attr('rel');
		var selected	= $j(this).val();
		var allowed		= $j('#allowedChars_' + selected).val();
		var allowed		= allowed/10;
		
		$j('#maxZeichen' + block).text(allowed);
		$j('#maxCounterDisplay' + block).text(allowed);
	});
	// get allowed character count for sleected giftwrap END

	
	var textarea	= $j('.giftwrap-message textarea');
	var x			= 0;
	
	textarea.each(function(){
		var maxCountVal = $j('#maxZeichen' + x).text();
		if ( $j('#maxCounterDisplay'+x).length == 0 ) {
			$j(this).after('<span style="float: right;"><b id="maxCounterDisplay'+x+'">'+maxCountVal+'</b> Zeichen übrig</span>');
		}
		
		//if ( $j(this).attr('maxlength') != maxCountVal) 
			$j(this).attr('maxlength', maxCountVal);
		
		gift.textCounter(this, x)
		x++;
	});
	
	$j(textarea).live('keyup', function() {
		var rel = $j(this).attr('rel');
		gift.textCounter(this, rel);
	});
	
})
