var Search 		= function () {
	this.Running		= false; 
	this.Query			= '';
	this.Shown			= false; 
	this.LastChecked	= 0;
	this.NextHideTime	= 0; 
	this.IgnoreClick	= false; 
	this.Selected		= -1;
	this.ShiftDown		= false;
	this.ControlDown	= false; 
	this.SetFocus		= false;
	this.ID				= '';
	this.Group			= '';
};
var Searches	= new Array (); 
Search.Create = function (el) {
	if (el.attr ('id').length == 0) {
		var newSearch	= new Search (); 
		newSearch.ID	= 'search_'+Searches.length.toString();
		Searches.push(newSearch);
		el.attr ('id',newSearch.ID);
		newSearch.Group	= el.children('.group').val();
	}
}
Search.Hide = function () {
	for (var i=0;i<Searches.length;i++) {
		Searches[i].Hide ();
	}
}
Search.HtmlClick = function () {
	for (var i=0;i<Searches.length;i++) {
		var s	= Searches[i];
		if (!s.IgnoreClick)
		s.Hide (); 
	}
}
Search.Get = function (id) {
	var tokens	= id.split ("_");
	if (tokens.length == 2)
	{
		var index	= parseInt (tokens[1],10);
		if (index >=0 && index < Searches.length) {
			return Searches [index];
		}
	}
	alert ('Invalid id: '+id);
	return null; 
}
Search.GlobalKeyDown = function (e) {
	for (var i=0;i<Searches.length;i++) {
		Searches[i].KeyDown (e);
	}
}
Search.GlobalKeyUp = function (e) {
	for (var i=0;i<Searches.length;i++) {
		Searches[i].KeyUp (e);
	}
}
Search.GlobalTick = function () {
	
	for (var i=0;i<Searches.length;i++) {
		Searches[i].Tick ();
	}
	
	setTimeout ('Search.GlobalTick();',1000); 
}
Search.prototype.Tick = function ()
{
	var Time = this.GetTime ();
	if (Time >= this.NextHideTime)
	{
		if (this.Shown)
		this.Hide ();
	}
	var parent	= $('#'+this.ID);
	if (this.Query != parent.children('.keywords').val ()) 
	{
		this.Run ();
	}
	
}
var Composer	= {};



$(document).ready(function() {
	
	$('.haschildren img').bind('click', function() {
		 
		var el 	= $(this).parent().find('.subitems');
		var el0	= $(el[0]);

		if (el.css ('display') == 'none')
		{
			$($(this).parent().find ('img')[0]).attr ('src','/images/minus.gif');
			el0.slideDown (); 
		}
		else
		{
			$(this).parent().find ('img').attr ('src','/images/plus.gif');
			el.slideUp ();
		}
		
		//el.slideToggle (400);
	});
	
	$('#afleveradres').bind ('change',function (){
		
		$('#afleveradresBlock').css('display',$('#afleveradres').attr("checked")?'block':'none');
	}); 

	$("a.grouped_elements").fancybox();
	
	
	$('html').click (function() { Search.HtmlClick(); if (!Composer.DropDown.IgnoreClick) { Composer.DropDown.Hide(); }   });
	$('.search .keywords').click 	(function () { Search.Get($(this).parent().attr('id')).Run (); });
	$('.search .keywords').keyup 	(function (e) { if (e.keyCode != 38 && e.keyCode!=40) { Search.Get($(this).parent().attr('id')).Run (); } });
	$('.search').mouseover 	(function () { Search.Get ($(this).attr('id')).IgnoreClick = true; });
	$('.search').mouseout 	(function () { Search.Get ($(this).attr('id')).IgnoreClick = false; });
	$('.dropbox').mouseover	(function () { Composer.DropDown.IgnoreClick = true; });
	$('.dropbox').mouseout		(function () { Composer.DropDown.IgnoreClick = false; });
	$('.combobox').mouseover	(function () { Composer.DropDown.IgnoreClick = true; });
	$('.combobox').mouseout		(function () { Composer.DropDown.IgnoreClick = false; });
	$('.dropbox .inner').mousemove	(function () { return false; });
	$('.dropbox .inner').mousedown	(function () { return false; });
	$('.dropbox input').keyup (function () { Composer.DropDown.Search (this,$(this).val()); });
	$('.dropbox').scroll (function () {alert('scroll');}); 
	$('.forgot_password').click (function () {
		window.location = '/forgot_password/?email='+$('#email').val();
		return false;
	});
	
 	$(document).keydown			(function (e){ return Search.GlobalKeyDown (e); });
	$(document).keyup		(function (e){ return Search.GlobalKeyUp (e); });
	
	$('.search').each (function () { 
		Search.Create ($(this));
	});
	
	setTimeout ('Search.GlobalTick();',1000); 	
});



Search.prototype.KeyUp = function (e)
{
	if (e.keyCode == 16)
	{
		this.ShiftDown	= false;
		return false;
	}
	if (e.keyCode == 70)
	{
		if (this.SetFocus)
		{
			this.SetFocus = false;
			//$('#search input').focus ();
		}
	}
	this.ControlDown	= false; 
	
	if (e.keyCode!=70 && e.keyCode!=16)
	{
		this.SetFocus = false; 
	}
}
Search.prototype.FuncDown = function (e)
{
	if (e.keyCode == 16)
	{
		this.ShiftDown	= true;
	}
	else if (e.keyCode == 17)
	{
		this.ControlDown	= true;
	}
	else if (e.keyCode == 70)
	{
		if (this.ShiftDown)
		{
			this.SetFocus = true; 
		}
	}
	
	if (e.keyCode!=70 && e.keyCode!=16)
	{
		this.SetFocus = false; 
	}
}

Search.prototype.KeyDown = function (e)
{
	//this.Show (); 
	if (e.keyCode == 38)
	{
		if (this.Selected > 0)
		this.Selected --;
		else
		this.Selected = 4;
		this.SelectRow(this.Selected);
	}
	else if (e.keyCode == 40)
	{
		if (this.Selected < 4)
		{
			this.Selected += 1; 
		}
		else
		this.Selected = 0;
		this.SelectRow(this.Selected);
	}
	else if (e.keyCode == 13)
	{
		this.ClickRow(this.Selected);
	}
	else
	this.FuncDown(e);
}

Search.prototype.ClickRow = function (Row)
{
	
	this.Selected	= Row; 
	var Children	= $('#'+this.ID+' .results .tbproducts tbody').children ();
	for (var i=0;i<Children.length;i++)
	{
		var Child = Children[i];
		if (i == Row)
		$(Child).click ();
	}
}

Search.prototype.SelectRow = function (Row)
{
	this.Selected	= Row; 
	var Children	=  $('#'+this.ID+' #results .tbproducts tbody').children ();
	for (var i=0;i<Children.length;i++)
	{
		var Child = Children[i];
		$(Child).attr("id",(i == Row)?'searchkey':'');
	}
}

Search.prototype.RowHover = function (ID,El,Leave)
{
	if (!Leave)
	{
		this.SelectRow (ID);
	}
	else
	{
		this.SelectRow (-1);
	}
}

Search.prototype.GetTime = function ()
{
	var d = new Date();
	return d.getTime();
}
Search.prototype.Show = function ()
{
	$('#'+this.ID+' .results').css ('display','inline');
	this.Shown			= true; 
	this.NextHideTime	= this.GetTime ()+10000; 	
}
Search.prototype.Hide = function ()
{
	$('#'+this.ID+' .results').css ('display','none');
	this.Shown	= false; 
}

Search.prototype.Run = function ()
{
	var parent		=  $('#'+this.ID);
	var keywords	= parent.children ('.keywords');
	this.Selected		= 0;
	
	this.Show (); 
		
	if ($('#'+this.ID+' .keywords').val ().length < 1)
	return false; 
		
	if ($('#'+this.ID+' .keywords').val () == this.Query)
	return false; 
	
	if (this.Running) return false; // mag niet
	
		
	this.Query = $('#'+this.ID+' .keywords').val ();  
	
	this.Running		= true;
		
	var successFunction	= function (parent,thisSearch) {
		return (function (data) {
		thisSearch.Show ();
		var items 	= $.parseJSON(data);
			var output	= '<table width="100%" class="tbproducts" cellpadding="1" cellspacing="1" border="0"><tbody>';
			for (var i=0;i<items.length;i++)
			{
				var itm	= items[i];
				output += '<tr onmouseover="Search.Get (\'#'+thisSearch.ID+'\').RowHover('+i+',this,false);" onmouseout="Search.Get (\'#'+thisSearch.ID+'\').RowHover ('+i+',this,true);" onclick="ClickLink (this);" class="r1"><td width="20"><a href="/product/'+itm['p']+'"><img width="20" src="/include/upload/shop/thumbs/'+itm['i']+'" border="0"></a></td><td><a href="/product/'+itm['p']+'">'+itm['n']+'</a></td></tr>';
			}
			output += '</tbody></table>';
			$('#'+thisSearch.ID+' .results').html (output);
			$('#'+thisSearch.ID+' .loading').css ('display','none');
			thisSearch.SelectRow(this.Selected);
			if (thisSearch.Query != $('#'+thisSearch.ID+' .keywords').val ()) 
			{
				thisSearch.Run (parent);
			}
		});
	};
	var completeFunction	= function (parent,thisSearch) {
		return (function (data) {
			thisSearch.Running = false; 
			//thisSearch.Hide (); 
		});
	};
		
		this.Show ();
		$('#'+this.ID+' .loading').css ('display','inline-block');
		$.ajax({type:'POST',url:'/search',data: {'query':this.Query,'group':this.Group},
		success: successFunction (parent,this), 
		
		complete: completeFunction (parent,this)});
	
}


function ClickLink (el)
{
	var tdElements	= el.getElementsByTagName ('td');
	
	if (tdElements.length > 0)
	{
		var td			= tdElements[0];
		var aElements 	= td.getElementsByTagName ('a');

		if (aElements.length > 0)
		{
			var a 			= aElements[0];
			window.location = a.href;
		}
	}
}
 
Composer.LoadRow = function (ID,Index,Data)
{
	var IDSelect	= 'select_'+ID;
	var IDCount		= 'count_'+ID; 
	
	$('#'+IDSelect).html (this.FillTable (Data['data']));
	
	for (var i=1;i<=99;i++)
	{
		$('#'+IDCount).append ('<option value="'+i+'">'+i+'</option>');
	}
	
}
Composer.FillTable = function (Data)
{
	var html = '';
	
	var t		= '1'; 
	
	html += '<tr onclick="Composer.DropDown.ClickRow(this,\'\')" class="p0" class="t'+t+'">';
	html += '<td width="32"><div style="overflow:hidden;width:48px"></div></td>';
	html += '<td width="10"></td>';
	html += '<td width="357">&lt;Geen&gt;</td>';
	html += '<td width="60">-</td>';
		
		
	html += '</tr>';
	
	for (var i=0;i<Data.length;i++)
	{
		var Item = Data[i];
		var Box = '<div class="composer_delivery"><div class="box"></div></div>&nbsp;';
		
		html += '<tr valign="center" onclick="Composer.DropDown.ClickRow(this,\''+Item['id']+'\')" class="p'+Item['id']+'" class="t'+t+'">';
		
		html += '<td width="32"><div style="overflow:hidden;width:48px"><img height="32" src="/include/upload/shop/thumbs/'+Item['imagename']+'" border="0"/></div></td>';
		html += '<td valign="center" width="10">'+Box+'</td>';
		html += '<td width="357">'+Item['name']+'</td>';
		
		var Price	= Math.round(Item['price']);

		html += '<td width="60">&euro; '+Price+',-</td>';
		
		
		html += '</tr>';
		t = (t=='2')?'1':'2'; 
	}
	return html;
}
Composer.ChangeCount = function (key,Count)
{
	for (var i=0;i<Composer.PriceKeys.length;i++)
	{
		if (Composer.PriceKeys[i] == key)
		{
			Composer.PriceCount[i] = Count;
		}
	}
	
	Composer.CalcTotalPrice ();
}
Composer.UpdateProgress = function ()
{
	
	
	if (Composer.Loading)
	{
		$('#composer_loading .left').html ('Laden '+Composer.Progress+'%');
		$('#composer_loading .right .progress').css ('width',(Composer.Progress*5)+'px');
		setTimeout ('Composer.UpdateProgress()',100);
	}
	else
	{
		$('#composer_loading').html ('<strong>Stel uw systeem samen</strong>');
	}
}
Composer.LoadNext = function ()
{
	if (Composer.g < 18)
	{
		$.ajax({type:'GET',async:false,url:'/compose_system.php/ajax?g='+Composer.g,cache:true,success: function (data) {
			this.Data = $.parseJSON(data);
			Composer.Progress = Math.floor (Composer.g/17*100);
			Composer.UpdateProgress ();
			for (var i=0;i<this.Data.length;i++)
			{
				var Item = this.Data[i];
				var ID		= Item['id'];
				Composer.PriceKeys[Composer.PriceKeys.length] = ID;
				Composer.PriceValues[Composer.PriceValues.length] = 0;
				Composer.PriceCount[Composer.PriceCount.length] = 1;
				
				Composer.LoadRow (Item['id'],0,Item);
			}
		}});
		
		Composer.g ++;
		
		setTimeout('Composer.LoadNext ()',1);
	}
	else
	{
		$.ajax({type:'POST',url:'/compose_system',data: {'dl':'true'},
		success: function (data) {
			Composer.DropDown.Searching = false; 
			var items 	= $.parseJSON(data);
			
			//var Table	= Composer.DropDown.Active.find ('.inner table');
			//Table.find ('tr').css ('display','none');
			
			for (var a=0;a<items.length;a++)
			{
				var ID		= items[a].i;
				var V		= items[a].v;
				//var Rows	= Table.find ('tr');
				var Color	= '#D00';
				
				if (V == '1')
				Color = '#0D0';
				else if (V == '2')
				Color = '#DD0';
				
				$('.p'+ID+' .composer_delivery .box').css ('background-color',Color);
				
				/*for (var i=0;i<Rows.length;i++)
				{
					var Row	= Rows[i];
					
					if ($(Row).attr('class')=='r'+ID)
					{
						$(Row).css ('display','table-row');
					}
					
					
				}*/
			}	
		}});
		
		Composer.CalcTotalPrice ();
		Composer.DropDown.Init ();
		Composer.Loading = false;
		Composer.OnLoaded (); 
	}
}
Composer.Load = function ()
{	
	Composer.Loading = true;
	setTimeout ('Composer.UpdateProgress()',100);
	Composer.PriceKeys = Array (); 
	Composer.PriceValues = Array (); 
	Composer.PriceCount = Array (); 
	Composer.Progress = 0;
	Composer.g 			= 0;
	$('.combobox').mousedown (function (){
		var El	= $(this).parent().find ('.dropbox');
		if (Composer.DropDown.Active == null)
		{
			Composer.DropDown.Show (El);
		}
		else
		{
			Composer.DropDown.Hide();
		}
	});
	
	
	
	setTimeout('Composer.LoadNext ()',1);
	

}
Composer.UpdatePrice = function (key,value)
{
	for (var i=0;i<Composer.PriceKeys.length;i++)
	{
		if (Composer.PriceKeys[i] == key)
		{
			Composer.PriceValues[i] = value;
		}
	}
}
Composer.CalcTotalPrice = function ()
{
	var Total = 0;
	for (var i=0;i<Composer.PriceKeys.length;i++)
	{
	  Total += Composer.PriceValues[i]*Composer.PriceCount[i];
	}
	Total += $('#assemblage_1').is(':checked')?50:0;
	Total += $('#installatie_1').is(':checked')?49:0;
	
	Total = Math.ceil (Total*100)/100;
	$('#composed_price').html ('&euro; '+Total.toString());
}
Composer.DropDown = {};

Composer.DropDown.Init = function ()
{
	this.IgnoreClick	= false; 
	this.Searching		= false; 
}
Composer.ExtractNumber = function (str)
{
	var n0		= "0".charCodeAt(0);
	var n9		= "9".charCodeAt(0);
	var length	= str.length;
	var reading	= false;
	var out		= "";
	for (var i=0;i<length;i++)
	{
		var c = str.charCodeAt (i);
		if (c >= n0 && c<=n9)
		{
			reading = true;
			out += str.charAt (i);
		}
		else
		{
			if (reading)
			{
				break;
			}
		}
	}
	return out;
}

Composer.DropDown.SelectItem = function (CATID,PRODUCTID,COUNT)
{
	var IDSelect	= 'select_'+CATID;
	
	var TRs = $('#'+IDSelect).find ('.p'+PRODUCTID);
	if (TRs.length > 0)
	{
		var TR	= TRs[0];
		Composer.DropDown.ClickRow (TR,PRODUCTID);
	}
	
	$('#count_'+CATID).val (COUNT);
	Composer.ChangeCount (CATID,parseInt(COUNT,10));
}

Composer.DropDown.ClickRow = function (This,ID)
{
	var TDs	= $(This).find ('td');
	
	var TD0	= TDs[0];
	var TD1 = TDs[1];
	var TD2	= TDs[2];
	var TD3 = TDs[3];
	
	var Owner	=  $(This).parent()
			.parent()
			.parent()
			.parent()
			.parent();
	var priceVal 	= parseFloat (Composer.ExtractNumber($(TD3).html()));
	if (isNaN(priceVal)) priceVal = 0;
	var catid		= $(Owner).find('.catid').html();
	Composer.UpdatePrice(catid,priceVal);
	Composer.CalcTotalPrice();

	$('#input_'+catid).val (ID);

	$(Owner).find ('.combobox .c img').attr ('src',$(TD0).find ('img').attr('src'));
	$(Owner).find ('.combobox .c .text').html ($(TD2).html());
	$(Owner).find ('.combobox .c .price').html ($(TD3).html());
	this.Hide ();
}

Composer.DropDown.Hide = function ()
{
	if (this.Active!= null)
	{
		this.Active.css ('display','none');
		this.Active	= null; 
	}
}

Composer.DropDown.Show = function (Element)
{
	if (this.Active!=null)
	{
		if (this.Active!=Element)
		{
			this.Hide ();
		}
	}
	
	Search.Hide (); 
	
	this.Active = Element; 
	Element.css ('display','block');
}
Composer.DropDown.Search = function (This,Text)
{
	if (this.Searching)
	return; 
	
	if (Text.length < 1)
	{
		var Table	= Composer.DropDown.Active.find ('.inner table');
			Table.find ('tr').css ('display','table-row');
		
		return ;
	}
	
	this.Searching = true; 
	
	
		$('#'+this.ID+' .loading').css ('display','inline-block');
		$.ajax({type:'POST',url:'/compose_system',data: {'q':Text,'c':Composer.DropDown.Active.find('.catid').html()},
		success: function (data) {
			Composer.DropDown.Searching = false; 
			
			var items 	= $.parseJSON(data);
			
			var Table	= Composer.DropDown.Active.find ('.inner table');
			Table.find ('tr').css ('display','none');
			
			for (var a=0;a<items.length;a++)
			{
				var ID		= items[a];
				var Rows	= Table.find ('tr');
				
				Table.find('.p'+ID).css ('display','table-row');
				
				/*for (var i=0;i<Rows.length;i++)
				{
					var Row	= Rows[i];
					
					if ($(Row).attr('class')=='r'+ID)
					{
						$(Row).css ('display','table-row');
					}
					
					
				}*/
			}	
		}});
	
}

Validator = {};

Validator.Length	= 0x01;
Validator.Email		= 0x02;
Validator.Match		= 0x04;

Validator.Validate = function (El,Flags,Width,Userdata)
{
	var Valid	= true;
	
	if (Flags & this.Length)
	{
		if ($(El).val().length < 1)
		{
			Valid = false;
		}
	}
	if (Valid)
	{
		if (Flags & this.Email)
		{
			var reg = /^[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[@]{1}[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[.]{1}[A-Za-z]{2,5}$/;
			//var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
			if (!reg.test($(El).val()))
			{
				Valid = false; 
			}
		}
	}
	if (Valid)
	{
		if (Flags & this.Match)
		{
			var otherVal	= $('#'+Userdata).val();
			if ($(El).val()!=otherVal)
			Valid = false; 
		}
	}
	
	$(El).css ('background-image','url(/input.php?w='+Width+'&color='+(Valid?'green':'red')+')');
} 
Validator.Restore = function (El,Width)
{
	$(El).css ('background-image','url(/input.php?w='+Width+'&color=none)');
}
Validator.PragmaticChange	= function (El)
{
	$('.pragmatic').css ('display',$('#pragmaticYes').attr("checked")?'table-row':'none');
}

$(function(){
  $("#togglediv").toggle(function()
  {
	$("#overview").hide();
	$("#specs").show();
	$("#toggletext").html('Overzicht');
	window.location.href = '#product';
  },
  function()
  {
	$("#overview").show();
	$("#specs").hide();
	$("#toggletext").html('Specificaties');
	window.location.href = '#product';
  });
});
			
$(document).ready(function() {

	$("a[rel=ProgenionPhoto]").fancybox({
								
		'overlayOpacity'	: 0.6,
		'titlePosition'		: 'inside'
		
	});
	
	$("#downloads").fancybox({
							 
		'hideOnContentClick': false,
		'autoDimensions'	: false,
		'overlayOpacity'	: 0.6,
		'width'				: 250,
		'height'			: 150
		
	});
		
$('#magnifier').click(function() {
	$("#SmallThumb1").trigger('click');
});

$('#mainpic').click(function() {
	$("#SmallThumb1").trigger('click');
});
	
	
});

$(document).ready(function() {
						   
	$("#tellafriend_fancy").fancybox({
		'scrolling'		: 'no',
		'titleShow'		: false,
		'onClosed'		: function() {
			$("#login_error").hide();
		}
	});
	
	$("#tellafriend_form").bind("submit", function() {

		$.fancybox.showActivity();
	
		$.ajax({
			type		: "POST",
			cache	: false,
			url		: "/shop_tellafriend.php",
			data		: $(this).serializeArray(),
			success: function(data) {
				$.fancybox(data);
			}
		});
	
		return false;
	});
	
});

$(document).ready (function () {

	var location = window.location.href;
	var index =  location.indexOf ("#autoscroll");
	var scrolling = 0;
	function scrollUp ()
	{
		if (scrolling !=0 )
		return; 
		scrolling = 2; 
		$('html,body').animate({scrollTop: 0}, 15000,'linear',
		function (){ 
			scrolling = 0;
			window.location = 'http://www.progenion.nl#autoscroll';
			//scrollDown();
		}
		);
	}
	function scrollDown ()
	{
		if (scrolling !=0 )
		return; 
		scrolling = 1;
		var stopY = $(document).height()-$(window).height();
		stopY = 1000;
		$('html,body').animate({scrollTop: stopY}, 15000,'linear',function (){ 
			scrolling = 0;
			scrollUp();
		});
	}

	if (index>0)
	{
		scrollDown ();
	}
});
