﻿var winesearch = Class.create();

var numPeriods = -1;

function onTimer( )
{
	if( numPeriods >= 0 )
	{
		if( 4 == ++numPeriods )
			numPeriods = 0;

		str = 'Sökning pågår<b>';

		for( i=0; i<numPeriods; ++i )
			str += '.';

		str += '</b>';

		document.getElementById( 'informationBox' ).innerHTML = str;
	}
}

winesearch.prototype = {

	// Jan Jarfalk at Trive AB
	// jan.jarfalk@trive.se
	// http://www.trive.se

	// Requires	Prototype
	//			Script.aculo.us
	
	initialize: function(options) {
		

		if(options == null)
			throw("options cannot be null");

		this.textboxSearch;
		this.minChars = options.minChars || 1;
		this.extendedSearch = options.checkboxExtSearch;
		this.container;
		this.filter;
		this.currentregiontype = options.regiontype;
		this.currentregionid = options.pid || 0;
		this.currentResultLength = 0;
		
		this.counterCountries = '0';
		this.counterRegions = '0';
		this.counterDistricts = '0';
		this.counterOrigins = '0';
		this.counterProducers = '0';
		
		this.xmlSelectableRegions = options.xmlSelectableRegions;
		this.xmlSourceCountries = options.xmlSourceCountries;
		this.xmlSourceRegions = options.xmlSourceRegions;
		this.xmlSourceDistricts = options.xmlSourceDistricts;
		this.xmlSourceOrigins = options.xmlSourceOrigins;
		this.xmlSourceProducers = options.xmlSourceProducers;

		setInterval( 'onTimer( )', 250 );

		if(options){
			
			if(options.textboxSearch){
				(this.textboxSearch = options.textboxSearch || null)
			} else {
				throw("option.textboxSearch cannot be null");
			}
			
			if(options.container){
				(this.container = options.container || null)
			} else {
				throw("option.container cannot be null");
			}
			
			if(options.filter){
				(this.filter = options.filter || null)
			} else {
				throw("option.filter cannot be null");
			}
			
		}
		
		Event.observe(this.textboxSearch, 'keypress', this.handleKeyPress.bindAsEventListener(this), false);
		Event.observe(this.extendedSearch, 'click', this.handleKeyPress.bindAsEventListener(this, this.extendedSearch), false);
		Event.observe(this.container, 'click', this.move.bindAsEventListener(this, this.filter), false);
		//Event.observe(this.container, 'click', this.handleFilterClick.bindAsEventListener(this, this.filter), false);
		Event.observe(this.filter, 'click', this.move.bindAsEventListener(this, this.container), false);
		//Event.observe(this.filter, 'click', this.handleFilterClick.bindAsEventListener(this, this.container), false);
		
		
		var qp = location.href.toQueryParams();
		if(qp.s){ $('inputFilterString').value = qp.s; }
		if(qp.e){ $(this.extendedSearch).checked = qp.e; }
		var region = {id:this.currentregionid, type:this.currentregiontype}
		
		$('resultTabs').hide();
		$('resultTabs').hide();
		$('atabCountries').hide();
		$('atabRegions').hide();
		$('atabDistricts').hide();
		$('atabOrigins').hide();
		$('atabProducers').hide();

		$('informationBox').innerHTML = 'Du måste börja med att klicka på en världsdel och/eller skriva ett sökord';
		$('informationBox').show();

		this.updateSelectedRegions(region);
		if(this.currentregiontype != 0){
			this.updateSelectableRegions({id:this.currentregionid, type:this.currentregiontype+1}, this.filter);
		}
		else {
			this.updateSelectableRegions(region, this.filter);
		}
		//location.href = "#" + this.currentregiontype;
		this.dotheajax(this,this.currentregiontype,this.currentregionid,"","false");
		
		
		if ($(this.textboxSearch).value.length >= 3 || $('hiddenBrowseStateSelectedRegions').innerHTML != "")
			this.dotheajax(this,this.currentregiontype+1,this.currentregionid,$(this.extendedSearch).checked,"false");
		
		/*var region = {id: this.currentregionid, type: this.currentregiontype};
		this.updateSelectableRegions(region, this.filter);
		this.dotheajax(this,region.type+1,region.id,$(actor.extendedSearch).checked,"false");*/
	},
	
	getRegionIDandType: function(el)
	{
	    var region = null;
	    
	    if(el.tagName == 'LI' || el.tagName == 'SPAN' || el.tagName == 'A')
			{
				if(el.tagName != 'LI')
				{
					function findParentLi(el) {
						if(el.tagName != 'LI') {
							return findParentLi(el.parentNode);
						} else {
							return el;
						}
					}
					
					el = findParentLi(el);
				}
				
				region = {id: el.getAttribute('id'), type: el.getAttribute('rel')}
			}
		
		this.currentregiontype = region.type;
		this.currentregionid = region.id;
		return region;
	},
	
	handleFilterClick: function(e, target)
	{
	    var el = e.target || e.srcElement;	    
	    var region = this.getRegionIDandType(el);
        this.updateAll(region, target);
	},
	
	updateAll: function(region, target){
		this.updateSelectedRegions(region, target);
	    this.updateSelectableRegions(region, target);
	    this.dotheajax(this,region.type+1,region.id,$(actor.extendedSearch).checked,"false");
	},

	redirectToArticle: function( transport )
	{
		var articleId = transport.responseXML.documentElement.getElementsByTagName( 'id' )[ 0 ].childNodes[0].nodeValue;

		if( articleId > 0 )
			gotoArticle( articleId );
	},
	
	handleKeyPress: function()
	{
		doDirect = false;
		actor = this;
		window.clearTimeout(actor.keypresstimeout);
		if($(this.textboxSearch).value.length >= this.minChars)
		{
			//$('informationBox').innerHTML = 'Sökning pågår...';
			if( numPeriods < 0 )
				numPeriods = 0;

			$('informationBox').style.width = '';
			$('informationBox').style.cssFloat = '';
			$('informationBox').style.styleFloat = '';
			$('addNewProducer').hide( );

			$('informationBox').show();
			actor.keypresstimeout = window.setTimeout(function(){
				actor.dotheajax(actor,actor.currentregiontype+1,actor.currentregionid,$(actor.extendedSearch).checked,"false");
				}, 300);
			$('hiddenBrowseStateRecordID').value = actor.currentregionid;
			$('hiddenBrowseStateRecordType').value = parseInt(actor.currentregiontype);
			$('hiddenBrowseStateSearchString').value = $('inputFilterString').value;	
		}
	},
	
	updateSelectedRegions: function(region, target)
	{
	    if(target == this.container){
	       includeSelf = true;
	    }
	    if(target == this.filter){
	        includeSelf = false;
	    }
	    
        var self = this;
	    var url = "/default.aspx?documentId=82";
	    new Ajax.Request(url, {
	        method: 'get',
			parameters: {
			    pid: region.id, 
				includeSelf: 'true',
				includeWorld: 'false'
			},
			onSuccess: function(transport) {
			    $(self.container).innerHTML = triveCommon.prototype.setXSL(transport.responseXML,'xslt/selectedRegions.xsl');
			}
		});
	},
	
	updateSelectableRegions: function(region, target)
	{
		if( numPeriods < 0 )
			numPeriods = 0;

		$('informationBox').style.width = '';
		$('informationBox').style.cssFloat = '';
		$('informationBox').style.styleFloat = '';
		$('addNewProducer').hide( );
		$('informationBox').show();

	    var type;
	    if(target == this.container){
	        type = (region.type)*1+1;
	        //type = region.type
	    }
	    if(target == this.filter){
	        type = region.type;
	    }
	    	    					if(region.id != null && region.id != "-1" && region.type == 0){
						type = "1";
					}
	    if(region.id == 2908){
	        type = 0;
	    }

	    
	    new Ajax.Request(this.xmlSelectableRegions, {
	  			method: 'get',
				parameters: {ptype:type, pid:region.id},
	  			onSuccess: function(transport) {
	  				if (region.type == 0)
						$('aWorldLink').style.display = 'block';
					else
						$('aWorldLink').style.display = 'none';
					/*$('selectableRegionsMain').innerHTML = triveCommon.prototype.setXSL(transport.responseXML,'xslt/selectableRegionsMain.xsl');*/
					$('selectableRegions').innerHTML = triveCommon.prototype.setXSL(transport.responseXML,'xslt/selectableRegions.xsl');
	  			},
				onFailure: function()
				{
					$('selectableRegionsMain').innerHTML = "";
					$('selectableRegions').innerHTML = "";
				}
			});
	},
	
	getLength: function(transport)
	{
		var length; 
		if(document.implementation && document.implementation.createDocument)
		{
			Try.these(
		             function() { length = transport.responseXML.childNodes.item(1).childNodes.item(1).childNodes.item(0).nodeValue; },
		             function() { length = transport.responseXML.childNodes.item(0).childNodes.item(1).childNodes.item(0).nodeValue }
		       );
		}
		else if(window.ActiveXObject){
			length = transport.responseXML.childNodes.item(2).childNodes.item(0).childNodes.item(0).nodeValue;
		}

		return length;
	},
	
		move: function(e,target)
		{
		    
			var el = e.target || e.srcElement;
			var target = $(target) || $(this.filter);
			
			
			if(el.tagName == 'LI' || el.tagName == 'SPAN' || el.tagName == 'A')
			{
				if(el.tagName != 'LI')
				{
					function findParentLi(el) {
						if(el.tagName != 'LI') {
							return findParentLi(el.parentNode);
						} else {
							return el;
						}
					}
					
					el = findParentLi(el);
				}
				
				this.currentregiontype = el.getAttribute('rel');
				this.currentregionid = el.getAttribute('id');
				
				//clone = el.cloneNode(true);
				//clone.style.visibility = 'hidden';
				//target.appendChild(clone);

				//var posx = triveCommon.prototype.getPosition(clone)[0] - triveCommon.prototype.getPosition(el)[0]; 
				//var posy = triveCommon.prototype.getPosition(clone)[1] - triveCommon.prototype.getPosition(el)[1]; 

				actor = this;

				//new Effect.Move(el, {x:posx , y:posy, duration:0.1, afterFinish:function(){
					
					//target.appendChild(el);
					//el.remove();
					//clone.style.visibility = 'visible';
					
					if(target == $(actor.container)) //ADD
					{
						actor.dotheajax(actor,parseInt(actor.currentregiontype)+1,actor.currentregionid,$(actor.extendedSearch).checked);
						
						$('hiddenBrowseStateRecordID').value = actor.currentregionid;
						$('hiddenBrowseStateRecordType').value = parseInt(actor.currentregiontype) + 1;
						Try.these(function(){
						    $('hiddenBrowseStateSearchString').value = $('inputFilterString').value;
						});
					}
					if(target == $(actor.filter)) //DELETE
					{
						var lastindex;
						/*if($(actor.container).getElementsByTagName('li').length >= 1)
						{
							lastindex = $(actor.container).getElementsByTagName('li').length;
							var theptype = parseInt($(actor.container).getElementsByTagName('li')[lastindex-1].getAttribute('rel')) + 1;
							var thepid = $(actor.container).getElementsByTagName('li')[lastindex-1].getAttribute('id');
						}
						else
						{
							var theptype = 0;
							var thepid = 0;
						}*/
						
						var theptype = el.getAttribute('rel');
					    var thepid = el.getAttribute('id');
					    //location.href = "#" + thepid + "T" + theptype;
						
						actor.dotheajax(actor,theptype,thepid,$(actor.extendedSearch).checked,"true","delete");
						
						$('hiddenBrowseStateRecordID').value = thepid;
						$('hiddenBrowseStateRecordType').value = theptype;
						$('hiddenBrowseStateSearchString').value = $('inputFilterString').value;
					}

					

					//el.parentNode.removeChild(el);


				//t}});
				
				if(target == $(this.filter)){
					/*el.siblings().each(
						function(item){
							if(parseInt(item.getAttribute('rel')) > parseInt(el.getAttribute('rel')))
							{
								item.parentNode.removeChild(item);
							}
						});*/
				}
			}
		},
		
		dotheajax: function(actor,ptype,pid,extendedsearch,updateselectable,action){
		
			actor.currentResultLength = 0;

			//$('atabCountries').hide();
			//$('atabRegions').hide();
			//$('atabDistricts').hide();
			//$('atabProducers').hide();
			
			extendedsearch = !extendedsearch;
			//location.href = "#foo" 
			
			Try.these(function(){
		    var url = "/default.aspx?documentId=82";
	        new Ajax.Request(url, {
	            method: 'get',
			    parameters: {
			        pid: pid,
				    includeSelf: 'true',
				    includeWorld: 'false'
			    },
			    onSuccess: function(transport) {
			        $(actor.container).innerHTML = triveCommon.prototype.setXSL(transport.responseXML,'xslt/selectedRegions.xsl');
			    }
		    });
		    });
			
			if(updateselectable != "false")
			{
			  var selType = ptype;
		      var region = {id: pid, type:ptype}
		      this.updateSelectableRegions(region, this.filter);
			/*new Ajax.Request(this.xmlSelectableRegions, {
	  			method: 'get',
				parameters: {ptype:selType, pid:pid},
	  			onSuccess: function(transport) {
	  				if (ptype == 0)
						$('aWorldLink').style.display = 'block';
					else
						$('aWorldLink').style.display = 'none';
						
					$('selectableRegions').innerHTML = triveCommon.prototype.setXSL(transport.responseXML,'xslt/selectableRegions.xsl');
	  			},
				onFailure: function()
				{
					$('selectableRegions').innerHTML = "";
				}
			});*/
			}
					//alert('ptype' + ptype + 'pid' + pid);
	
					if(pid != '-1' || $(actor.textboxSearch).value.length >= 3/*(ptype != 0 && (pid != 0 || $(actor.textboxSearch).value.length >= 3)) /*&& pid != '-1'*/)
					{

					new Ajax.Request(actor.xmlSourceCountries, {
			  			method: 'get',
						parameters: {
							ptype:'1',
							pid:pid, 
							searchStr:$(actor.textboxSearch).value,
							extended:extendedsearch,
							page: '1',
							pageSize: '500',
							sortColumn: 'country',
							sortAscending: 'true'
							},
						onUninitialized: function(){
							$('tabCountries').innerHTML = "&nbsp;(laddar)";
						},
			  			onSuccess: function(transport) {
							//actor.counterCountries = actor.getLength(transport);	
							//actor.currentResultLength += actor.counterCountries;
							
							actor.counterCountries = parseInt(actor.getLength(transport, "region"));
							actor.currentResultLength += actor.counterRegions;
							
							//location.href = "#" + actor.counterCountries;
							
							if(actor.counterCountries > 0)
							{
								$('atabCountries').innerHTML = "L&auml;nder &nbsp;(" + actor.getLength(transport, "region") + ")";
								$('atabCountries').show();
								$('tbodyCountries').innerHTML = triveCommon.prototype.setXSL(transport.responseXML,'xslt/countries.xsl');
								$('resultTabs').show();

								$('addNewProducer').hide( );
								$('informationBox').hide();
								numPeriods = -1;
							}
							else
							{
								$('atabCountries').hide();
								$('resultTabs').tabber.tabShow(1);
							}
						},
						onComplete: function()
						{
							new Ajax.Request(actor.xmlSourceRegions, {
					  			method: 'get',
								parameters: {
									ptype:'2',
									pid:pid, 
									searchStr:$(actor.textboxSearch).value,
									extended:extendedsearch,
									page: '1',
									pageSize: '500',
									sortColumn: 'region',
									sortAscending: 'true'
									},
								onUninitialized: function(){
											$('tabRegions').innerHTML = "&nbsp;(laddar)";
										},
					  			onSuccess: function(transport) {
									
									actor.counterRegions = parseInt(actor.getLength(transport, "region"));
									actor.currentResultLength += actor.counterRegions;
																								
									if(actor.counterRegions > 0)
									{
										$('atabRegions').show();
										$('tabRegions').innerHTML = "&nbsp;(" + actor.getLength(transport, "region") + ")";
										$('tbodyRegions').innerHTML = triveCommon.prototype.setXSL(transport.responseXML,'xslt/regions.xsl');
										$('resultTabs').show();
										$('informationBox').hide();
										numPeriods = -1;
									}
									else
									{
										$('atabRegions').hide();
										$('resultTabs').tabber.tabShow(2);
									}
									
								},
								onComplete: function()
								{
									new Ajax.Request(actor.xmlSourceDistricts, {
							  			method: 'get',
										parameters: {
											ptype:'3',
											pid:pid, 
											searchStr:$(actor.textboxSearch).value,
											extended:extendedsearch,
											page: '1',
											pageSize: '500',
											sortColumn: 'district',
											sortAscending: 'true'
											},
										onUninitialized: function(){
													$('tabDistricts').innerHTML = "&nbsp;(laddar)";
												},
							  			onSuccess: function(transport) {
											
											actor.counterDistricts = parseInt(actor.getLength(transport, "region"));	
											actor.currentResultLength += actor.counterDistricts;

											if(actor.counterDistricts > 0)
											{
												$('atabDistricts').show();
												$('tabDistricts').innerHTML = "&nbsp;(" + actor.getLength(transport, "region") + ")";
												$('tbodyDistricts').innerHTML = triveCommon.prototype.setXSL(transport.responseXML,'xslt/districts.xsl');
												$('resultTabs').show();
												$('informationBox').hide();
												numPeriods = -1;
											}
											else
											{
												$('atabDistricts').hide();
												$('resultTabs').tabber.tabShow(3);
											}
											
										},
										onComplete: function()
										{
											new Ajax.Request(actor.xmlSourceOrigins, {
									  			method: 'get',
												parameters: {
													ptype:'4',
													pid:pid, 
													searchStr:$(actor.textboxSearch).value,
													extended:extendedsearch,
													page: '1',
													pageSize: '500',
													sortColumn: 'origin',
													sortAscending: 'true'
													},
												onUninitialized: function(){
															$('tabOrigins').innerHTML = "&nbsp;(laddar)";
														},
									  			onSuccess: function(transport) {
																							
													
													actor.counterOrigins = parseInt(actor.getLength(transport, "region"));	
													actor.currentResultLength += actor.counterOrigins;
													
													if(actor.counterOrigins > 0)
													{
														$('atabOrigins').show();
														$('tabOrigins').innerHTML = "&nbsp;(" + actor.counterOrigins + ")";
														$('tbodyOrigins').innerHTML = triveCommon.prototype.setXSL(transport.responseXML,'xslt/origins.xsl');
														$('resultTabs').show();
														$('informationBox').hide();
														numPeriods = -1;
													}
													else
													{
														$('atabOrigins').hide();
														$('resultTabs').tabber.tabShow(4);
													}
												
												},
												onComplete: function()
												{
													new Ajax.Request(actor.xmlSourceProducers, {
											  			method: 'get',
														parameters: {
															ptype:'5',
															pid:pid, 
															searchStr:$(actor.textboxSearch).value,
															extended:extendedsearch,
															page: '1',
															pageSize: '2400',
															sortColumn: 'producer',
															sortAscending: 'true'
															},
														onUninitialized: function(){
																$('tabProducers').innerHTML = "&nbsp;(laddar)";
															},
											  			onSuccess: function(transport) {

															
															actor.counterProducers = parseInt(actor.getLength(transport, "region"));	
															actor.currentResultLength += actor.counterProducers;

															if(actor.counterProducers > 0)
															{
																$('atabProducers').show();
																$('tabProducers').innerHTML = "&nbsp;(" + actor.getLength(transport, "region") + ")";
																$('tbodyProducers').innerHTML = triveCommon.prototype.setXSL(transport.responseXML,'xslt/producers.xsl');
																$('resultTabs').show();
																$('informationBox').hide();
																numPeriods = -1;
															}
															else
															{
																$('atabProducers').hide();
																$('resultTabs').tabber.tabShow(0);
															}
														},
														onComplete: function(transport)
														{
															//location.href = "#" + actor.currentResultLength;

															if(actor.counterCountries == "-1"){ actor.counterCountries = 0 }
															if(actor.counterRegions == "-1"){ actor.counterRegions = 0 }
															if(actor.counterDistricts == "-1"){ actor.counterDistricts = 0 }
															if(actor.counterOrigins == "-1"){ actor.counterOrigins = 0 }
															if(actor.counterProducers == "-1"){ actor.counterProducers = 0 }

															var totalhits = actor.counterCountries + actor.counterRegions + actor.counterDistricts + actor.counterOrigins + actor.counterProducers;
															
															if(totalhits <= 0)
															{
																$('resultTabs').hide();

																numPeriods = -1;
																$('informationBox').innerHTML = 'Din sökning gav inga träffar. Är stavningen rätt? Är tidigare sökning kvar?';
																$('informationBox').style.width = '470px';
																$('informationBox').style.cssFloat = 'left';
																$('informationBox').style.styleFloat = 'left';
																$('informationBox').show();
																$('addNewProducer').show( );
															}

															else if( 1 == totalhits && doDirect )
																actor.redirectToArticle( transport )

															else
															{
																$('informationBox').style.width = '';
																$('informationBox').style.cssFloat = '';
																$('informationBox').style.styleFloat = '';
																$('addNewProducer').hide( );

																$('resultTabs').show();
																$('informationBox').hide();			
																numPeriods = -1;													
																
																selectedTab = 0;
																
																$('resultTabs').tabber.tabShow(0);
																if(actor.counterCountries <= 0){
																	//$('resultTabs').tabber.tabShow(1);
																	selectedTab = 1;
																	if(actor.counterRegions <= 0){
																		//$('resultTabs').tabber.tabShow(2);
																		selectedTab = 2;
																		if(actor.counterDistricts <= 0){
																			//$('resultTabs').tabber.tabShow(3);
																			selectedTab = 3;
																			if(actor.counterOrigins <= 0){
																				//$('resultTabs').tabber.tabShow(4);
																				selectedTab = 4;
																					if(actor.counterProducers <= 0){
																						//$('resultTabs').tabber.tabShow(5);
																						selectedTab = 5
																			}
																			}
																		}
																	}
																}
																
																arrHits = new Array(actor.counterCountries,actor.counterRegions,actor.counterDistricts,actor.counterOrigins,actor.counterProducers);
																
																if ($('hiddenBrowseStateTabberIndex').value != "" && selectedTab != 5 && arrHits[parseInt($('hiddenBrowseStateTabberIndex').value)] > 0)
																	selectedTab = parseInt($('hiddenBrowseStateTabberIndex').value);

																else if( 0 == selectedTab && 1 != ptype )
																{
																	selectedTab = 1;
																	if(actor.counterRegions <= 0)
																	{
																		selectedTab = 2;
																		if(actor.counterDistricts <= 0)
																		{
																			selectedTab = 3;
																			if(actor.counterOrigins <= 0)
																			{
																				selectedTab = 4;
																				if(actor.counterProducers <= 0)
																					selectedTab = 0;
																			}
																		}
																	}
																}
																
																$('resultTabs').tabber.tabShow(selectedTab);
																
																
																
																var totalhits = actor.counterCountries + actor.counterRegions + actor.counterDistricts + actor.counterOrigins + actor.counterProducers;
																//location.href = "#" + totalhits;
																if(totalhits <= 0)
																{
																	numPeriods = -1;
																	$('resultTabs').hide();
																	$('informationBox').show();
																}
																else
																{
																	numPeriods = -1;
																	$('resultTabs').show();
																	$('informationBox').hide();
																}
																
																//alert(actor.counterProducers);
																/*if ( selectedTab == 5){
																
																	$('resultTabs').hide();
																	$('informationBox').show();
																}*/	
															}
														}
													});
												}
											});
										}
									});
								}
							});
						}
					});
				}
				else
				{
					$('resultTabs').show();
					
					numPeriods = -1;
					
					$('informationBox').style.width = '';
					$('informationBox').style.cssFloat = '';
					$('informationBox').style.styleFloat = '';
					$('addNewProducer').hide( );

					$('informationBox').innerHTML = 'Du måste börja med att klicka på en världsdel och/eller skriva ett sökord';
					$('informationBox').show();
				}
		}
}