// submitFunction ??
// Activation for GV System
function submitFunction() {
    submitter = 1;
}

// JavaScript Document
function add_opensearch(opensearch_link, message) {

	if (navigator.userAgent.match(/MSIE [7]\./) || navigator.userAgent.match(/Firefox/)) {
		window.external.AddSearchProvider(opensearch_link);
	} else {
		alert(message);
	}
}

/* --------------------------------------------------------------
GMLiveSearch
-------------------------------------------------------------- */
function GMLiveSearch()
{
	$('#mode1_search_cell_form').append('<div id="live_search_container"></div>');
	
	$('#quick_find_input').keyup(function(event) 
	{
		var needle = encodeURIComponent( $('#quick_find_input').attr('value') );
		if(needle.length > 2)
		{
			$('#live_search_container').load('live_search.php?needle=' + needle, {});
		} else {
			$('#live_search_container').html('');
		}
	});
}

/* --------------------------------------------------------------
PayPal Express
-------------------------------------------------------------- */
function check_paypal_form(){
	var error = '';
	var check = true;
	$('.accept_box_checkbox input').each(function(){
		if($(this).attr('type') == 'checkbox'){
			if($(this).attr('checked') != true){
				if($(this).attr('name') == 'withdrawal') error = error + 'Sofern Sie unsere Allgemeinen Geschäftsbedingungen nicht akzeptieren,\n können wir Ihre Bestellung leider nicht entgegennehmen! \n\n';
				else if($(this).attr('name') == 'conditions') error = error + 'Sofern Sie unser Wiederrufsrecht nicht akzeptieren,\n können wir Ihre Bestellung leider nicht entgegennehmen! \n\n';
				check = false;
			} 
		}		
	});
	
	if(error != '') alert(error);
	return check;
}

/* --------------------------------------------------------------
GMOrderQuantityChecker
-------------------------------------------------------------- */
function GMOrderQuantityChecker()
{
	
	this.check = function(){
		var products_id = $('#gm_products_id').val();
		var qty = $('#gm_attr_calc_qty').val();

		var html = jQuery.ajax({
			data: 'id=' + products_id + '&qty=' + qty,
			url: 'gm_ajax.php?module=order_quantity_checker',
			type: "GET",
			async: false}).responseText;

		$('#gm_checker_error_' + products_id).html('<div class="details_checker_error">' + html + '</div>');
		if(html == '') return true;
		else return false;
	}
	
	this.check_listing = function(products_id){
		var qty = $('#gm_attr_calc_qty_' + products_id).val();

		var html = jQuery.ajax({
			data: 		'id=' + products_id + '&qty=' + qty,
			url: 		'gm_ajax.php?module=order_quantity_checker',
			type: 		"GET",
			async: false}).responseText;

		$('#gm_checker_error_' + products_id).html(html);
		if(html == '') return true;
		else return false;
	}
	
	this.check_cart = function(){
		var products_id = '';
		var qty = '';
		var inputs = [];
		var html = '';
		var j = 0;
		var no_error = true;
		
		$('.gm_cart_data').each(function(){
			inputs.push(escape(this.value));
		});
		
		for(i = 0; i < inputs.length; i = i+2) {
			
			qty = inputs[i];
			products_id = inputs[i+1];			
			
			products_id_copy = products_id;
			products_id_copy = products_id_copy.replace(/%7B/g, "_");
			products_id_copy = products_id_copy.replace(/%7D/g, "_");
			products_id_copy = products_id_copy.replace(/{/g, "_");
			products_id_copy = products_id_copy.replace(/}/g, "_");
			
			if($('#gm_delete_product_' + products_id_copy).attr('checked') != true){				
				j = products_id.indexOf('{');
				if(j == -1) j = products_id.indexOf('%');
				if(j != -1) products_id = products_id.slice(0, j);			
				html = jQuery.ajax({
					data:	'id=' + products_id + '&qty=' + qty,
					url: 	'gm_ajax.php?module=order_quantity_checker',
					type:	"GET",
					async: false}).responseText;
				$('#gm_checker_error_' + products_id_copy).html(html);
				if(html != '') no_error = false;
			}
			
		}
		
		return no_error;
	}
	
	
	this.check_wishlist = function(){
		var products_id = '';
		var qty = '';
		var inputs = [];
		var html = '';
		var j = 0;
		var no_error = true;
		
		$('.gm_cart_data').each(function(){
			inputs.push(escape(this.value));
		});
		
		for(i = 0; i < inputs.length; i = i+2){
			
			qty = inputs[i];
			products_id = inputs[i+1];			
			
			products_id_copy = products_id;
			products_id_copy = products_id_copy.replace(/%7B/g, "_");
			products_id_copy = products_id_copy.replace(/%7D/g, "_");
			products_id_copy = products_id_copy.replace(/{/g, "_");
			products_id_copy = products_id_copy.replace(/}/g, "_");
			
			j = products_id.indexOf('{');
			if(j == -1) j = products_id.indexOf('%');
			if(j != -1) products_id = products_id.slice(0, j);			
			html = jQuery.ajax({
													data:	'id=' + products_id + '&qty=' + qty,
													url: 	'gm_ajax.php?module=order_quantity_checker',
													type:	"GET",
													async: false}).responseText;
			$('#gm_checker_error_' + products_id_copy).html(html);
			if(html != '') no_error = false;
			
		}
		
		return no_error;
	}
	
}

/* --------------------------------------------------------------
GMAttributesCalculator
-------------------------------------------------------------- */
function GMAttributesCalculator()
{
	
	this.calculate = function()
	{
		$.ajax({
			type: "POST",
			url: 'attributes_calculator.php',
			data: $("#cart_quantity").serialize(),
			success: function(updated_price)
			{
				$("#gm_attr_calc_price").html('<div class="normalPrice">'+updated_price+'</div>');
			}
		});
	}
	
	this.calculate_listing = function(gm_id)
	{
		var inputs = [];
		
		$('#gm_add_to_cart_' + gm_id + ' .gm_listing_form').each(function()
		{
				if($(this).attr('type') == 'radio')
				{
					if($(this).attr('checked') == true) inputs.push(this.name + '=' + escape(this.value));
				} else
				{
					inputs.push(this.name + '=' + escape(this.value));
				}
			}
		);
		
		var updated_price = jQuery.ajax({
			data: inputs.join('&') + '&products_id=' + gm_id, 
			url: 'attributes_calculator.php', 
			type: "POST", 
			async: false}).responseText;

		$("#gm_attr_calc_price").html('<div class="normalPrice">'+updated_price+'</div>');

	}
}


$(document).ready(function()
{	
	// TAB FUNCTION
	$(function() {
		$("#tabs").tabs();
		$("#special_tabs").tabs();
		$("#new_tabs").tabs();
	});
		
	// LIVE SEARCH - HIDE WHEN CLICK OUTSIDE
	var gmLiveSearch = new GMLiveSearch();
	$(document).click(function() {
		$('#live_search_container').html('');
    });
	
	// DIALOG BOX - TEXT CONTENT
	var $dialog = $('<div></div>')
		.dialog({
			autoOpen: false,
			width: 769,
			height: 400,
			closeText: 'Schliessen',
			resizable: 0,
			position: ['center',200]
		});
	$('.opener').click(function()
	{
		$.ajax({
			type: "GET",
			url: this.title + ".php",
			success: function(msg)
			{
				var splitter = msg.split("#|#");
				$dialog.dialog({
					title: splitter[0]
				});
				$dialog.html( splitter[1] );
			}
		});		
		$dialog.dialog('open');
		// prevent the default action, e.g., following a link
		return false;
	});
	
	// DIALOG BOX - PICTURE CONTENT
	var $picture = $('<div></div>')
		.dialog({
			autoOpen: false,
			width: 900,
			height: 700,
			closeText: 'Schliessen',
			resizable: 0,
			position: ['center',100]
		});
	$('.openImage').click(function()
	{
		// INIT
		$picture.html('');
		$.ajax({
			type: "GET",
			data: "&products_image=" + $(this).attr('id'),
			url: "openImage.php",
			success: function(msg)
			{
				var splitter = msg.split("#|#");
				$picture.dialog({
					title: splitter[0]
				});
				$picture.html( splitter[1] );			
			}
		});		
		$picture.dialog('open');
		// prevent the default action, e.g., following a link
		return false;
	});
	$picture.dialog('.dialog_change_image').click(function(event)
	{
		var $target = $(event.target).parent();
		if( $target.attr('id') != "")		
		$('#main_image').attr('src', $target.attr('id'));
	});
	
	// DIALOG BOX - PRINT CONTENT
	var $print = $('<div></div>')
		.dialog({
			autoOpen: false,
			width: 800,
			height: 600,
			closeText: 'Schliessen',
			resizable: 0,
			position: ['center',100]
		});	
	$(".product_info_link").click(function()
	{
		$.ajax({
			type: "GET",
			data: "products_id=" + $("#gm_products_id").attr('value'),
			url: "print_product_info.php",
			success: function(msg)
			{
				var splitter = msg.split("#|#");
				$print.dialog({
					title: splitter[0]
				});
				$print.html( splitter[1] );
				
				$('#print_output').printElement();
			}		
		});
		$print.dialog('open');
		
		
		// prevent the default action, e.g., following a link
		return false;		
	});
	
	// DIALOG BOX - VIDEO CONTENT
	var $videobox = $('<div></div>')
		.video({
			autoOpen: false,
			width: 800,
			height: 600,
			closeText: 'Schliessen',
			resizable: 0,
			position: ['center',100]
		});
	$('.openVideo').click(function()
	{
		// INIT
		$videobox.html('');
		$.ajax({
			type: "GET",
			data: "&videoID=" + $(this).attr('id') + "&videoTitle=" + $(this).attr('title'),
			url: "openVideo.php",
			success: function(msg)
			{
				var splitter = msg.split("#|#");
				$videobox.video({
					title: splitter[0]
				});
				$videobox.html( splitter[1] );			
			}
		});		
		$videobox.video('open');
		// prevent the default action, e.g., following a link
		return false;
	});

	$('.openVideo_Mov').click(function()
	{
		// INIT
		$videobox.html('');
		$.ajax({
			type: "GET",
			data: "&videoParams=" + $(this).attr('id') + "&videoTitle=" + $(this).attr('title'),
			url: "openVideo_mov.php",
			success: function(msg)
			{
				var splitter = msg.split("#|#");
				$videobox.video({
					title: splitter[0]
				});
				$videobox.html( splitter[1] );			
			}
		});		
		$videobox.video('open');
		// prevent the default action, e.g., following a link
		return false;
	});		

	
	// UPDATE PRODUCTS PRICE FROM ATTRIBUTES
	$(".gm_attr_calc_input").click(function(){
			var attr_calc = new GMAttributesCalculator();
			attr_calc.calculate();
		}
	);
	
	// SORT PRODUCTS
	$('#sort_name').click(function() {
		var sort_type = $('input#sort_name_by').val();
		var sort_url = $('input#current_category').val() + "?sort_name=" + sort_type;
		$('#filter_products').attr("action", sort_url);
        $('#filter_products').submit();
	});
	$('#sort_price').click(function() {
		var sort_type = $('input#sort_price_by').val();
		var sort_url = $('input#current_category').val() + "?sort_price=" + sort_type;
		$('#filter_products').attr("action", sort_url);
        $('#filter_products').submit();
	});
	$('#sort_manu').change(function() {
		$('#sort_manu option:selected').each(function()
		{
			sort_type = $(this).val();
		});
		var sort_url = $('input#current_category').val() + "?sort_manu=" + sort_type;
		$('#filter_products').attr("action", sort_url);
        $('#filter_products').submit();
	});
	$('#sort_price_section').change(function()
	{
		window.location.href = $(this).val();
	
	});
				
	
	// ADDITIONAL PRODUCTS SCROLLER
	$(function() {
		//scrollpane parts
		var scrollPane = $('.scroll-pane');
		//console.log(scrollPane);
		var scrollContent = $('.scroll-content');
		
		//build slider
		var scrollbar = $(".scroll-bar").slider({
			slide:function(e, ui){
				if( scrollContent.width() > scrollPane.width() ){ scrollContent.css('margin-left', Math.round( ui.value / 100 * ( scrollPane.width() - scrollContent.width() )) + 'px'); }
				else { scrollContent.css('margin-left', 0); }
			}
		});
		
		//append icon to handle
		var handleHelper = scrollbar.find('.ui-slider-handle')
		.mousedown(function(){
			scrollbar.width( handleHelper.width() );
		})
		.mouseup(function(){
			scrollbar.width( '100%' );
		})
		.append('<img src="templates/gambio/img/icon_arrow_left_red.gif" alt="Mehr Artikel sehen" title="Mehr Artikel sehen" class="scrollbar-left-icon" />')
		.append('<p class="scrollbar-text">Mehr Artikel</p>')
		.append('<img src="templates/gambio/img/icon_arrow_right_red.gif" alt="Mehr Artikel sehen" title="Mehr Artikel sehen" class="scrollbar-right-icon" />')		
		.wrap('<div class="ui-handle-helper-parent"></div>').parent();
		
		//change overflow to hidden now that slider handles the scrolling
		scrollPane.css('overflow','hidden');
		
		//size scrollbar and handle proportionally to scroll distance
		function sizeScrollbar(){
			var remainder = scrollContent.width() - scrollPane.width();
			var proportion = remainder / scrollContent.width();					
			var handleSize = scrollPane.width() - (proportion * scrollPane.width());
			scrollbar.find('.ui-slider-handle').css({
				width: handleSize,
				'margin-left': -handleSize/2
			});
			// Left Icon
			scrollbar.find('.scrollbar-left-icon').css({
				'float': 'left'
			});
			// Right Icon
			scrollbar.find('.scrollbar-right-icon').css({
				'float': 'right'
			});
			// Text
			scrollbar.find('.scrollbar-text').css({
				'float': 'left',
				'width': handleSize-42,
				'text-align': 'center'
			});						
			handleHelper.width('').width( scrollbar.width() - handleSize);
		}
		
		//reset slider value based on scroll content position
		function resetValue(){
			var remainder = scrollPane.width() - scrollContent.width();
			var leftVal = scrollContent.css('margin-left') == 'auto' ? 0 : parseInt(scrollContent.css('margin-left'));
			var percentage = Math.round(leftVal / remainder * 100);
			scrollbar.slider("value", percentage);
		}
		//if the slider is 100% and window gets larger, reveal content
		function reflowContent(){
				var showing = scrollContent.width() + parseInt( scrollContent.css('margin-left') );
				var gap = scrollPane.width() - showing;
				if(gap > 0){
					scrollContent.css('margin-left', parseInt( scrollContent.css('margin-left') ) + gap);
				}
		}
		
		//change handle position on window resize
		$(window)
		.resize(function(){
				resetValue();
				sizeScrollbar();
				reflowContent();
		});
		//init scrollbar size
		setTimeout(sizeScrollbar,10);//safari wants a timeout
	});
	
	//landingpages magnifier icon
	$('.magnifier').click(function() {
		window.location = $(this).next('a').attr('href');
	});
	
	//landingpages magnifier icon
	$('#product_info #video_container .video_box:nth-child(4n)').each(function() {
		$(this).css({
			'margin-right':'0px'
		});
	});			
	
	/**
	 * box-info horizontal boxes
	 */
	$('.horizontal-box .box-list-tabs .box-list-head').hover(function() {
		if($(this).hasClass('clickable')) {
			$(this).css({
				'background-image':'url("templates/gambio/img/box_header_bg_02.gif")'
			});
		}
	},function() {
		if($(this).hasClass('clickable')) {
			$(this).css({
				'background-image':'url("templates/gambio/img/box_header_bg_05.gif")'
			});
		}
	}).click(function() {
		$('.horizontal-box .box-list-tabs').each(function() {
			$(this).find('.box-list-body').css({'display':'none'});
			$(this).find('.box-list-head').css({'background-image':'url("templates/gambio/img/box_header_bg_05.gif")'});
			$(this).find('.box-list-head').addClass('clickable');
		});
		$(this).parent().find('.box-list-body').css({'display':'block'});
		$(this).removeClass('clickable');
		$(this).css({'background-image':'url("templates/gambio/img/box_header_bg_02.gif")'});		
	});
	
	/**
	 * box-info limited opener
	 */
	$('.box-list-opener').click(function(event) {		
		var element = event.target.id.substring(0,(event.target.id.length-7));
		var childrens = $('#'+element+' ul.box-list').children().length;
		var limit = $('#'+element+' ul.box-list').attr('id');		
		if(!$('#'+element+' .box-list-opener').hasClass('open')) {
			$('#'+element+' ul.box-list .box-list-item').slice(limit, childrens).removeClass('hidden');
			$('#'+element+' .box-list-opener').addClass('open');			
			$('#'+element+' .box-list-opener a').html('Box schliessen');
		} else if($('#'+element+' .box-list-opener').hasClass('open')) {
			$('#'+element+' ul.box-list .box-list-item').slice(limit, childrens).addClass('hidden');
			$('#'+element+' .box-list-opener').removeClass('open');
			$('#'+element+' .box-list-opener a').html('Weitere Infos anzeigen');			
		}
		$('#'+element+' .box-list-body').css({'display':'none'});
		$('#'+element+' .box-list-head').addClass('clickable');
		$('#'+element+' .box-list-head').css({'background-image':'url("templates/gambio/img/box_header_bg_05.gif")'});
	});
	
	$('.catslider-elements .catslider-element').each(function() {
		$(this).css({'display':'none'});
	});
	
	$('.catslider-elements').find('.catslider-element:first').css({'display':'block'}).addClass('active');
	$('.catslider-nav').find('.catslider-nav-element:first').addClass('active');	
	
	$('.catslider-nav-element a').click(function(event) {
		$('.catslider-element').each(function() {
			$(this).css({'display':'none'});
		});
		$('.catslider-nav-element a').each(function() {
			$(this).parent().parent().removeClass('active');
		});		
		$('#'+event.target.id+'-slice').css({'display':'block'}).addClass('active');;
		$(this).parent().parent().addClass('active');
		

		clearInterval(catsliderloop);
	});
	$('.catslider-element').hover(function() {
		$(this).find('a:first').css({'color':'#CA2127'});
	},function() {
		$(this).find('a:first').css({'color':'#464646'});
	}).click(function() {
		window.location = $(this).find('a:first').attr('href');
	});
	$('.box-startpage').hover(function() {
		linkCount = $(this).find('.box-info-links').children().length;
		if(linkCount == 1) $(this).find('a:first').css({'text-decoration':'underline'});
		else $(this).css({'cursor':'default'});
	},function() {
		linkCount = $(this).find('.box-info-links').children().length;
		if(linkCount == 1) $(this).find('a:first').css({'text-decoration':'none'});
	}).click(function() {
		linkCount = $(this).find('.box-info-links').children().length;
		if(linkCount == 1) window.location = $(this).find('a.box-forwardlink').attr('href');
	});
	
	$('#oms .oms-slider .oms-block').each(function() {
		$(this).css({'display':'none'});
	});
	$('#oms .oms-slider .oms-block:first').css({'display':'block'});
		
	$('.oms-link').click(function(event) {
		$('#oms .oms-slider .oms-block').each(function() {
			$(this).css({'display':'none'});
		});
		var id = Number(event.target.id.substring((event.target.id.length-1), (event.target.id.length)));
		$('#oms .oms-slider .oms-block:eq('+id+')').css({'display':'block'});
		if($('.oms-slider').children().length > (id+1)) {
			$('.oms-link').attr('id', 'oms-block-nav-'+(id+1));
			$('.oms-link').text('Weiter lesen...');
		} else {
			$('.oms-link').attr('id', 'oms-block-nav-0');
			$('.oms-link').text('Zum Anfang');
		}
	});
	$('#oms-block-location').css({'display':'none'});
	
	$('#open-location').toggle(function() {
		$('#oms-block-location').css({'display':'block'});
	},function() {
		$('#oms-block-location').css({'display':'none'});
	});
	
	$('#sp-categories .box-list-item').hover(function() {
		$(this).find('a:first').css({'text-decoration':'underline'});
	},function() {
		$(this).find('a:first').css({'text-decoration':'none'});
	}).click(function() {
		window.location = $(this).find('a:first').attr('href');
	});
	
	var catslidercounter = 0;
	var catsliderElements = $('.catslider-elements').children().length;
		
	catsliderloop = setInterval(function() {
		catslidercounter++;
		if(catslidercounter == catsliderElements) catslidercounter = 0;
		$('.catslider-elements .catslider-element').each(function() {
			$(this).css({'display':'none'}).removeClass('active');
		});
		$('.catslider-elements .catslider-element:eq('+catslidercounter+')').css({'display':'block'}).addClass('active');		
		$('.catslider-nav .catslider-nav-element').each(function() {
			$(this).removeClass('active');
		});
		$('.catslider-nav .catslider-nav-element:eq('+catslidercounter+')').css({'display':'block'}).addClass('active');
	}, 5000);
	
	$('#sp-box-info-wiki .box-info-image').css({'top':'-10px'});
	$('#sp-box-info-conditions .box-info-image').css({'top':'-10px'});
	$('#sp-box-info-gafe .box-info-image').css({'top':'-12px','right':'8px'});
	/**
	 * outgoing clickcounter
	 * substring:
	 product-info-
	 footer-
	 * #2. category
	 * #3. action
	 * #4. value
	 */
	 $('a.footer_social_link').click(function() {

		_gaq.push(['_trackEvent', 'socials-outgoing', 'footer', $(this).attr('id').substring(7, $(this).attr('id').length)]);
	 });
	 $('.product-info_social_link').click(function() {
	
		_gaq.push(['_trackEvent', 'socials-outgoing', 'product-info', $(this).attr('id').substring(13, $(this).attr('id').length)]);
	 });
	
	/**
	 * infocenter
	 */	
	$('.infocenter ul li.box-list-item').hover(function() {
		$(this).find('a:first').css({'text-decoration':'underline'});
	},function() {
		$(this).find('a:first').css({'text-decoration':'none'});		
	}).click(function() {
		window.location = $(this).find('a:first').attr('href');	
	});
	
	/**
	 * infocenter
	 */	
	$('#box-additional-info').hover(function() {
		$(this).find('a:first').css({'text-decoration':'underline'});
	},function() {
		$(this).find('a:first').css({'text-decoration':'none'});		
	}).click(function() {
		window.location = $(this).find('a:first').attr('href');	
	});
	
	/**
	 * hover function li.box-list-item
	 */	
	$('.slider li.box-list-item').hover(function() {
		$(this).find('a:first').css({'text-decoration':'underline'});
	},function() {
		$(this).find('a:first').css({'text-decoration':'none'});		
	}).click(function(event) {
		if(event.target.className!= "shipping-link") {
			window.location = $(this).find('a.product-link').attr('href');
		}
	});	
	
	
	/**
	 * hover function li.box-list-item
	 */		
	$('#oms .box-list-item, .categories_description .box-list-item').hover(function() {
		$(this).find('a:first').css({'text-decoration':'underline'});
	},function() {
		$(this).find('a:first').css({'text-decoration':'none'});
	}).click(function() {
		window.location = $(this).find('a:first').attr('href');
	});
	
	/**
	 * hover function product_info special button
	 */	
	$('#product_listing .product_button_installation, #product_info .product_button_installation').hover(function() {
		$(this).attr('src', 'images/icons/icon_installation-hover.png'); 
	},function() {
		$(this).attr('src', 'images/icons/icon_installation.png'); 		
	});			 	 		
});
