/* DOCUMENT READY */
$(document).ready(function()
{
	/* COMMON INIT */
	initCommon();
	
	/* PAGE DEPENDENT */
	switch(pagedata.name)
	{
		case 'home':
			initHome();
			break;
		case 'request':
			initRequest();
			break;
		case 'order':
			initOrder();
			break;
	}
});


/* VARIABLES */
var pics = new Array();
var moveCount = 5;


/* INIT COMMON */
initCommon = function()
{
	/* SET INFIELD LABELS */
    $('#login label').inFieldLabels({
    	fadeOpacity:0
    });
    
	/* REST */
	$('#countries > ul').hide();
	
	$('#countries a:lt(2)').mouseover(function(){
		$('#countries > ul').fadeIn(300);
	});
	
	$('#countries > ul').mouseleave(function(){
		$('#countries > ul').fadeOut(300);
	});
	
	$('#pictures > div > a').showPic();
}


/* INIT HOME */
initHome = function()
{
	
	/* PICTURE SLIDER */
	
	/* CLICK PREV BUTTON */
	$(".gallery a.control.prev").click(function()
	{
		gallerySlide(this);
		
		return false;
	});
	
	/* CLICK NEXT BUTTON */
	$(".gallery a.control.next").click(function(){
		gallerySlide(this);
		
		return false;
	});
	
	/* SET IMAGE POPUP FOR SLIDER AND VISUAL */
	$('.product > .content > .visual > a').showPic();
    $('.gallery > ul > li > a').showPic();
    
    
    
    /* CLICK SPECS BUTTON */
    $('#showSpecs').click(function(){
    	showSpecs();
    });
    
    
    
    /* SHOW VIDEO DIALOG */
    $('a.showVid').click(function(){
    	/* GET URL */
    	link = $(this).attr('href');
    	
    	/* SHOW VIDEO */
    	showVid(link);
    	
    	return false;
    });
    
    
    /* SHOW AUTO VIDEO */
    if(focus_video_url!=''){
    	showVid(focus_video_url);
    }
}


/* INIT REQUEST */
initRequest = function()
{
	/* VARIABLES */
	var companyRequired = false;
	var vatRequired = false;
	var firstnameRequired = true;
	var lastnameRequired = true;

	/* BIND USERTYPE CHANGE */
	$('#field_usertype').change(function(){
	
		/* GET VALUE */
		type = $(this).val();
		
		/* CHECK VALUE */
		if(type=='part'){
			/* HIDE & EMPTY FIELDS */
			$('#field_company').hide();
			$('#field_company').val('');
			$('#field_vat').hide();
			$('#field_vat').val('');
			
			/* SHOW FIELDS */
			$('#field_firstname').show();
			$('#field_lastname').show();
		} else {
			/* HIDE & EMPTY FIELDS */
			$('#field_firstname').hide();
			$('#field_firstname').val('');
			$('#field_lastname').hide();
			$('#field_lastname').val('');
			
			/* SHOW FIELDS */
			$('#field_company').show();
			$('#field_vat').show();
		}
		
		/* $("#request_form").removeAttrs("required"); */
	});
	
	/* VALIDATIONS */
	$("#request_form").validate({
		focusInvalid: false,
		/* RULES */
		rules: {
			firstname: {
				required: true
			},
			lastname: {
				required: true
			},
			company: {
				required: false
			},
			vat: {
				required: false
			},
			email: {
				required: true,
				email:true
			},
			address: {
				required: true
			},
			pc_city: {
				required: true
			}
		},
		/* MESSAGES */
		messages: {
			firstname: '',
			lastname: '',
			company: '',
			vat: '',
			email: '',
			address: '',
			pc_city: ''
		},
		/* INVALID HANDLER */
		invalidHandler: function(e, validator) {
            var errors = validator.numberOfInvalids();
            
            if (errors)
                $("#form_error").show();
            else
                $("#form_error").hide();
        },
        /* SUBMIT HANDLER */
        submitHandler: function() {
            $("#form_error").hide();
        }
	});
	
	/* SENDFUNCTION CONTACTFORM */
	$('#request_form').submit(function(){
		/* CHECK USERTYPE */
		type = $('#field_usertype').val();
		
		// GET VALIDATION SETTINGS
     	var settings = $('#request_form').validate().settings;
     	
		// CHECK VALUE
		if(type=='part'){
		
			// MODIFY SETTINGS
			$.extend(settings, {
				rules: {
					// ADD
					"firstname": {
						required: true
					}, 
					"lastname": {
						required: true
					},
					"company": {
						required: false
					},
					"vat": {
						required: false
					},
					"email": {
						required: true,
						email:true
					},
					"address": {
						required: true
					},
					"pc_city": {
						required: true
					}
				}
			});
		}else{
		
			// MODIFY SETTINGS
			$.extend(settings, {
				rules: {
					// ADD
					"firstname": {
						required: false
					}, 
					"lastname": {
						required: false
					},
					"company": {
						required: true
					},
					"vat": {
						required: true
					},
					"email": {
						required: true,
						email:true
					},
					"address": {
						required: true
					},
					"pc_city": {
						required: true
					}
				}
			});
		}
		
		if($(this).valid()){
			$('#request_form').load('/'+pagedata.url+'/a/request', $(this).serializeArray());
		}
		
		return false;
	})
}


/* GALLERY SLIDE */
gallerySlide = function(button)
{
	/* GET BUTTON TYPE */
	actionType = $(button).attr('class').split(' ').slice(-1); ;
	
	/* GET GALLERY CONTAINER */
	galleryContainer = $(button).parent();
	galleryList = galleryContainer.children('ul');
	
	/* VARIABLES */
	totalImages = galleryList.find('li').length;
	imageWidth = galleryList.find('li:first').outerWidth(true);
	totalWidth = imageWidth * totalImages;
	
	visibleImages = Math.round(galleryContainer.width() / imageWidth);
	visibleWidth = visibleImages * imageWidth;
	stopPosition = (visibleWidth - totalWidth);
	
	/* REPOSITION */
	
	if(actionType=='prev' && galleryList.position().left < 0 && !galleryList.is(":animated")){
		if(Math.abs(galleryList.position().left) < imageWidth*moveCount)
			moveWidth = Math.abs(galleryList.position().left);
		else
			moveWidth = imageWidth*moveCount;
		
		galleryList.animate({left : "+=" + moveWidth + "px"}, function(){
			/* CHECK IF BUTTONS NEEDS TO BE HIDDEN */
			prevButton = galleryContainer.children('a.control.prev');
			nextButton = galleryContainer.children('a.control.next');
			
			if(galleryList.position().left == 0 && prevButton.is(':visible'))
				prevButton.hide();
			
			if(galleryList.position().left > stopPosition && !nextButton.is(':visible'))
				nextButton.show();
		});
	}
	
	if(actionType=='next' && galleryList.position().left > stopPosition && !galleryList.is(":animated")){
		positionDiff = galleryList.position().left - stopPosition;
	
		if(positionDiff < imageWidth*moveCount)
			moveWidth = positionDiff;
		else
			moveWidth = imageWidth*moveCount;
		
		galleryList.animate({left : "-=" + moveWidth + "px"}, function(){
			/* CHECK IF BUTTONS NEEDS TO BE HIDDEN */
			prevButton = galleryContainer.children('a.control.prev');
			nextButton = galleryContainer.children('a.control.next');
			
			if(galleryList.position().left != 0 && !prevButton.is(':visible'))
				prevButton.show();
			
			if(galleryList.position().left == stopPosition && nextButton.is(':visible'))
				nextButton.hide();
		});
	}
}


jQuery.fn.showPic = function()
{	
	return this.each(function()
	{		
		$(this).click(function()
		{
			$('#vidWindow').remove();
			$('#picWindow').remove();
			$('#specsWindow').remove();
			
			if($(currentImage).parent('li').length)
			{
				$('#videoplayer').hide();
			}
			
			var picWindow = $('<div id="picWindow">');
			
			closePicWindow = function()
			{
				$(picWindow).fadeOut('fast');
				$(picWindow).queue(function(){
					$('#videoplayer').show();
					$(picWindow).remove();				
				});
			};
			
			
			var closeButton = $('<a>');
			closeButton.attr('href','#');
			closeButton.addClass('close');
			closeButton.text('close');
			closeButton.click(function()
			{
				closePicWindow();
				return false;
			});
			picWindow.append(closeButton);

			var pic = $('<img>');
			pic.attr('src', $(this).attr('href'));
			
			var nav = $('<div id="picWindowNavigation">');
			nav.html('<a href="#" class="nextPic">next</a> <a href="#" class="prevPic">previous</a>');
			
			var currentImage = this;
			
			$('a.prevPic', nav).click(function(){
				if($(currentImage).parent('li').length)
				{
					parentItem = $(currentImage).parent();
					itemContainer = parentItem.parent();
					 
					if(parentItem.prev().length==0)
					{
						currentImage = itemContainer.children('li:last').children('a');
					}
					else
					{
						currentImage = parentItem.prev().children('a');
					}
						
				}
				else
				{
					parentItem = $(currentImage).parent().parent();
					itemContainer = parentItem.children('.side').children('.gallery').children('ul');
					
					currentImage = itemContainer.children('li:last').children('a');
				}
				
				pic.attr('src', currentImage.attr('href'));
				return false;
			});
			
			$('a.nextPic', nav).click(function(){
				if($(currentImage).parent('li').length)
				{
					parentItem = $(currentImage).parent();
					itemContainer = parentItem.parent();
					 
					if(parentItem.next().length==0)
					{
						currentImage = itemContainer.children('li:first').children('a');
					}
					else
					{
						currentImage = parentItem.next().children('a');
					}
						
				}
				else
				{
					parentItem = $(currentImage).parent().parent();
					itemContainer = parentItem.children('.side').children('.gallery').children('ul');
					
					currentImage = itemContainer.children('li:first').next().children('a');
				}
				
				pic.attr('src', currentImage.attr('href'));
				
				return false;
			});
			
			picWindow.append(nav);

			picLoaded = function()
			{
				picWindow.css({width: $(pic).attr('width')+'px'});
				picWindow.center($(pic).attr('width'), $(pic).attr('height')+77);
				
				closeButton.after(pic);
				picWindow.show();	
				
				$(picWindow).draggable();
			};
			
			
			
			if(pic.get(0).complete)
			{
				picLoaded();				
			}
			else
				pic.load(picLoaded);
			
			$('body').append(picWindow);
			
			return false;
		});
	});
	
	return false;
};


showVid = function(link)
{		
		
	$('#picWindow').remove();
	$('#vidWindow').remove();
	$('#specsWindow').remove();
	
	var vidWindow = $('<div id="vidWindow">');
	
	closeVidWindow = function()
	{
		$(vidWindow).fadeOut('fast');
		$(vidWindow).queue(function(){
			$(vidWindow).remove();			
		});
	};
	
	var closeButton = $('<a>');
	closeButton.attr('href','#');
	closeButton.addClass('close');
	closeButton.text('close');
	
	closeButton.click(function()
	{
		closeVidWindow();
		
		return false;
	});
	
	vidWindow.append(closeButton);
	
	var vid = $('<a></a>');
	vid.attr('id', 'popupvideo');
	vid.css('width', '640px');
	vid.css('height', '480px');
	vid.attr('href', link);
	
	vidWindow.append(vid);

	vidLoaded = function()
	{
		vidWindow.css('width', parseFloat($(vid).css('width'), 10));
		vidWindow.center(parseFloat($(vid).css('width'), 10), parseFloat($(vid).css('height'), 10));
		
		closeButton.after(vid);
		vidWindow.show();
		
		/*$(vidWindow).draggable();*/
	};
		
	vidLoaded();			
		
	$('body').append(vidWindow);
	
	/* INIT VIDEO */
	initVideoPlayer();
	
	return false;
};


/* VIDEO PLAYER */
function initVideoPlayer(onFinish)
{
	if(onFinish==undefined)
		onFinish = null;
		
	var player = $f("popupvideo", "/SWF/flowplayer-3.2.1.swf", {
		buffering:false,
		canvas:{backgroundColor:"transparent"},
		onError:onFinish,
		
		clip:{ 
     		autoBuffering:false,
     		autoPlay:true,
     		bufferLength:8,
     		scaling:'orig',
     		onFinish:onFinish
	    },
		
		plugins:{
		   controls:{
		      volumeSliderGradient:'none',
		      progressGradient:'none',
		      bufferGradient:'none',
		      buttonOverColor:'#FFB807',
		      timeBgColor:'#262626',
		      borderRadius:'0px',
		      tooltipTextColor:'#D00000',
		      sliderGradient:'none',
		      timeColor:'#d5d5d5',
		      volumeSliderColor:'#D00000',
		      durationColor:'#ffffff',
		      buttonColor:'#000000',
		      backgroundGradient:'none',
		      tooltipColor:'#C9C9C9',
		      backgroundColor:'#B7B7B7',
		      sliderColor:'#C9C9C9',
		      bufferColor:'#FFDB89',
		      progressColor:'#FFB807',
		      height:24,
		      opacity:1.0,
		      
		      /* ELEMENTS CONTROLBAR */
		      playlist:false,
		      volume:false,
		      fullscreen:false,
		      
		      /* AUTOHIDE */
		      autoHide:'always',
		      hideDelay:1000,
		      
		      /* TOOLTIPS HIDE */
		      tooltips:{ 
				scrubber:false
			  } 
		   }
		}
	
	});
	
	return false;
}


showSpecs = function(link)
{			
	$('#picWindow').remove();
	$('#vidWindow').remove();
	
	var specsWindow = $('<div id="specsWindow">');
	
	closeSpecsWindow = function()
	{
		$(specsWindow).fadeOut('fast');
		$(specsWindow).queue(function(){
			$(specsWindow).remove();			
		});
	};
	
	var closeButton = $('<a>');
	closeButton.attr('href','#');
	closeButton.addClass('close');
	closeButton.text('close');
	
	closeButton.click(function()
	{
		closeSpecsWindow();
		
		return false;
	});
	
	specsWindow.append(closeButton);
	
	var specs = $('<div></div>');
	specs.attr('id', 'popupspecs');
	specs.css('width', '640px');
	specs.css('height', '260px');
	specs.attr('href', $(link).attr('href'));
	specs.html(specs_html);
	
	specsWindow.append(specs);

	specsLoaded = function()
	{
		specsWindow.css('width', parseFloat($(specs).css('width'), 10));
		specsWindow.center(parseFloat($(specs).css('width'), 10), parseFloat($(specs).css('height'), 10));
		
		closeButton.after(specs);
		specsWindow.show();
	};
		
	specsLoaded();			
		
	$('body').append(specsWindow);
	
	return false;
};


showTable = function(link)
{			
	var tableWindow = $('<div id="tableWindow">');
	
	closeTableWindow = function()
	{
		$(tableWindow).fadeOut('fast');
		$(tableWindow).queue(function(){
			$(tableWindow).remove();			
		});
	};
	
	var closeButton = $('<a>');
	closeButton.attr('href','#');
	closeButton.addClass('close');
	closeButton.text('close');
	
	closeButton.click(function()
	{
		closeTableWindow();
		
		return false;
	});
	
	tableWindow.append(closeButton);
	
	var table = $('<div></div>');
	table.attr('id', 'popuptable');
	table.css('width', '640px');
	table.attr('href', $(link).attr('href'));
	
	html = $('#transport_table').html();
	
	table.html(html);
	
	closeButton.after(table);
	tableWindow.show();
	tableWindow.append(table);
	
	$('body').append(tableWindow);
	
	tableWindow.css('width', parseFloat($(table).css('width'), 10));
	tableWindow.center(parseFloat($(table).css('width'), 10), parseFloat($(table).css('height'), 10));			
	
	return false;
};


function preloadImage(file)
{
	
	var img = new Image();
	img.src = file;
	pics.push(img);

}


jQuery.fn.center = function (width, height) {
	return this.each(function () {
		var t = jQuery(this);

		t.css({
			position:	'absolute', 
			left:		'50%', 
			top:		'50%', 
			zIndex:		'99999'
		}).css({
			marginLeft:	'-' + (width / 2) + 'px', 
			marginTop:	'-' + (height / 2) + 'px'
		});
		t.css({
			marginTop:	parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(), 
			marginLeft:	parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
		});
	});
};

function updateOrder()
{
	$('#cart').load(document.location.toString()+'/a/update_cart', $('#form_order').serializeArray(), initOrder);
}


function initOrder()
{
	$('#paymenttype select').change(function()
	{
		$('#carttable').load(document.location.toString(), {a:'set_paymenttype', paymenttype:$(this).val()});
	});
	$('#transporttype select').change(updateOrder);
	$('#deliverycountry select').change(updateOrder);
	$('#contactdata input[name="vat"]').change(updateOrder);
	
	$('#transporttype input[type="checkbox"]').click(updateOrder);
	
	/* VALIDATIONS */
	$('#form_order').validate({
		focusInvalid: false,
		/* RULES */
		rules: {
			name: {
				required: true
			},
			company: {
				required: false
			},
			vat: {
				required: false
			},
			email: {
				required: true,
				email:true
			},
			address: {
				required: true
			},
			pc_city: {
				required: true
			}
		},
		/* MESSAGES */
		messages: {
			name: '',
			company: '',
			vat: '',
			email: '',
			address: '',
			pc_city: ''
		},
		/* INVALID HANDLER */
		invalidHandler: function(e, validator) {
            var errors = validator.numberOfInvalids();
            
            if (errors)
                $("#form_error").show();
            else
                $("#form_error").hide();
        }
	});
	
	/* */
	$('#show_transport_table').click(function(){
		showTable();
		
		return false;
	});

}


var cart = {

	isEmpty : true,
	
	
	
	add : function(id, type)
	{
		if($.trim($('#carttable').html())=='')
		{
			cart.isEmpty = true;
			$('#cart').hide();	
		}
		else
			cart.isEmpty = false;
			
		$('#carttable').load(document.location.toString(), {a:'cart_add',id:id, type:type}, cart.addCallback);

		return false;
	},
	
	addCallback : function(data)
	{
		if(cart.isEmpty)
		{
			$('#cart').fadeIn();
			
		}
	},
	
	
	
	
	remove : function(id)
	{
		$('#cart').load(document.location.toString(), {a:'cart_remove',id:id}, cart.removeCallback);
		
		return false;
	},
	
	removeCallback : function(data)
	{
		if($.trim($('#carttable').html())=='')
		{
			$('#cart').fadeOut();
		}
		else		
			initOrder();
	},
	
	
	
	
	changeAmount : function(select, id)
	{
		$('#cart').load(document.location.toString(), {a:'cart_changeamount',id:id,amount:$(select).val()}, initOrder);
		
		return false;
	}

}


function downloadFile(select)
{
	if($(select).val()=='')
		return;
		
	var win = window.open();
	win.location = '/PDF/' + $(select).val();
}
