String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

var FManager = null;

Manager = Class.create({

	samples : ["Toyota Corolla Ankara resimli 2000-2010", 
	           "Opel Corsa İzmir 20000 liraya kadar resimli",
	           "İstanbul Corona 1994",
	           "İstanbul Şahin Manuel beyaz",
	           "Ankara tofaş sahibinden resimli 2000-2009 LPG",
	           "LPG Adana Fiat Uno",
	           "15000 Liradan ucuz reno",
	           "25000-35000 TL BMW Ankara resimli 5-8 yasinda"],
	
	initialize: function() {
		this.initializeElements();
		this.hookEvents();
		//this.focus.bind(this).delay(0.2);
		this.initializeExtras();	
	},
	
	initializeExtras: function() {
		if (setup.comparisionEnabled)
		{
			new Comparator();
		}
		if (setup.averagePricesEnabled)
		{
			this.displayAvegares();
		}
		if (setup.minmaxPricesEnabled)
		{
			this.displayMinMax();
		}
		this.enUygun 		= new EnUygun();
		this.sorter 		= new Sorter(this);
		this.poll			= new Poll();
		this.priceAnalyzer	= new PriceAnalyzeManager();
		this.contactUs		= new ContactUsManager();
		this.featureManager	= new ResultDisplayFeatureManager();
	},
	
	initializeElements: function() {
		this.keywords				= $("txtKeywords");
		this.searchIcon				= $("searchIcon");
		this.keywordsTable			= $("keywordsTable");
	},
	
	hookEvents: function() {
		this.hookTopContainer();
		if (this.searchIcon)
		{
			this.searchIcon.observe("click",	this.clicked.bindAsEventListener(this));
			this.keywords.observe("keypress",	this.keyPressed.bindAsEventListener(this));
			this.initializeSampler();
		}
	},
	
	initializeSampler: function() {
		this.keywords.sampling = false;
		this.keywords.observe("focus", 		this.searchKeyFocused.bindAsEventListener(this));
		this.keywords.observe("blur", 		this.searchKeyBlured.bindAsEventListener(this));
		this.keywords.observe("keydown", 	this.searchKeyChanged.bindAsEventListener(this));
		this.searchKeyBlured(null);
	},
	
	hookTopContainer: function() {
		var container = $("topContainer");
		if (container)
		{
			if (top.location.href.indexOf("home.php") == -1)
			{
				container.observe("click",	function() {top.location = "home.php";});
			} else
			{
				container.title = "5 İleri - Araba Arama Motoru";
				container.setStyle({cursor:"default"});
			}
		}
	},
	
	clicked: function(e) {
		this.search();
	},
	
	keyPressed: function(e) {
		switch (e.keyCode)
		{
			case Event.KEY_RETURN:
				this.search();
				break;
//			default:
//				if (this.keywords.sampling)
//				{
//					this.keywords.sampling = false;
//					this.keywords.removeClassName("silverKeywords");
//					this.keywords.setValue("");
//				}
//				break;
		}
	},
	
	isValueSample: function(value) {
		var result = false;
		for (var index = 0; index < this.samples.length && !result; index++)
		{
			result = (this.samples[index] == value);
		}
		return result;
	},
	
	getRandomSample: function() {
		return this.samples[Math.floor(Math.random()*this.samples.length)];
	},
	
	searchKeyChanged: function(e) {
		//this.keywords.sampling = (this.keywords.getValue().trim() == "");
	},
	
	searchKeyFocused: function(e) {
		if (this.keywords.sampling)
		{
			this.keywords.sampling = false;
			this.keywords.removeClassName("silverKeywords");
			this.keywords.setValue("");
		}
	},
	
	searchKeyBlured: function(e) {
		this.keywords.sampling = (this.keywords.getValue().trim() == "");
		if (this.keywords.sampling)
		{
			var value = this.keywords.getValue();
			if (value == "" || this.isValueSample(value))
			{
				this.keywords.setValue(this.getRandomSample());
				this.keywords.addClassName("silverKeywords");
			} else
			{
				this.keywords.removeClassName("silverKeywords");
				this.keywords.sampling = false;
			}
		}
	},
	
	search: function(keywords) {
		if (!keywords)
		{
			keywords = this.keywords.getValue().trim();
		}
		if (keywords && keywords != "")
		{
			var url = "search.php?q=" + keywords + this.sorter.serialize();
			top.location.href = url;
		}
	},
	
	focus: function() {
		if (this.keywords && top.location.href.indexOf("search") == -1)
		{
			this.keywords.focus();
		}
	},
		
	displayAvegares: function() {
		var averages = $$('div[class="averages"]');
		if (averages)
		{
			averages.each(function(average) {
				new Ajax.Updater(average, 'ajax/average.php', 
					{
 						parameters: { 
 							m: average.readAttribute('model'),
 							y: average.readAttribute('year')
 						}
					});				
			}.bind(this));
		}
	},
	
	displayMinMax: function() {
		var minMaxs = $$('div[class="minmax"]');
		if (minMaxs)
		{
			minMaxs.each(function(minMax) {
				new Ajax.Updater(minMax, 'ajax/minmaxprices.php', 
					{
 						parameters: { 
 							m: minMax.readAttribute('model'),
 							y: minMax.readAttribute('year'),
 							t: minMax.readAttribute('type')
 						}
					});				
			}.bind(this));
		}
	}
});

Sorter = Class.create({

	initialize: function(owner) {
		this.owner		                = owner;
		this.sortAdvertDate      	    = $("sortAdvertDate");
		this.sortYear		            = $("sortYear");
		this.sortVolume     	    	= $("sortVolume");
		this.sortKm	                	= $("sortKm");
		this.sortPrice      	    	= $("sortPrice");
		this.sortOrder                  = $("sortOrder");
		this.sortOrderEditorContainer   = $("sortOrderEditorContainer");
		this.sortOrderEditor            = $("sortOrderEditor");
        this.sortOrderEditorData        = $("sortOrderEditorData");
        this.btnApplySort               = $("btnApplySort");
        this.imgSortOrder               = $("imgSortOrder");
		this.hookEvents();
	},
	
	hookEvents: function() {
		var clickHandler        = this.click.bindAsEventListener(this);
		var mouseOverHandler    = this.mouseOver.bindAsEventListener(this);
		var mouseOutHandler     = this.mouseOut.bindAsEventListener(this);
		if (this.sortAdvertDate)
		{
    		this.observeEvents(this.sortAdvertDate, clickHandler, mouseOverHandler, mouseOutHandler);
    		this.observeEvents(this.sortYear,       clickHandler, mouseOverHandler, mouseOutHandler);
    		this.observeEvents(this.sortVolume,     clickHandler, mouseOverHandler, mouseOutHandler);
    		this.observeEvents(this.sortKm,         clickHandler, mouseOverHandler, mouseOutHandler);
    		this.observeEvents(this.sortPrice,      clickHandler, mouseOverHandler, mouseOutHandler);
        /*    		
			this.sortAdvertDate.observe("click", clickHandler);
			this.sortYear.observe("click", clickHandler);
			this.sortVolume.observe("click", clickHandler);
			this.sortKm.observe("click", clickHandler);
			this.sortPrice.observe("click", clickHandler);
		*/
			this.sortOrder.observe("click", this.sortOrderEditorClick.bindAsEventListener(this));
			this.btnApplySort.observe("click", this.applySortClick.bindAsEventListener(this));
			$$('img[class="sortMoveDown"]').invoke("observe", "click", this.moveDownClick.bindAsEventListener(this));
			$$('img[class="sortMoveUp"]').invoke("observe", "click", this.moveUpClick.bindAsEventListener(this));
		}
	},
	
	observeEvents: function(element, clickHandler, mouseOverHandler, mouseOutHandler) {
    	element.observe("click",        clickHandler);
    	element.observe("mouseover",    mouseOverHandler);
    	element.observe("mouseout",     mouseOutHandler);
	},
	
	click: function(e) {
		this.switchSort(Event.element(e));
		this.owner.search();
	},
	
	mouseOver: function(e) {
	    var element = Event.element(e);
	    if (element.hasClassName("sortNone"))
	    {
	        element.addClassName("mouseOver");
	    }
	},
	
	mouseOut: function(e) {
	    var element = Event.element(e);
	    if (element.hasClassName("mouseOver"))
	    {
	        element.removeClassName("mouseOver");
	    }
	},
	
	sortOrderEditorClick: function(e) {
	    if (this.editorVisible)
	    {
	        //Effect.Fade(this.sortOrderEditorContainer, {duration: 1});
	        this.sortOrderEditorContainer.hide();
			this.imgSortOrder.src = "themes/images/plus.gif";
			this.editorVisible = false;
	    } else
	    {
			//Effect.Appear(this.sortOrderEditorContainer, {duration: 1});
			this.sortOrderEditorContainer.show();
	        this.imgSortOrder.src = "themes/images/minus.gif";
	        this.editorVisible = true;
	    }
	},
	
	applySortClick: function(e) {
		this.owner.search();
	},

	moveDownClick: function(e) {
    	this.moveRowDown(this.findParentRow(Event.element(e)));
	},
	
	moveUpClick: function(e) {
	    this.moveRowUp(this.findParentRow(Event.element(e)));
	},
	
	findParentRow: function(element) {
	    while (element && element.tagName != "TR")
	    {
	        element = element.up();
	    }
	    return element;
	},
	
	moveRowDown: function(row) {
	    this.switchRows(row, this.sortOrderEditorData.rows[row.rowIndex+1]);
	},
	
	moveRowUp: function(row) {
	    this.switchRows(row, this.sortOrderEditorData.rows[row.rowIndex-1]);
	},
	
	switchRows: function(sourceRow, destRow) {
		sourceRow 	= Element.extend(sourceRow);
		destRow		= Element.extend(destRow);
		this.switchCaptions(sourceRow, destRow);
	    this.switchCombos(sourceRow, destRow);
	    this.switchKeys(sourceRow, destRow);
	},
	
	switchCaptions: function(sourceRow, destRow) {
	    var sourceCell          = sourceRow.cells[0];
	    var destCell            = destRow.cells[0];
	    var pushCell            = sourceCell.innerHTML;
	    sourceCell.innerHTML    = destCell.innerHTML;
	    destCell.innerHTML      = pushCell;
	},
	
	switchCombos: function(sourceRow, destRow) {
	    var sourceCombo             = this.getCombo(sourceRow);
	    var destCombo               = this.getCombo(destRow);
	    var pushCombo               = sourceCombo.selectedIndex;
	    sourceCombo.selectedIndex   = destCombo.selectedIndex;
	    destCombo.selectedIndex     = pushCombo;
	},
	
	switchKeys: function(sourceRow, destRow) {
		var sourceKey = sourceRow.readAttribute("key");
		sourceRow.writeAttribute("key", destRow.readAttribute("key"));
		destRow.writeAttribute("key", sourceKey);
	},
	
	getCombo: function(row) {
		var cell = Element.extend(row.cells[1]);
	    return cell.down();
	},
	
	switchSort: function(element) {
		if (element)
		{
			if (element.hasClassName("sortAsc"))
			{
				element.removeClassName("sortAsc");
				element.addClassName("sortDesc");
			} else if (element.hasClassName("sortDesc"))
			{
				element.removeClassName("sortDesc");
				element.addClassName("sortNone");
			} else
			{
				element.removeClassName("sortNone");
				element.addClassName("sortAsc");
			}
		}
	},
	
	serializeFieldOrder: function() {
	    var row     	= null;
	    var key     	= null;
	    var value   	= "";
	    var result  	= "";
	    this.hasAnyData	= false;
	    for (var index = 0; index < this.sortOrderEditorData.rows.length-1; index++)
	    {
	        row = Element.extend(this.sortOrderEditorData.rows[index]);
	        key = row.readAttribute("key");
	        if (key)
	        {
	            value = this.getCombo(row).getValue();
                if (result != "")
                {
                    result += "_";
                }
                if (!this.hasAnyData && value != "-")
                {
                	this.hasAnyData = true;
                }
                result += key + ":" + value;
	        }
	    }
	    return result;
	},
	
	serialize: function() {
		this.hasAnyData 	= false;
		var serializedData 	= this.editorVisible ? this.serializeFieldOrder() : null;
		
		var result = this.hasAnyData ?
				{
					sr: serializedData
				} :
				{
					ad: this.check(this.sortAdvertDate),
					yr: this.check(this.sortYear),
					vl: this.check(this.sortVolume),
					km: this.check(this.sortKm),
					pr: this.check(this.sortPrice)
				}
		result = Object.toQueryString(result);
		return (result && result != "" ? "&" + result : "");
	},
	
	check: function(element) {
		if (element)
		{
			if (element.hasClassName("sortAsc"))
			{
				return "a";
			}
			if (element.hasClassName("sortDesc"))
			{
				return "d";
			}
		}
		return null;
	}
});

Comparator = Class.create({

	initialize: function() {
		this.visible 		= false;
		this.MAX_ITEMS		= 5;
		this.elements 		= $A(new Array());
		this.startButton	= $("startCompareButton");
		this.clearButton	= $("clearCompareButton");
		this.closeButton	= $("closeCompareButton");
		this.createBaseUI();
	},

	createBaseUI: function() {
		this.outerContainer = $("comparatorOuterContainer");
		if (this.outerContainer)
		{
			this.outerContainer.hide();
			this.container = $("comparator");
			this.startButton.disable();
			this.clearButton.disable();
			this.listen();
		}
	},

	listen: function() {
		this.checks = $$('input[class="check"]');
		if (this.checks)
		{
			this.checks.invoke("observe", "click", this.clickHandler.bindAsEventListener(this));
		}
		this.startButton.observe("click", this.startCompareClick.bindAsEventListener(this));
		this.clearButton.observe("click", this.clearCompareClick.bindAsEventListener(this));
		this.closeButton.observe("click", this.closeCompareClick.bindAsEventListener(this));
	},

	clickHandler: function(e) {
		var input = Event.element(e);
		if (input.checked)
		{
			this.append(input);
		} else
		{
			this.remove(input);
		}
	},

	append: function(input) {
		if (this.elements.size() < this.MAX_ITEMS)
		{
			this.elements.push(new CompareElement(this, input));
			this.disableChecks();
		}
		if (this.elements.size() > 0)
		{
			this.show();
		}
		this.checkOperationButtons();
	},

	remove: function(input) {
		if (input.item)
		{
			input.item.remove();
		}
	},

	disableChecks: function() {
		if (this.elements.size() >= this.MAX_ITEMS)
		{
			this.checks.each(function(check) {
				if (!check.checked)
				{
					check.disable();
				}
			}.bind(this));
		}
	},

	enableChecks: function() {
		if (this.elements.size() < this.MAX_ITEMS)
		{
			this.checks.each(function(check) {
				if (!check.checked)
				{
					check.enable();
				}
			}.bind(this));
		}
	},
	
	checkOperationButtons: function() {
		if (this.elements.size() > 1)
		{
			this.startButton.enable();
		} else
		{
			this.startButton.disable();
		}
		if (this.elements.size() > 0)
		{
			this.clearButton.enable();
		} else
		{
			this.clearButton.disable();
		}
	},

	show: function() {
		if (!this.visible)
		{
			Effect.Appear(this.outerContainer, {duration: 1});
			this.visible = true;
		}
	},
	
	hide: function() {
		if (this.visible)
		{
			Effect.Fade(this.outerContainer, {duration: 1});
			this.visible = false;
		}
	},

	serialize: function() {
		var result = "";
		this.elements.each(function(element) {
			if (result != "")
			{
				result += ",";
			}
			result += element.dataId;
		}.bind(this));
		return result;
	},

	startCompareClick: function(e) {
		window.top.location = "compare.php?q=" + this.serialize();
	},
	
	clearCompareClick: function(e) {
		this.elements.invoke("remove");
	},
	
	closeCompareClick: function(e) {
		this.clearCompareClick();
		this.hide();
	}
});

CompareElement = Class.create({

	initialize: function(owner, input) {
		this.owner		= owner;
		this.index		= owner.elements.size();
		this.input 		= input;
		input.item		= this;
		this.dataId		= input.readAttribute("dataid");
		this.imageSrc	= input.readAttribute("image");
		this.createUI();
	},
	
	createUI: function() {
		this.element = new Element("DIV", {className:"compareItem"});
		this.element.insert(this.createImage());
		this.element.insert(new Element("BR"));
		this.element.insert(this.createRemoveButton());
		this.owner.container.insert(this.element);
	},
	
	createImage: function() {
		return new Element("IMG", {
			width		: 100,
			height		: 75,
			className	: "thumbnail",
			border		: 0,
			src			: this.imageSrc
		});
	},
	
	createRemoveButton: function() {
		var input = new Element("INPUT", {
			type	: "button",
			value	: "Kaldır"
		});
		input.setStyle({width:"110px", marginTop : "10px"});
		input.observe("click", this.removeClick.bindAsEventListener(this));
		return input;
	},
	
	removeClick: function(e) {
		this.remove();
	},
	
	remove: function() {
		this.input.checked = false;
		this.element.remove();
		this.owner.element
		this.owner.elements = this.owner.elements.without(this);
		this.owner.enableChecks();
		this.owner.checkOperationButtons();
		if (this.owner.elements.size() == 0)
		{
			this.owner.closeCompareClick();
		}
	}
});

Paginator = Class.create({

	initialize: function(maxentries, container, options) {
		this.container		= $(container);
		this.maxentries		= (!maxentries || maxentries < 0) ? 1 : maxentries;
		this.clickHandler	= this.click.bindAsEventListener(this);
		this.options 	= {
			items_per_page		: 10,
			num_display_entries	: 10,
			current_page		: 0,
			num_edge_entries	: 2,
			link_to				: "#",
			prev_text			: "Prev",
			next_text			: "Next",
			ellipse_text		: "...",
			prev_show_always	: true,
			next_show_always	: true,
			url					: null
		};
		Object.extend(this.options, options || {});
		this.options.items_per_page = (!this.options.items_per_page || this.options.items_per_page < 0) ? 1 : this.options.items_per_page;
		if (this.maxentries > this.options.items_per_page)
		{
			this.drawLinks();
		}
	},
	
	click: function(e) {
		var element = Event.element(e);
		var pageId 	= element.pageId;
	},
	
	numPages: function() {
		return Math.ceil(this.maxentries / this.options.items_per_page);
	},
	
	getInterval: function() {
		var ne_half		= Math.ceil(this.options.num_display_entries/2);
		var np			= this.numPages();
		var upper_limit	= np - this.options.num_display_entries;
		var start		= this.options.current_page > ne_half ? Math.max(Math.min(this.options.current_page-ne_half, upper_limit), 0) : 0;
		var end			= this.options.current_page > ne_half ? Math.min(this.options.current_page+ne_half, np) : Math.min(this.options.num_display_entries, np);
		return [start,end];
	},
	
	pageSelected: function(page_id, evt) {
		this.options.current_page = page_id;
		this.drawLinks();
	},
	
	clear: function() {
		var children = this.container.childElements();
		if (children && children.size() > 0)
		{
			children.invoke("remove");
		}
	},
	
	appendItem: function(page_id, np, appendopts) {
		var link	= null;
		page_id 	= page_id < 0 ? 0 : (page_id < np ? page_id : np - 1);
		appendopts 	= Object.extend({text:page_id+1, classes:null}, appendopts || {});
		if (page_id == this.options.current_page)
		{
//			link = new Element("SPAN", { className:"current"});
			link = new Element("SPAN");
			link.addClassName("current");
		} else
		{
			link = new Element("A", { 
				href  : this.options.url.replace("#{page}", page_id),
				title : (page_id + 1) + ". Sayfaya git..."
			});
			link.pageId = page_id;
		}
		link.update(appendopts.text);
		if (appendopts.classes)
		{
			link.addClassName(appendopts.classes);
		}
		this.container.insert(link);
	},
	
	appendEllipsis: function() {
		var ellipsis = new Element("SPAN");
		ellipsis.update(this.options.ellipse_text);
		this.container.insert(ellipsis);
	},
	
	drawLinks: function() {
		this.clear();
		var interval	= this.getInterval();
		var np			= this.numPages();
		
		if (this.options.prev_text && (this.options.current_page > 0 || this.options.prev_show_always))
		{
			this.appendItem(this.options.current_page-1, np, {text:this.options.prev_text, classes:"prev"});
		}

		if (interval[0] > 0 && this.options.num_edge_entries > 0)
		{
			var end = Math.min(this.options.num_edge_entries, interval[0]);
			for(var index = 0; index < end; index++)
			{
				this.appendItem(index, np);
			}
			if (this.options.num_edge_entries < interval[0] && this.options.ellipse_text)
			{
				this.appendEllipsis();
			}
		}
		
		for (var index = interval[0]; index < interval[1]; index++)
		{
			this.appendItem(index, np);
		}
		
		if (interval[1] < np && this.options.num_edge_entries > 0)
		{
			if (np - this.options.num_edge_entries > interval[1] && this.options.ellipse_text)
			{
				this.appendEllipsis();
			}
			var begin = Math.max(np - this.options.num_edge_entries, interval[1]);
			for(var index = begin; index < np; index++)
			{
				this.appendItem(index, np);
			}
		}
		
		if (this.options.next_text && (this.options.current_page < np-1 || this.options.next_show_always))
		{
			this.appendItem(this.options.current_page+1,{text:this.options.next_text, classes:"next"});
		}
	},
	
	selectPage: function(page_id) {
		this.pageSelected(page_id);
	},
	
	prevPage: function() { 
		if (this.options.current_page > 0)
		{
			this.pageSelected(this.options.current_page - 1);
			return true;
		}
		return false;
	},
	
	nextPage: function() { 
		if (this.options.current_page < numPages() - 1)
		{
			this.pageSelected(this.options.current_page + 1);
			return true;
		}
		return false;
	}
});

EnUygun = Class.create({

	initialize: function() {
		this.container	 			= $("enuygunCreditResults");
		this.resultsContainer		= $("creditResultsContainer");
		this.calculateCreditButton	= $("calculateCreditButton");
		this.paymentTerms			= $("paymentTerms");
		this.capital				= $("capital");
		this.hookEvents();
	},
	
	hookEvents: function() {
		if (this.calculateCreditButton && this.capital)
		{
			this.calculateCreditButton.observe("click", this.calculateClick.bindAsEventListener(this));
			this.capital.observe("keypress", this.capitalKeyPress.bindAsEventListener(this));
		}
	},
	
	calculateClick: function(e) {
		this.calculate(this.capital.getValue(), this.paymentTerms.getValue());
	},
	
	calculate: function(capital, terms) {
		this.clear();
		this.capital.setValue(capital);
		new Ajax.Updater(this.resultsContainer, 'ajax/enuygunautocredit.php', 
					{
 						parameters: { 
 							capi: capital,
 							term: terms
 						}
					});			
		this.show();	
	},
	
	clear: function() {
		this.resultsContainer.immediateDescendants().invoke("remove");
		this.resultsContainer.insert(this.createWaitImage());
	},
	
	createWaitImage: function() {
		return new Element("IMG", {
			src 	: setup.root + "images/loading.gif",
			width	: 16,
			height	: 16
		});
	},
	
	show: function() {
		if (!this.visible)
		{
			Effect.Appear(this.container, {duration: 1});
			this.visible = true;
		}
	},
	
	hide: function() {
		if (this.visible)
		{
			Effect.Fade(this.container, {duration: 1});
			this.visible = false;
		}
	},
	
	capitalKeyPress: function(e) {
		var keyCode = e.keyCode;
		switch (keyCode)
		{
			case 0:
				if (!(e.charCode >= 48 && e.charCode <= 57))
				{
					Event.stop(e);
					return false;
				}
				break;
			case Event.KEY_RIGHT:
			case Event.KEY_LEFT:
			case Event.KEY_HOME:
			case Event.KEY_END:
			case Event.KEY_TAB:
			case Event.KEY_DELETE:
			case Event.KEY_BACKSPACE:
				break;
			case Event.KEY_RETURN:
				var value = parseInt(this.element.getValue());
				if (!isNaN(value))
				{
					this.calculate(this.capital.getValue(), this.paymentTerms.getValue());
				} else
				{
					alert("Lutfen bir rakam giriniz.");
				}
				break;
			default:
				Event.stop(e);
				return false;	
		}
	}
});

Poll = Class.create({

	initialize: function() {
		this.pollData = $("pollData");
		if (this.pollData)
		{
			this.pollQuestion	= $("pollQuestion");
			this.pollThankYou	= $("pollThankYou");
			this.pollFooter     = $("pollFooter");
			this.question		= pollQuestion;
			$("submitPoll").observe("click", this.submitAnswer.bindAsEventListener(this));
		}
	},

	submitAnswer: function(e) {
		var params = this.serializeAnswer();
		if (params)
		{
			new Ajax.Request("ajax/poll.php",
					{
						method 		: "get",
						parameters	: params,
						onComplete	: this.requestCompleted.bind(this)
					});
		}
	},
	
	requestCompleted: function(transport) {
	    this.pollData.hide();
		this.pollQuestion.hide();
		this.pollThankYou.show();
		this.pollFooter.hide();
	},
	
	serializeAnswer: function() {
		var result = "";
		switch (this.question.fld_type)
		{
			case 0:
			case 1:
				result = this.serializeSingleSelect();
				break;
			case 2:
				result = this.serializeMultiSelect();
				break;
			case 3:
				result = this.serializeFreeText();
		}
		return (result != "") ? {q: this.question.fld_id, a: result} : null;
	},
	
	serializeSingleSelect: function() {
		var index 	= 0;
		var result 	= false;
		var input	= null;
		while (!result)
		{
			input = $("question_" + index);
			if (!input)
			{
				break;
			}
			result = input.checked ? input.value : false;
			index++;
		}
		return result;
	},
	
	serializeMultiSelect: function() {
		var index 	= 0;
		var result 	= "";
		var input	= null;
		while (true)
		{
			input = $("question_" + index);
			if (!input)
			{
				break;
			}
			if (input.checked)
			{
				if (result != "")
				{
					result += "|";
				}
				result += input.value;
			}
			index++;
		}
		return result;
	},

	serializeFreeText: function() {
		return $("question").getValue();
	}
});

PriceAnalyze = Class.create({
	
	initialize: function(image) {
		this.image			= $(image);
		this.id 			= this.image.readAttribute("row");
		this.wait			= $("priceAnalysisWait_" + this.id);
		this.container		= $("priceAnalysis_" + this.id);
		this.priceRow		= $("priceAnalysisContainer_" + this.id);
		this.image.observe("click", this.click.bindAsEventListener(this));
	},
	
	click: function(e) {
		this.processExpandCollapse();
	},

	processExpandCollapse: function() {
		if (!this.expanded)
		{
			this.expand();
		} else
		{
			this.collapse();
		}
	},
	
	expand: function() {
		if (!this.loaded)
		{
			this.load();
		} else
		{
			this.expandFinished();
		}
	},
	
	load: function() {
		this.wait.show();
		new Ajax.Request(
				"ajax/priceanalyze.php",
				{
					method		: "get",
					parameters	: {i : this.id},
					onComplete	: this.loadResponse.bind(this)
				}
		);
	},
	
	loadResponse: function(transport) {
		var json = transport.responseText.evalJSON();
		if (json.status == 0)
		{
			var element = null;
			for (var property in json)
			{
				element = $(property);
				if (element) 
				{
					element.update(eval("json." + property));
				}
			}
			this.expandFinished(json);
		}
		this.loaded = true;
	},
	
	expandFinished: function(json) {
		this.wait.hide();
		this.image.src 	= "themes/images/up.gif";
		this.expanded	= true;
		this.priceRow.removeClassName("bottomBorder");
		this.container.show();
	},
	
	collapse: function() {
		this.image.src 	= "themes/images/down.gif";
		this.expanded	= false;
		this.container.hide();
		this.priceRow.addClassName("bottomBorder");
	}
});

PriceAnalyzeManager = Class.create({
	
	initialize: function() {
		var images = $$('img[class="priceAnalysisButton"]');
		if (images)
		{
			for (var index = 0; index < images.size(); index++)
			{
				
				new PriceAnalyze(images[index]);
			}
		}
	}
});

ContactUsManager = Class.create({
	
	initialize: function() {
		if ($("contact"))
		{
			this.cmbDepartment 	= $("cmbDepartment");
			this.txtSubject		= $("txtSubject");
			this.txtData 		= $("txtData");
			this.txtName 		= $("txtName");
			this.txtEMail 		= $("txtEMail");
			this.txtCaptcha 	= $("txtCaptcha");
			this.btnSend 		= $("btnSend");
			this.txtPleaseWait 	= $("txtPleaseWait");
			this.txtError 		= $("txtError");
			this.btnSend.observe("click", this.sendClick.bindAsEventListener(this));
			this.focus.bind(this).delay(0.2);
		}
	},
	
	focus: function() {
		this.cmbDepartment.focus();
	},
	
	validateEMail: function() {
		var r = /^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-]+\.[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?$/;
		return (!r.test(this.txtEMail.getValue())) ?
			"Lütfen geçerli bir e-posta adresi giriniz.\n" : "";
	},
	
	validatePresence: function() {
		return ((this.txtSubject.getValue() != "") &&
					(this.txtData.getValue() != "") &&
					(this.txtName.getValue() != "") &&
					(this.txtEMail.getValue() != "") &&
					(this.txtCaptcha.getValue() != "")) ?
				"" : "Bütün alanların girilmesi zorunludur!";
	},
	
	validateData: function() {
		var msg = this.validateEMail() + this.validatePresence();
		if (msg != "")
		{
			alert(msg);
			return false;
		}
		return true;
	},
	
	getParameters: function() {
		return {
			d : this.cmbDepartment.getValue(),
			s : this.txtSubject.getValue(),
			t : this.txtData.getValue(),
			n : this.txtName.getValue(),
			e : this.txtEMail.getValue(),
			c : this.txtCaptcha.getValue()
		};
	},
	
	sendClick: function(e) {
		if (this.validateData())
		{
			this.btnSend.disable();
			this.txtError.hide();
			this.txtPleaseWait.show();
			new Ajax.Request("ajax/contact.php",
					{
						method 		: "get",
						parameters	: this.getParameters(),
						onComplete	: this.requestCompleted.bind(this)
					});
		}
	}, 
	
	requestCompleted: function(transport) {
		this.btnSend.enable();
		var json = transport.responseText.evalJSON();
		if (json.status != 0)
		{
			this.txtPleaseWait.hide();
			this.txtError.show();
		} else
		{
			alert("İletişim talebiniz alındı. En kısa zamanda size konu ile ilgili dönüş yapacağız.");
			top.location = "home.php";
		}
	}
});

ResultDisplayFeatureManager = Class.create({
	
	initialize: function() {
		this.containers = $$('div[type="analysis"]');
		if (this.containers && this.containers.size() > 0)
		{
			this.responseHandler = this.response.bind(this);
			this.prepare();
		}
	},
	
	prepare: function() {
		this.containers.each(function(container) {
			container.analysisContainer = new AnalysisContainer(this, container);
		}.bind(this));
	},
	
	load: function(tab) {
		if (tab.dataElement)
		{
			this.showDataElement(tab);
		} else
		{
			this.request(tab);
		}
	},
	
	request: function(tab) {
		if (!this.operatingTab)
		{
			this.operatingTab = tab;
			tab.update("Bekleyiniz...");
			new Ajax.Request(
					"ajax/features.php",
					{
						method		: "get",
						parameters	: {o: tab.tabType, i : tab.analysisContainer.dataId},
						onComplete	: this.responseHandler
					});
		}
	},
	
	response: function(transport) {
		var analysisContainer			= this.operatingTab.analysisContainer;
		var dataContainer 				= analysisContainer.dataContainer;
		dataContainer.innerHTML 		+= transport.responseText;
		this.operatingTab.responseText	= transport.responseText;
		this.operatingTab.dataElement	= $(this.operatingTab.dataElementId);
		this.showDataElement(this.operatingTab);
		this.operatingTab = null;
	},
	
	showDataElement: function(selectedTab) {
		var dataElement 		= null; 
		var analysisContainer	= selectedTab.analysisContainer;
		var dataContainer 		= analysisContainer.dataContainer;
		analysisContainer.tabs.each(function(tab) {
			if (tab != selectedTab && tab.dataElement)
			{
				$(tab.dataElementId).hide();
			}
		}.bind(this));
		analysisContainer.tabbedPage.removeClassName("bottomMargin");
		$(selectedTab.dataElementId).show();
		dataContainer.show();
		selectedTab.responseText.evalScripts();
		selectedTab.update(selectedTab.originalText);
		var intEdits = $$("#" + selectedTab.dataElementId + ' input[editType="intEdit"]');
		if (intEdits && intEdits.size() > 0)
		{
			intEdits.invoke("observe", "keypress", this.intFieldKeyPress.bindAsEventListener(this));
		}
		this.selectedTab = selectedTab;
	},
	
	requestCredit: function(elementId, dataId, capital, currency, terms) {
		if (!this.operatingTab)
		{
			this.operatingTab = this.selectedTab;
			this.operatingTab.update("Bekleyiniz...");
			this.requestCreditElement = $(elementId);
			new Ajax.Request(
					"ajax/features.php",
					{
						method		: "get",
						parameters	: {
							o		: "credits", 
							i 		: dataId,
							capi 	: $(capital).getValue(),
							term	: $(terms).getValue(),
							curr	: $(currency).getValue()
						},
						onComplete	: this.requestCreditResponse.bind(this)
					});
		}
	},
	
	requestCreditResponse: function(transport) {
		this.requestCreditElement.remove();
		var analysisContainer	= this.selectedTab.analysisContainer;
		var dataContainer 		= analysisContainer.dataContainer;
		dataContainer.innerHTML	+= transport.responseText;
		transport.responseText.evalScripts();
		this.selectedTab.update(this.selectedTab.originalText);
		this.operatingTab = null;
	},
	
	intFieldKeyPress: function(e) {
		if ((e.charCode) && (e.keyCode==0))
		{
			charCode = e.charCode;
			keyCode  = e.keyCode;
		} else {
			charCode 	= e.keyCode;
			keyCode		= 0;
		}
		switch (keyCode)
		{
			case 0:
				if (!(charCode >= 48 && charCode <= 57))
				{
					Event.stop(e);
					return false;
				}
				break;
			case Event.KEY_RIGHT:
			case Event.KEY_LEFT:
			case Event.KEY_HOME:
			case Event.KEY_END:
			case Event.KEY_TAB:
			case Event.KEY_DELETE:
			case Event.KEY_BACKSPACE:
				break;
			default:
				Event.stop(e);
				return false;	
		}
	},
	
	validateEMail: function(element) {
		var r = /^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-]+\.[a-zA-Z]{2,3}(\.[a-zA-Z]{2})?$/;
		return (!r.test(element.getValue())) ? "Lütfen geçerli bir e-posta adresi giriniz.\n" : "";
	},
	
	validatePresence: function(name, from, to) {
		return ((name.getValue() != "") &&
					(from.getValue() != "") &&
					(to.getValue() != "")) ?
				"" : "İsim, gönderen ve alıcı alanlarının girilmesi zorunludur!";
	},
	
	validateData: function(name, from, to) {
		var msg = this.validateEMail(from) + this.validateEMail(to) +  this.validatePresence(name, from, to);
		if (msg != "")
		{
			alert(msg);
			return false;
		}
		return true;
	},
	
	tellAFriend: function(elementId, dataId) {
		name	= $(elementId + "_name");
		from 	= $(elementId + "_from");
		to		= $(elementId + "_to");
		message	= $(elementId + "_message");
		if (this.validateData(name, from, to) && !this.operatingTab)
		{
			this.operatingTab = this.selectedTab;
			this.operatingTab.update("Bekleyiniz...");
			
			new Ajax.Request(
						"ajax/features.php",
						{
							method		: "get",
							parameters	: {
								o		: "tellafriend", 
								i 		: dataId,
								tafname : name.getValue(),
								taffrom	: from.getValue(),
								tafto	: to.getValue(),
								tafmsg	: message.getValue()
							},
							onComplete	: this.tellAFriendresponse.bind(this)
						});
		}
	},
	
	tellAFriendresponse: function(transport) {
		this.operatingTab = null;
		alert("Mesajınız başarıyla arkadaşınıza gönderildi...");
		this.selectedTab.update(this.selectedTab.originalText);
	}
});

AnalysisContainer = Class.create({
	
	initialize: function(manager, container) {
		this.manager		= manager;
		this.container 		= container;
		this.id				= container.id;
		this.dataId			= parseInt(this.id.split("_")[1], 10);
		this.tabbedPage		= $$("#" + this.id + ' table[class="tabbedPageTabs bottomMargin"]')[0];
		this.tabs			= $$("#" + this.id + " td[type]");
		this.sepeartors		= $$("#" + this.id + " td[speratorTab]");
		this.dataContainer	= $$("#" + this.id + ' div[class="tabbedPageDataContainer"]')[0];
		this.prepareTabs();
	},
	
	prepareTabs: function() {
		this.tabs.invoke("observe", "click", this.tabClick.bindAsEventListener(this));
		this.tabs.each(function(tab) {
			tab.tabType 			= tab.readAttribute("type");
			tab.dataElementId 		= tab.tabType + "_ajax_" + this.dataId;
			tab.analysisContainer 	= this;
			tab.originalText 		= tab.innerHTML;
		}.bind(this));
	},

	tabClick: function(e) {
		var tab = Event.element(e);
		if (tab.selected)
		{
			this.deselectTab(tab);
		} else
		{
			this.selectTab(tab);
		}
	},
	
	selectTab: function(selectedTab) {
		this.tabs.each(function(tab) {
			tab.removeClassName("closedTab");
			if (selectedTab == tab)
			{
				tab.removeClassName("openedNotSelectedTab");
				tab.addClassName("openedSelectedTab");
				tab.selected = true;
			} else
			{
				tab.removeClassName("openedSelectedTab");
				tab.addClassName("openedNotSelectedTab");
				tab.selected = false;
			}
		}.bind(this));
		this.switchSeperators("closedSeparatorTab", "openedSeparatorTab");
		this.manager.load(selectedTab);
	},
	
	deselectTab: function(selectedTab) {
		this.tabs.each(function(tab) {
			tab.removeClassName("openedSelectedTab");
			tab.removeClassName("openedNotSelectedTab");
			tab.addClassName("closedTab");
			if (tab.dataElement)
			{
				tab.dataElement.hide();
			}
		}.bind(this));
		selectedTab.selected = false;
		this.dataContainer.hide();
		this.tabbedPage.addClassName("bottomMargin");
		this.switchSeperators("openedSeparatorTab", "closedSeparatorTab");
	},
	
	switchSeperators: function(removeStyle, addStyle) {
		this.sepeartors.each(function(seperator) {
			seperator.removeClassName(removeStyle);
			seperator.addClassName(addStyle);
		}.bind(this));
	}
});

CookieManager = Class.create({
	
	setCookie: function(key, value, expireDays) {
		value += ";domain=http://www.5ileri.com";
		value = escape(value);
		if (expireDays)
		{
			var exdate = new Date();
			exdate.setDate(exdate.getDate() + expireDays);
			value += ";expires=" + exdate.toGMTString(); 
		}
		document.cookie = key + "=" + value;
	},

	getCookie: function(key) {
		if (document.cookie.length > 0)
		{
			startOffset = document.cookie.indexOf(key + "=");
			if (startOffset != -1)
			{
				startOffset = startOffset + key.length+1;
				endOffset	= document.cookie.indexOf(";", startOffset);
				if (endOffset == -1)
				{
					endOffset = document.cookie.length;
				}
				return unescape(document.cookie.substring(startOffset, endOffset));
			}
		}
		return false;
	},	

	deleteCookie: function(key) {
		if (this.getCookie(key))
		{
			document.cookie = key + "=" + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
		}
	}	
	
});

function storeItIntoStatistics(advertId)
{
	new Ajax.Request(
			"/ajax/stats.php", 
			{
				method		: "get",
				parameters	: { i:advertId }
			});
}

function storeItIntoCookies(advertId)
{
	var cookieManager 	= new CookieManager();
	var lastVisitedCars	= cookieManager.getCookie("lastVisitedCars");
	if (lastVisitedCars)
	{
		var pos = lastVisitedCars.indexOf(";");
		if (pos >= 0)
		{
			lastVisitedCars = lastVisitedCars.substr(0, pos);
		}
		if (lastVisitedCars.indexOf(advertId) < 0)
		{
			lastVisitedCarsList = lastVisitedCars.split("|");
			if (lastVisitedCarsList.length == 6)
			{
				lastVisitedCarsList = lastVisitedCarsList.slice(1);
			}
			lastVisitedCarsList.push(advertId);
			lastVisitedCars = lastVisitedCarsList.join("|");
		}
	} else
	{
		lastVisitedCars = advertId;
	}
	cookieManager.setCookie("lastVisitedCars", lastVisitedCars);
}

function advertClick(advertId)
{
	storeItIntoStatistics(advertId);
	storeItIntoCookies(advertId);
}

function __ManagerWindowLoaded__()
{
	FManager = new Manager();
}

(function() {
	Event.observe(window, "load", __ManagerWindowLoaded__);
})();
