// (sk) 20.03.2007
// (sk) 06.05.2008 Modified for compatibility with Prototype 1.6.0.2 and Script.aculo.us 1.8.1
// (c) 2007-2008 klickTel AG. All rights reserved.

// Holds all ktDropDown Elements on a page
ktDropDowns=Array();
updaters = Array();
var current = null;


// The base class
var ktDropDown = Class.create ({
	
	id:'',
	dropdownID:'',
	contentDiv:'',
	insideDiv:'',
	contentDivClassName:'kT_selectBoxFlyout',
	insideDivClassName:'kT_selectBoxFlyoutInner',
	dynamicSpanID:'',
	isOpen:false,
	ajaxURL:'',
	openEffect:null,
	closeEffect:null,
	dropdownWidth:0,
	foldoutWidth:0,
	direction:"right",
	template:null,
	
	initialize: function (id, ajaxURL, openEffect, closeEffect, params, template) {

		this.template=template;
		this.id=id;
		this.contentDiv='dropdown_'+id+'_content';
		this.insideDiv=this.contentDiv+'_inside';
		this.dropdownID='dropdown_'+id;
		this.dynamicSpanID='dropdown_dynamic_'+id;
		
		if(ajaxURL != '') {
			this.ajaxURL=ajaxURL+'&dropdown_id='+encodeURIComponent(this.dropdownID)+'&tpl='+this.template;
		}
		
		if(openEffect=='') openEffect=null;
		if(closeEffect=='') closeEffect=null;

		this.openEffect=openEffect;
		this.closeEffect=closeEffect;

		current=this;
		

		var temp = $H(params);
		temp.each(function(item){
			eval("current."+item.key+"='"+item.value+"';");
		});
		
		
		ktDropDowns.push(this);
	},

	// Closes all open dropdowns
	cleanup: function() {
		ktDropDowns.each(function(dd) {
			dd.close();
		});
	},	
	
	// Closes THIS dropdown
	close: function() {
		if(this.isOpen) {
			if(this.closeEffect != null) {
				eval('new Effect.'+this.closeEffect+'($(this.contentDiv), { duration: 0.2 });');
			} else {
				$(this.contentDiv).hide();
			}
			if ($(this.dropdownID+"_iframe") != null) {
				$(this.dropdownID+"_iframe").remove();
			}
			this.isOpen=false;
		}

	},
	
	
	// Opens THIS dropdown
	open: function() {
		// Cleanup first
		this.cleanup();
		controllerPos = Position.cumulativeOffset($(this.dropdownID));
		controllerDims = $(this.dropdownID).getDimensions();

		// Get and set positions and dimensions
		ddDiv=$(this.contentDiv);
                ddDiv.setStyle({
                    width:(this.foldoutWidth+2)+'px'
                });
		
		dropdownDims = $(this.contentDiv).getDimensions();
		
		if(this.direction=="left"){
                    $(this.contentDiv).setStyle({
                        left:((controllerPos[0]-dropdownDims.width)+controllerDims.width)+"px"
                    });
		} else {
                    if(this.id == "standort_dropdown") {
			  $(this.contentDiv).setStyle({
                            left:((controllerPos[0])+1)+"px" // +1 to get a clean left alignment because of the added 1px white border
                            });
                    } else {
                        $(this.contentDiv).setStyle({
                            left:(controllerPos[0])+"px" // -1 to get a clean left alignment for other boxes
                        });
                    }
		}

		if(this.id == "standort_dropdown") {
		    $(this.contentDiv).setStyle({
                        top:(controllerPos[1]+controllerDims.height)+"px"
                    });
		} else {
                    $(this.contentDiv).setStyle({
                        top:((controllerPos[1]+controllerDims.height)-1)+"px"
                    });
                }
		
		myIframe = new Element('iframe', { id:this.dropdownID+"_iframe" });

		if(this.openEffect != null) {
			eval('new Effect.'+this.openEffect+'(ddDiv, { duration: 0.2 });');
		} else {
			ddDiv.show();
		}
		
		this.isOpen=true;
		$(document.body).appendChild (myIframe);
                myIframe.setStyle({
		  position:"absolute",
		  left:$(this.contentDiv).style.left,
		  top:$(this.contentDiv).style.top,
		  width:$(this.contentDiv).style.width,
		  height:$(this.contentDiv).style.height,
		  zIndex:49000,
		  border:'none',
		  backgroundColor:'white'
		});
	},
	
	
	// Toggles the display of THIS dropdown
	toggle: function() {
		if(this.isOpen) {
			this.close();
		} else {
			this.open();
		}
	},
	
	
	// Is used for handling the assigned events, i.e. CLICK
	eventHandler: function(e) {
		this.toggle();
		Event.stop(e);
	},
	
	
	update: function(html) {
	
		if(html != null) {
			// Content given, so paste into SPAN
			Element.update($(this.dynamicSpanID), html);
		}

		// Get the SPAN dimensions and set the size of the contentDIV accordingly
		ddsDims=$(this.dynamicSpanID).getDimensions();
		ddsWidth=ddsDims.width;

		ddsHeight=ddsDims.height;
		this.foldoutWidth=this.dropdownWidth;
		if(this.dropdownWidth < ddsWidth) {
			this.foldoutWidth=ddsWidth;
		}
		
		$(this.contentDiv).setStyle({
                    height:(ddsHeight+2)+'px' // 2 pixels because of the 2px border!
	        });
                
		// (1) Paste the code from the SPAN into the main DIV
		Element.update($(this.insideDiv), $(this.dynamicSpanID).innerHTML);
		
		// (2) Empty the SPAN content to conserve memory
		//Element.update($(this.dynamicSpanID), '');
	},
	
	
	// Initializes the object, loads the data via AJAX and creates the onclick event handler
	init: function() {
		
		dummySpan = $(this.dynamicSpanID);
		
		if(dummySpan != null) dummySpan.remove();
		document.body.appendChild (dummySpan);
							
		// Show the WAIT cursor to indicate that data is still being retrieved
		$(this.dropdownID).setStyle({
                    cursor:'wait'
		});

		// Remember the dropdown dimensions globally
		dimDDDiv=$(this.dropdownID).getDimensions();
		this.dropdownWidth=dimDDDiv.width;
		
		// Create dynamic DIV containing the list
		ddDiv=new Element('div', { id:this.contentDiv });
                $(document.body).appendChild(ddDiv);
		ddDiv.addClassName(this.contentDivClassName);

                var buttonPos = Position.cumulativeOffset($(this.dropdownID));
		var buttonDimensions = $(this.dropdownID).getDimensions();

                ddDiv.setStyle({
                    display:'none',
                    left:buttonPos[0]+"px",
                    top: (buttonDimensions.height+buttonPos[1]-1)+"px"
                });

			
		// Create the AJAX content DIV
		ddXDiv=new Element('div', { id:this.insideDiv });
                ddDiv.appendChild(ddXDiv);
                ddXDiv.setStyle({
                    display:'block',
                    cursor:'default'  // The inside DIV should not have the pointer automatically
                });
		ddXDiv.addClassName(this.insideDivClassName);


		// Append this object to the corresponding element in the DOM tree
		if($(this.dropdownID).dropdown == null) {
			$(this.dropdownID).dropdown=this;
		}
		
		if(this.ajaxURL == '') {
		
			this.update();

			// Add the event handler
			$(this.dropdownID).observe('click', this.eventHandler.bindAsEventListener(this));
			
			// Modify the cursor to reflect the status change
			$(this.dropdownID).setStyle({
                            cursor:'pointer'
			 });
		} else {
			// Use AJAX to fill the DIV
							
			myAjax = new Ajax.Request (
				this.ajaxURL,
				{
					method:'get',
					evalScripts: true,
					onSuccess: function(req,json) {
						cdnID=json['id'];
						resHTML=req.responseText;
						if($(cdnID).dropdown != null) {
							$(cdnID).dropdown.update(resHTML);
						}
						$(cdnID).observe('click', $(cdnID).dropdown.eventHandler.bindAsEventListener($(cdnID).dropdown));

						// Modify the cursor to reflect the status change
                                                $(cdnID).setStyle({
                                                    cursor:'pointer'
                                                });
					}
				}
			);
		}
	}
	
});


// Global function used to close all dropdowns if the user clicks anywhere on the page
function ktDropDownCloseHandler(e) {
	if(ktDropDowns.length) {
		mouseX=Event.pointerX(e);
		mouseY=Event.pointerY(e);
		withinDropDown=false;
		ktDropDowns.each(function (dd) {
			if(Position.within($(dd.contentDiv), mouseX, mouseY) || Position.within($(dd.dropdownID), mouseX, mouseY)) {
				withinDropDown=true;
			}
		});
		if(!withinDropDown) {
			ktDropDowns[0].cleanup();
		}
	}
}

function ktFillField (field, value) {
	if ($(field) != null) {
		$(field).value = value;
	}
}

function ktStandortFillFields (zipId, cityId, streetId, housenumberId, countryId, longitudeId, latitudeId, zip ,city, street, housenumber, country, longitude, latitude) {
	if (zipId == cityId) {
		zipCity = (zip+" "+city).strip();
		ktFillField (zipId, zipCity);
	} else {
		ktFillField (zipId, zip);
		ktFillField (cityId, city);
	}
	
	if (streetId == housenumberId) {
		streetNumber = (street+" "+housenumber).strip();
		ktFillField (streetId, streetNumber);
	} else {
		ktFillField (streetId, street);
		ktFillField (housenumberId, housenumber);
	}
	ktFillField (countryId, country);
	ktFillField (longitudeId, longitude);
	ktFillField (latitudeId, latitude);
	ktDropDowns.each(function (dd) {
		ktDropDowns[0].cleanup();	
	});
}

function ktStandortDeleteHistory () {
	historyLists = document.getElementsByClassName("standortHistory");
	historyLists.each (function (list) {
		Element.update (list, "");
	});
	
    var myRequest = new Ajax.Request (
    	"/global/ajax/standorte.php",
    	{
    		method:'get',
    		parameters:'action=clearCookie'
    	}
    );
}



// Every click on a page is also piped through this event handler
// so that dropdowns are closed if the user clicks outside of one
Event.observe(document, 'click', ktDropDownCloseHandler);


