/*** NATIVE *******************************************************************/
/***Clearing for Inputs***/
function clearInput(obj, cpValue) {
	if(obj.value == cpValue) {obj.value = '';}
}
/***Clearing for TextAreas***/
function clearTextArea(obj, cpValue) {
	if(obj.innerHTML == cpValue) {obj.innerHTML = '';}
}

/*** JQUERY *******************************************************************/
/**
 * this function is for simulation the bind() function like in mootools
 */
jQuery.extend({
	  shove: function(fn, object) {
	    return function() {
	      return fn.apply(object, arguments);
	    }
	  }
});
/*
 * hide suggestlayer if open, and flyout mainmenu is triggered
 */
function flyOutMenu() {
	$ = jQuery;
	$('#main-menu').bind('mouseenter',function(){
		$('#suggestLayer').hide();
	});
}

/**
 * function for slideable login header
 * @author			Markus Brunner
 */
function displaySlidableLogin(initialHeight,layerOpacity) {
	if(initialHeight == '') {initialHeight = '-118px';}
	if(layerOpacity == '') {layerOpacity = '1.0';}

	/* initial positioning */
	jQuery('#login-layer').show().css({'top':initialHeight});

	/* initial opcity: opacity:0.9;filter:alpha(opacity=90); */
	/*jQuery("#top-login-div").show().css({'opacity':layerOpacity});*/

	/* click-action for open-button */
	jQuery("#login-button").click(
		function(){
			/* std: jQuery('#top-login-div').slideToggle("slow");*/
			if(jQuery('#login-layer').css('top') == initialHeight) {
				jQuery('#header').addClass('overlayed');
				jQuery('#login-layer').animate(
					{top: '0px'},500,'swing'
				);
			} else {
				jQuery('#login-layer').animate(
					{top: initialHeight},500,'swing',function(){
						jQuery('#header').removeClass('overlayed');
					}
				);
			}
		}
	);

	/* click-action for close-button */
	jQuery("#close-login-div").click(
		function(){
			/* std: jQuery('#top-login-div').slideUp("slow");*/
			jQuery('#login-layer').animate(
				{top: initialHeight},500,'swing',function(){
						jQuery('#header').removeClass('overlayed');
					}
			);
		}
	);

	/* special selectbox selection */
	jQuery('.special-select').mouseover(function()
	{
		jQuery('.special-select-sublist').show();
	});
	jQuery('.special-select').mouseout(function()
	{
		jQuery('.special-select-sublist').hide();
	});
}
/**
 * Open link functions
 */
var openLinkStatus = 0;
function openLinkUrl(linkUrl) {
	if(linkUrl != '/' && openLinkStatus == 0) {
		openLinkStatus = 1;
		window.location = linkUrl;
		openLinkStatus = 0;
	}
}
/***jQuery product-box-link initialization***/
function initProductBoxLinks() {
	jQuery('.product-box:not(.openpopup)').each(function(index,elem){
		jQuery(elem).click(function() {
			boxLink = jQuery(elem).find('a').attr('href');
			openLinkUrl(boxLink);
		});
	});
}
/**
 * Open Pop-Up-Functions
 */
var websiteWidth = 600;
var popupid = 'popup';
var popuplayerid = 'popuplayer';
var popupcontentid = 'popupcontent';
var closePopupClass = 'closepopup';
var enablePopupCloseButton = true;
var websiteWidthBigImage = 960;
function openPopUpByAjaxContent(url) {
	jQuery.ajax({
		url:url,
		success:function(data) {
			openPopUp(data);
		},
		dataType:'html'
	});
}
function openPopUpByAttributeForBigImage(elem,dataAttribute) {
	
	var content = '<div '+(websiteWidthBigImage > 0 ? 'data-width="'+websiteWidthBigImage+'" ' : '')+'class="align-center"><img src="'+jQuery(elem).attr(dataAttribute)+'" alt="" class="displayinline" /></div>';
	openPopUp(content);
}
function openPopUpByContentId(contentSelector) {
	openPopUp(jQuery(contentSelector).html());
}
function openPopUp(content) {
	var content;
	var widthForPopup = websiteWidth;
	if(enablePopupCloseButton) {
		content = content+'<div class="'+closePopupClass+'">&nbsp;</div>';
	}
	var customWidth = parseInt(jQuery(content).filter('[data-width]:first').data('width'));
	if(!isNaN(customWidth)){
		widthForPopup = customWidth;
	}
	if(jQuery('#'+popupid).length > 0) {
		jQuery('#'+popupcontentid).html(content);
	} else {
		content = '<div id="'+popupid+'" style="display:none"><div id="'+popuplayerid+'" class="'+closePopupClass+'">&nbsp;</div><div id="'+popupcontentid+'">'+content+'</div></div>';
		jQuery('body').append(content);
	}
	var leftMargin = (jQuery('body').innerWidth() - widthForPopup) / 2;

	var pos = jQuery(window).scrollTop();
	var topMargin = 128 + pos;
	jQuery('#'+popuplayerid).css({'backgroundColor':'white','opacity':'0.5'});
	jQuery('#'+popupcontentid).css({'left':leftMargin+'px','top':topMargin+'px','width':widthForPopup+'px'});
	jQuery('#'+popupid).fadeIn();
	jQuery('#'+popupid).trigger('popupopened');		
}
function closePopUp() {
	jQuery('#'+popupid).fadeOut('slow');
	jQuery('#'+popupcontentid).html('');
}

/***jAnythingSlider initialization***/
function initJAnythingSlider() {
	$ = jQuery;
	var container = $('.slider-container');
	var slideElements = $('.slider-element',container);

	if(slideElements.length > 0 && container.length == 1){
		$(slideElements).each(function(index,el){
			var wrapLi = $('<li></li>').attr('id','slider-element-'+index);
			$(el).wrap(wrapLi);
		});
		//reversed
		$(slideElements).parent('li').wrapAll('<div class="anythingSlider"><div class="wrapper"><ul></ul></div></div>');

		$('.anythingSlider').anythingSlider({
					easing: "swing",												// Anything other than "linear" or "swing" requires the easing plugin
					autoPlay: true,													// This turns off the entire FUNCTIONALY, not just if it starts running or not.
					delay: 10000,														// How long between slide transitions in AutoPlay mode
					startStopped: false,										// If autoPlay is on, this can force it to start stopped
					animationTime: 600,											// How long the slide transition takes
					hashTags: false,												// Should links change the hashtag in the URL?
					buildNavigation: true,									// If true, builds and list of anchor links to link to each slide
					pauseOnHover: false,										// If true, and autoPlay is enabled, the show will pause on hover
					startText: "",													// Start text
					stopText: "",														// Stop text
					navigationFormatter: sliderPagerText		// Details at the top of the file on this use (advanced use)
		});
	}
}

function initProductImageSlider(){
	$ = jQuery;
	var container = $('.product-image-variants.slider-wrapper-small');
	var slideElements = $('.slider-element',container);

	if(slideElements.length > 0 && container.length == 1){
		$(slideElements).each(function(index,el){
			var wrapLi = $('<li></li>').attr('id','slider-element-'+index);
			$(el).wrap(wrapLi);
		});
		//reversed
		$(slideElements).parent('li').wrapAll('<div class="product-image-slider"><div class="wrapper"><ul class="clearfix"></ul></div></div>');
		$(container).addClass('sliding');

		$('.product-image-slider').anythingSlider({
					easing: "swing",												// Anything other than "linear" or "swing" requires the easing plugin
					autoPlay: false,													// This turns off the entire FUNCTIONALY, not just if it starts running or not.
					delay: 10000,														// How long between slide transitions in AutoPlay mode
					startStopped: true,										// If autoPlay is on, this can force it to start stopped
					animationTime: 600,											// How long the slide transition takes
					hashTags: false,												// Should links change the hashtag in the URL?
					buildNavigation: false,									// If true, builds and list of anchor links to link to each slide
					pauseOnHover: true,										// If true, and autoPlay is enabled, the show will pause on hover
					startText: "",													// Start text
					stopText: "",														// Stop text
					navigationFormatter: sliderPagerText		// Details at the top of the file on this use (advanced use)
		});
	}	
}
function sliderPagerText(index, panel) {
	return index + "";
};
/**
 * Fixes the height of two or more columns
 *
 * @name		$.fixColumnHeights
 * @cat			Plugins/Design
 * @author		Markus Brunner
 * @version		1.0.1 (jQuery 1.5.*)
 *
 * @param									Object settings [optional]
 * elementsSelector: []						String of comma-separated selectors		selector for the columns - otherwise all children of wrapper
 * additionalHeight: 0						Integer																Additional px to computed max-height
 * setOnlyMinHeight: false					Boolean																If this option is true, no height is set, only min-height. This isn't working in all browser, but may bee needed for dynamic content.
 *
 * @how-to	jQuery('#wrapper').fixColumnHeights({elementsSelector:'.nav,.content',additionalHeight:20,setOnlyMinHeight:true});
 */
(function($) {
	$.fn.fixColumnHeights = function(params) {
		var options = {
			elementsSelector: '',
			additionalHeight: 0,
			setOnlyMinHeight: false
		};
		return $(this).each(function(index,elem) {
			// Merge params with default option values
			$.extend(true, options, params);
			// Get all columns
			var columns;
			if(options.elementsSelector.length > 0) {
				columns = jQuery(elem).find(options.elementsSelector);
			} else {
				columns = jQuery(elem).children();
			}
			//console.log(columns);
			// Compute Columns Height
			var maxColumnHeight = 0;
			jQuery(columns).each(function(innerIndex,innerElem){
				if(jQuery(innerElem).height() > maxColumnHeight) {
					maxColumnHeight = jQuery(innerElem).height();
				}
			});
			// Fix Column Height
			if(options.setOnlyMinHeight === true) {
				jQuery(columns).css('min-height',maxColumnHeight+options.additionalHeight+'px');
			} else {
				jQuery(columns).height(maxColumnHeight+options.additionalHeight+'px');
			}
		});
	};
})(jQuery);


function initRatingForm(){
	$ = jQuery;
	$('.rating-form:visible form input[type="submit"]').live('click',function(ev){
		ev.preventDefault();
		ev.stopPropagation();
		$(this).parents('form:first').submit();
	});
	$('.rating-form:visible form').live('submit',function(ev){
		ev.preventDefault();
		var data = {
			"rating_price": parseInt($('.rating-form:visible :input[name="tx_nfcshop_pi1[rating][rating_price]"]').val()),
			"rating_quality": parseInt($('.rating-form:visible :input[name="tx_nfcshop_pi1[rating][rating_quality]"]').val()),
			"rating_design": parseInt($('.rating-form:visible :input[name="tx_nfcshop_pi1[rating][rating_design]"]').val()),
			"rating_service": parseInt($('.rating-form:visible :input[name="tx_nfcshop_pi1[rating][rating_service]"]').val()),
			"size": parseInt($('.rating-form:visible :input[name="tx_nfcshop_pi1[rating][size]"]:checked').val()),
			"comment": $('.rating-form:visible :input[name="tx_nfcshop_pi1[rating][comment]"]').val(),
			"email": $('.rating-form:visible :input[name="tx_nfcshop_pi1[rating][email]"]').val(),			
			"name": $('.rating-form:visible :input[name="tx_nfcshop_pi1[rating][name]"]').val()
		}
		handleRatingForm(data);
	});
	
	$('#rating-link').bind('click',function(ev){
		$('.rating-form .rating-errror').hide();
		openPopUpByContentId('#rating-form-wrapper');
	});
	$('#popup .rating-form').live('rating_form_submitted',function(ev){
		$('#rating-form-wrapper,.ratinglink').remove();
	});
}

function initProductListCategoryText(){
	$ = jQuery;
	var contentWrapper = $('.productlist-category-description-wrapper');
	var targetWrapper = $('#content-left');
	if(contentWrapper.length > 0 && targetWrapper.length > 0){
		$(targetWrapper).append($(contentWrapper).html());
	}
}

function initJQZoom(){
	if(jQuery.fn.jqzoom){
		var jQZoomOptions = {
			zoomWidth: 270,
			zoomHeight: 270,
			xOffset: 75,
			yOffset: 0,
			position: "right",
			title: false
		};
		
		$('.zoom-class').jqzoom(jQZoomOptions);
		
		$('.product-image-variants .image-wrapper a').live('mouseenter',function(ev){
			 jQuery(this).trigger('click');
		});
	}
}

/*** Factfinder Filter Function ***/
function filterSelectAction(elem) {
	if(elem.value != '') { 
		if(elem.value.match(/^\//) != null) { 
			document.location.href=window.location.protocol+'//'+window.location.host+elem.value; 
		} else {  
			document.location.href=window.location.protocol+'//'+window.location.host+'/'+elem.value; 
		}	
	}
}

function initUniform(){
	if(jQuery.uniform){
		jQuery(".uniform").uniform();
	}
}
/***jQuery initialization***/
google.setOnLoadCallback(function() {
	/* jQuery - Broken Image Handling */
	(function($) {
		 var hideFlashMessages = function()
		 {
				/*$('.tx-nfcflashmessage').fadeOut();	 */
		 }
		 
		$(document).ready(function(){
			/***error handling for not found images***/
			$("img").error(function(){
				$(this).hide();
			});
			flyOutMenu();
			/***slideable login***/
			login_initialHeight = '-169px';
			login_layerOpacity = '1.0';
			displaySlidableLogin(login_initialHeight,login_layerOpacity);
			/***close popup***/
			$('.'+closePopupClass).live('click', function(ev) {
				ev.preventDefault();
				closePopUp();
			});
			/***jqzoom***/
			initJQZoom();

			/***product image slider ***/
		  initProductImageSlider();
			/***product-box-links***/
			initProductBoxLinks();
			
			/***product rating form ***/
			initRatingForm();
			setTimeout(hideFlashMessages, 5000);

			/*** uniform ***/
			initUniform();
			/***jAnythingSlider***/
			initJAnythingSlider();

			/***fix columns heights***/
			jQuery('.fix-column-heights').fixColumnHeights({elementsSelector:'.box-special-middle',additionalHeight:0,setOnlyMinHeight:true});

			jQuery('.checkout_shoppingcart_parts').fixColumnHeights({elementsSelector:'.box-special-middle',additionalHeight:0,setOnlyMinHeight:true});

			initProductListCategoryText();
		});
		
		// packstation
		$('.packing-station-assume-btn').live('click',function(ev){
			openPopUpByContentId('#insert-packstation'); 
		});	
		
	})(jQuery);
});

