/*
 * g*Sales
 * http://www.gsales.de
 *
 * Author: Gedankengut.de
 * Date: 2010-06
 */

var defaultPrice = 99;
var defaultTaxRate = 19;

// Anchors
var currentFaq = '';
var currentFile = document.location.toString();
if (currentFile.match('#')) {
	currentFaq = currentFile.split('#')[1];
}

$(document).ready(function(){
	// Highlight Navitem
	$('#navigation ul li:last a').addClass('glow');
	// Scroller
	var screenCount = $(".screenshots .items img").length;
	var randomMax = screenCount+1;
	var api = $(".screenshots").scrollable({
		circular: true,
		onBeforeSeek: function(){
			$('#headerScreenDesc').hide();
		},
		onSeek: function(){
			$('#headerScreenDesc').html($('.items img').eq(this.getIndex()+1).attr('longdesc'));
			$('#headerScreenDesc').fadeIn();
		}
	}).autoscroll({ interval: 8000, autoplay: true, api: true });
	var randomItem = Math.floor(Math.random()*randomMax);
	if(screenCount > 0) api.seekTo(randomItem);
	// Check Empty Inputs
	$('form').submit(function(e){
		var errors = false;
		$(':input.mandatory',this).each(function(){
			if(!$(this).val()){
				errors = true;
				$(this).addClass('error');
			} else {
				$(this).removeClass('error');
			}
		});
		$(':input.checkEmail',this).each(function(){
			if(!checkEmail($(this))){
				errors = true;
				$(this).addClass('error');
			} else {
				$(this).removeClass('error');
			}
		});
		if(errors) e.preventDefault();
	});
	// Newsletter ajax form
	$(".newsletterForm").submit(function(e){
		e.preventDefault();
	    
	    var formAction = $(this).attr("action");
	    var id = $(this).attr("id");
	    var emailId = id + "-" + id;
	    var str = $(this).serialize();
	    var serialized = str + "&action=" + formAction;
	    var formRef = $(this);
	    
	    $.ajax({
	    	url: gsPath + "/template/js/campaignMonitorProxy.php",
	    	type: "POST",
	    	data: serialized,
	    	success: function(data){
	    		if (data.search(/invalid/i) != -1) {
	    			$('#'+emailId).addClass('error');
	    		} else {
	    			$(formRef).hide();
	    			$('#'+id+'Confirm').slideDown('slow');
	    			$('#'+id+'Confirm').tabIndex = -1;
	    			$('#'+id+'Confirm').focus();
	    		}
	    	}
	    });
	});
	// FAQ
	$('.faqBox').each(function(){
		var boxRef = $(this);
		$('.question',boxRef).click(function(e){
			e.preventDefault();
			$('.answer',boxRef).slideToggle('fast');
		});
	});
	if(currentFaq != ''){
		$('#'+currentFaq).show();
		$('#'+currentFaq).parent().addClass('highlight');
		$('#'+currentFaq).parent().hover(function(){ $(this).removeClass('highlight'); });
		$('#'+currentFaq).focus();
	}
	// Numeric PLZ
	$('#orderForm #plz').numeric();
	// Discount calculator
	$('#orderForm #posCount').numeric();
	if(!$('#orderForm #posCount').val()) $('#orderForm #posCount').val(1);
	setUnitPrice();
	setTaxRate();
	setTotals();
	$('#orderForm #posCount').keyup(function(){
		setUnitPrice();
		setTotals();
	});
	$('#orderForm #land').change(function(){
		setTaxRate();
		setTotals();
	});
	$('#orderForm #land').keyup(function(){
		$('#orderForm #land').trigger('change');
	});
	$('#orderForm #ustid').keyup(function(){
		$('#orderForm #land').trigger('change');
	});
	$('#orderForm #firma').keyup(function(){
		$('#orderForm #land').trigger('change');
	});
	// Select input text onclick
	$('.clickSelect').click(function(){
		$(this).select();
	});
});

// Check E-Mail
function checkEmail(emailRef) { 
	var pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var emailVal = $(emailRef).val();
	return pattern.test(emailVal);
}
	
// Discount calculator functions
function getDiscountPrice(count){
	var step = Math.floor(count/5);
	if(step == 0) return defaultPrice;
	else return Math.round(defaultPrice*(1-(step/100)));
}
function getTaxRate(){
	var isCompany = false;
	if($.trim($('#orderForm #firma').val())!='') isCompany = true;
	if($('#orderForm #land').val() == 'de') return defaultTaxRate;
						// not swiss								// EU									// private					// company, no ustid
	else if( $('#orderForm #land').val()!='ch' && $('#orderForm #land option:selected').hasClass('eu') && (!isCompany || (isCompany && $.trim($('#orderForm #ustid').val())=='')) ) return defaultTaxRate;
	else return 0;
}
function setUnitPrice(){
	$('#orderForm #unitPrice').html(getDiscountPrice($('#orderForm #posCount').val()));
}
function setTaxRate(){
	$('#orderForm #tax').html(getTaxRate());
}
function setTotals(){
	var sum = ( $('#orderForm #posCount').val() * getDiscountPrice($('#orderForm #posCount').val()) * ((100+getTaxRate())/100) );
	$('#orderForm #sum').html(deNumFormat(sum));
}

// Format numbers
function deNumFormat(val){
	return numFormat(val,2,',','.');
}
function numFormat(n,s,d,t){
	n=n.toFixed(s);	
	z=n.split('.');
	g=z[0].split('').reverse();
	g=g.join('');
	s='';
	for (var i=1;i<=g.length;i++){
		s+=g.charAt(i-1);
		if(i%3==0&&i!=g.length)s+=t;
	}
	g=s.split('').reverse();
	de='';
	if(z[1])de=d+z[1];
	g=g.join('')+de;
	return g;
}