/*

verantwortlich für Design, Konzept & Realisierung: 
	
Polargold - Agentur für Kommunikation und Design 
Kleine Johannisstra§e 6 
20457 Hamburg 
	
E-Mail: info@polargold.de 
Website: http://www.polargold.de
	
*/

var digits = 3;

function makeNumber(num, size, prefix) { 
	prefix = (prefix) ? prefix : "0"; 
	var minus = (num < 0) ?"-" : "", result = (prefix == "0") ? minus : ""; 
	num = Math.abs(parseInt(num, 10));
	size -= ("" + num).length; 
	for(var i=1; i<=size; i++) {
		result += "" + prefix;
	}
	result += ((prefix != "0") ? minus: "") + num; 
	return result;s
}

function writeCounterDigits(element, value) {
	var digitsArray = value.split('');
	var e = $(element);
	for(var i=0; i<digits; i++) {
		var d = $('.digit-' + (i + 1), e);
		$(d).html('<img height="20" width="15" src="/images/counter/' + digitsArray[i] + '.gif" alt="' + digitsArray[i] + '" />');
	}
}

function checkReplacements() {
	// hide overlays when all flashs are loaded
	$('.form-overlay').css('display', 'none');
}

$(document).ready(function () {
	
	// preload counter images
	for(var i=0; i < 9; i++) {
		var l = '/images/counter/' + i + '.gif';
		$.ajax({ // preload image
			url: l
		});	
	}
	
	// show content
	$('body').addClass('js');
	$('#wrapper').show();
	
	// handle counter
 	$('.counter').each(function() {
		var c = $(this);
		// handle digits
		var state_normal = makeNumber(counter, digits);
		var state_decreased = makeNumber(counter - 1, digits);
		var element_start = $('#counter-start');
		var element_application = $('#counter-application');
		writeCounterDigits(element_start, state_normal);
		writeCounterDigits(element_application, state_decreased);
	});

	// do slider
    var $panels = $('#slider .scrollContainer > div');
    var $container = $('#slider .scrollContainer');
 
    // if false, we'll float all the panels left and fix the width 
    // of the container
    var horizontal = true;
 
    // float the panels left if we're going horizontal
    if (horizontal) {
        $panels.css({
            'float' : 'left',
            'position' : 'relative' // IE fix to ensure overflow is hidden
        });
 
        // calculate a new width for the container (so it holds all panels)
        $container.css('width', $panels[0].offsetWidth * $panels.length);
    }
 
    // collect the scroll object, at the same time apply the hidden overflow
    // to remove the default scrollbars that will appear
    var $scroll = $('#slider .scroll').css('overflow', 'hidden');
 
    // handle nav selection
    function selectNav() {
        $(this)
            .parents('ul:first')
                .find('a')
                    .removeClass('selected')
                .end()
            .end()
            .addClass('selected');
    }
 
    $('#slider .navigation').find('a').click(selectNav);
 
    // go find the navigation link that has this target and select the nav
    function trigger(data) {
        var el = $('#slider .navigation').find('a[href$="' + data.id + '"]').get(0);
        selectNav.call(el);
    }
 
    if (window.location.hash) {
        trigger({ id : window.location.hash.substr(1) });
    } else {
        $('ul.navigation a:first').click();
    }
 
    // offset is used to move to *exactly* the right place, since I'm using
    // padding on my example, I need to subtract the amount of padding to
    // the offset.  Try removing this to get a good idea of the effect
    var offset = parseInt((horizontal ? 
        $container.css('paddingTop') : 
        $container.css('paddingLeft')) 
        || 0) * -1;
 
 
    var scrollOptions = {
        target: $scroll, // the element that has the overflow
 
        // can be a selector which will be relative to the target
        items: $panels,
 
        // allow the scroll effect to run both directions
        axis: 'xy',
 
        onAfter: trigger, // our final callback
 
        offset: offset,
 
        // duration of the sliding effect
        duration: 1750,
 
        // easing - can be used with the easing plugin: 
        // http://gsgd.co.uk/sandbox/jquery/easing/
        easing: 'easeOutBack'
    };
 
    // apply serialScroll to the slider - we chose this plugin because it 
    // supports// the indexed next and previous scroll along with hooking 
    // in to our navigation.
    $('#slider').serialScroll(scrollOptions);
 
    // now apply localScroll to hook any other arbitrary links to trigger 
    // the effect
    $.localScroll(scrollOptions);
 
    // finally, if the URL has a hash, move the slider in to position, 
    // setting the duration to 1 because I don't want it to scroll in the
    // very first page load.  We don't always need this, but it ensures
    // the positioning is absolutely spot on when the pages loads.
    scrollOptions.duration = 1;
    $.localScroll.hash(scrollOptions);

	// handle resizing
	var initDimensions = function() {
		// resize
		var newWidth = $(window).width();
		$('#slider').width(newWidth);
		$('.scroll').width(newWidth);
		// calculate a new width for the container (so it holds all panels)
		$container.css('width', $panels[0].offsetWidth * $panels.length);
		// refresh
		window.location.hash = '#start';
	}
	initDimensions();
	$(window).resize(function() {
		initDimensions();
	});
	
	// handle helper in search form
	writeLabel = function(input) {
		if($(input).val() == '') {
			$(input).val($(input).prev('label').text()).addClass('help-active');
			$(input).bind('focus', function() {
				$(input).val('').removeClass('help-active');
			});
		}	
	}
	$('#application-form input.display-help').each(function() {
		if($(this).val() == '') {
			$(this).addClass('help-active').val($(this).prev('label').text());
		}
		$(this).bind('blur', function() {
			if($(this).val() == '') {
				$(this).val($(this).prev('label').text()).addClass('help-active');
			}
		});
		$(this).bind('focus', function() {
			if($(this).val() == $(this).prev('label').text()) {
				$(this).val('').removeClass('help-active');
			}
		});
	});
	
	/* handle submit buttons */
	$('#application-form button').mouseover(function(){
		$(this).addClass('hover');
	}).mouseout(function(){
		$(this).removeClass('hover');			
	});
	
	/* handle form */
	var opened = false;
	$('#application-form').bind('submit', function() {
		
		if(opened) {
			// do nothing if an overlay is opened
			return false;
		}
			
		// get fields
		var field_firstname = $('#firstname').val();
		var field_lastname = $('#lastname').val();
		var field_phone = $('#phone').val();
		var field_email = $('#email').val();
		var field_zip = $('#zip').val();
		var field_city = $('#city').val();
		var field_agreed = $('#agreed:checked').val();
		
		// validate
		var valid = true;
		if(field_firstname == '' || field_firstname == 'Vorname')
			valid = false;
		if(field_lastname == '' || field_lastname == 'Nachname')
			valid = false;
		if(field_phone == '' || field_phone == 'Telefon')
			valid = false;
		if(field_email == '' || field_email == 'E-Mail' || !(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(field_email)))
			valid = false;
		if(field_zip == '' || field_zip == 'PLZ')
			valid = false;
		if(field_city == '' || field_city == 'Ort')
			valid = false;
		if(field_agreed != '1')
			valid = false;
			
		//submit form
		if(valid) {
			// todo: ajax
			$.post(
				'/home', 
				{
					firstname: field_firstname, 
					lastname: field_lastname,
					phone: field_phone,
					email: field_email,
					zip: field_zip,
					city: field_city,
					agreed: field_agreed,
					ajax: '1'
				}, 
				function(data) {
					// handle counter
					counter--;
					var state_normal = makeNumber(counter - 1, digits);
					var element_start = $('#counter-start');
					writeCounterDigits(element_start, state_normal);
					var state_decreased = makeNumber(counter - 1, digits);
					var element_application = $('#counter-application');
					writeCounterDigits(element_application, state_decreased);
					// reset fields
					$('#firstname').val($('#firstname').prev('label').text()).addClass('help-active');
					$('#lastname').val($('#lastname').prev('label').text()).addClass('help-active');
					$('#phone').val($('#phone').prev('label').text()).addClass('help-active');
					$('#email').val($('#email').prev('label').text()).addClass('help-active');
					$('#zip').val($('#zip').prev('label').text()).addClass('help-active');
					$('#city').val($('#city').prev('label').text()).addClass('help-active');
					$("#agreed:checked").attr("checked", "");
					// debug
					//alert(data);
					
				}
			);
			// show success overlay
			$('#overlay-success').fadeIn('fast', function() {
			});
			opened = true;
		} else {
			// show error overlay
			$('#overlay-error').fadeIn('fast', function() {
			});
			opened = true;
		}
		return false;
	});
	
	$('a.close-box').click(function() {
		if(opened) {
			$('.form-overlay').fadeOut('fast', function() {
				opened = false;	
			});
		}
		return false;
	});
	
	// fix safari list view
	if($.browser.safari) {
		$('.sIFR-hasFlash ul.content li').css('margin-bottom', '17px');
	}
	
	setTimeout('checkReplacements()', 1000);
	
});
