var ResultList = Class.create({
	initialize: function(container, opt){
		if (!container) {
			throw "You must supply a container to the ResultList constructor. Id or DOMNode will do.";
		}
		container = container instanceof Array ? $A(container) : $(container).select('.hit');    
		if (!container.length || container.length === 0) { return; }
		this.hits = $A();
		this.opt  = Object.extend({
			obj: Hit,
			type: ""
		}, opt || {});
		container.each(function(hit) {
			var hit = new this.opt.obj(hit, this.opt.type);
			this.hits.push(hit);
			hit.attachDialogs(hit.e.select("div.block-1")[0]);
			hit.attachDialogs(hit.e.select("div.block-2")[0]);
			hit = null;
		}.bind(this));
	},
	getHitById: function(id){
		return this.hits[id-1];
	}
});

var Hit = Class.create({
	initialize: function(e, type, callbacks){
		this.e    = $(e);
		this.callbacks = callbacks || {};
		this.type = type;
		this.id   = this.e.id ? this.e.id.match(/([0-9]+)/)[0] : null;
		Event.observe(this.e, 'mouseover', this.hover.bind(this), false);
		Event.observe(this.e, 'mouseout', this.unHover.bind(this), false);
		Event.observe(this.e, 'click', this.toggle.bind(this), false);
	},
	toggle: function(v) {
		if (this.callbacks.before_toggle) {
			this.callbacks.before_toggle(this);
		}
		var e = v.element();
		if ((e.tagName.toLowerCase() !== 'a' || e.hasClassName("expand")) && (!$(e.parentNode.parentNode).hasClassName("logo") || !this.expanded)){
			v.stop();
			if (!this.expanded) {
				this.expand(v);
			}
			else if (e.hasClassName('expand') || $(e.parentNode.hasClassName("expand"))) {
				this.hide(v);
			}
		}
		if (this.callbacks.after_toggle) {
			this.callbacks.after_toggle(this);
		}
	},
	expand: function(v){
		if (this.callbacks.before_expand) {
			this.callbacks.before_expand(this);
		}
		this.e.addClassName('expanded');
		this.e.addClassName('visited');
		this.expanded = true;
		if (this.callbacks.after_expand) {
			this.callbacks.after_expand(this);
		}
	},
	hide: function(v){
		if (this.callbacks.before_hide) { this.callbacks.before_hide(this); }
		this.e.removeClassName('expanded');
		this.expanded = false;
		if (this.callbacks.after_hide) { this.callbacks.after_hide(this); }
	},
	hover: function(){
		if (this.callbacks.before_hover) { this.callbacks.before_hover(this); }
		if(!this.e.hasClassName("hithover")){ this.e.addClassName("hithover"); }
		if (this.callbacks.after_hover) { this.callbacks.after_hover(this); }
	},
	unHover: function(){
		if (this.callbacks.before_unhover) { this.callbacks.before_unhover(this); }
		if(this.e.hasClassName("hithover")){ this.e.removeClassName("hithover"); }
		if (this.callbacks.after_unhover) { this.callbacks.after_unhover(this); }
	},
	attachDialogs: function(e){
		if(!this.dialogs){ this.dialogs = new DialogHandler(); }
		e = e || this.e;
		els = e.select('a.dialog');
		if(els[0]){
			els.each(function(e){
				if(!e.has_dialog){
					dialog_opt = {e:e, submit_by_ajax:e.hasClassName('ajax')};
					if($(e.parentNode).hasClassName("phone-us")){
						dialog_opt.before_submit = function(){
							if((client = $("client"))){
								Eniro.settings().data.c2c_phone_no = client.value;
								Eniro.settings().save();
							}
						};
					}
					if($(e.parentNode).hasClassName("phone-us") || $(e.parentNode).hasClassName("sms") || $(e.parentNode).hasClassName("coupon-sms")){
						if($(e.parentNode).hasClassName("phone-us")) {
							dialog_opt.extra_class = "phone-us-dialogue";
						}
						dialog_opt.after_content = function(dialogue){
							if((client = $("client"))){
								client.value = Eniro.settings().data.c2c_phone_no || "";
							}
							var info = dialogue.box.select("div.infobox")
							if(info[0]){
								info = info[0];
								info.hide();
								dialogue.box.select("a.toggle_info").each(function(e){
									Event.observe(e, "click",function(v){
										Event.stop(v);
										dialogue.box.select("div.infobox")[0].toggle();
									},false);
								}.bind(dialogue));
							}
						};
					}
					if($(e.parentNode).hasClassName("contact")) {
						dialog_opt.after_content = function(dialogue){
							var cookies_error = dialogue.box.select("#cookies_error")[0];
							var contact_form = dialogue.box.select("#contact_form")[0];
								if (!Eniro.Page.check_cookies_enabled()) {
								if(cookies_error) {
								cookies_error.setStyle({
								display:'block'
								});
								if (contact_form) {contact_form.hide()}
								}
								}
							var warning_message = dialogue.box.select("#warning_message")[0];
							if (warning_message) {
							if (!warning_message.hasClassName('first')) {
							warning_message.hide();
							}
							var rand_no = Math.floor((3)*Math.random());
							if (rand_no == 0) {
							warning_message.show();
							}
							}
						};
					}
					dialogue = this.dialogs.add(dialog_opt);
					dialogue.handler = this.dialogs;
					e.has_dialog = true;
				}
			}.bind(this));
		}
	}


});

var CompanyPeopleHit = Class.create(Hit, {

	initialize: function(e, type, callbacks) { 
		this.e     = $(e);
		this.type  = type;
		this.callbacks = callbacks || {};
		// ADDED, Zarai
		this.hoverMadeByList = false;
		this.id    = this.e.id ? this.e.id.match(/([0-9]+)/)[0] : null;
		this.multi = e.hasClassName('multi');
		this.has_infopage = e.hasClassName('has-infopage');
		this.findLogo();
		Event.observe(this.e, 'mouseover', this.hover.bind(this), false);
		Event.observe(this.e, 'mouseout', this.unHover.bind(this), false);
		if(!this.multi){
			this.expanded = this.e.hasClassName('expanded');
			Event.observe(this.e, 'click', this.toggle.bind(this), false);
		}
		else if (this.multi) {
			this._setupMultiHits();
		}
	},
	_setupMultiHits: function() {
		var _headings = this.e.select(".headings");
		_headings.each(function(heading){
			new Heading(heading);
		});
		_headings = null;
	},
	findLogo: function(){
		e = this.e.select("div.logo");
		if(e.length > 0){
			this.logo = e[0].getElementsByTagName("img")[0] || false;
		}
	},
	toggle: function(event) {
		var e = event.element();
		if (this.callbacks.before_toggle) {
			this.callbacks.before_toggle(this);
		}
		if (((e.tagName.toLowerCase() !== 'a' && e.parentNode.tagName.toLowerCase() !== 'a') || e.hasClassName("expand")) && (!$(e.parentNode.parentNode).hasClassName("logo") || !this.expanded)){
			if (this.type === "company" && e.tagName.toLowerCase() === "span" && $(e.parentNode).hasClassName("expand") && e.parentNode.tagName.toLowerCase() === "a") {
				// Open infopage in new window if we're on the map page
				if (Eniro.Page.tab() === "map") {
					event.stop();
					window.open(e.parentNode.href); 
				}
			} else {
				if (e.tagName.toLowerCase() !== "img") {
					event.stop();
				}
				if (!this.expanded) {
					this.expand(event);
				}
				else if (e.hasClassName('expand') || $(e.parentNode).hasClassName("expand") || e.tagName.toLowerCase() == "h3") {
					this.hide(event);
				}
			}
		}
		if (this.callbacks.after_toggle) {
			this.callbacks.after_toggle(this);
		}
	},
	expand: function(v){
		if (this.callbacks.before_expand) { this.callbacks.before_expand(this); }
		this.ads  = this.ads || this.e.select("p.adLinks")[0] || false;
		this.info = this.info || this.e.select("div.companyinfo")[0] || false;
		this.loading = true;
		this.e.addClassName("loading");
		if(!this.ext){
			this.getExtended();
		}else{
			this.doExpansion();
		}
		if (this.callbacks.after_expand) { this.callbacks.after_expand(this); }
	},
	doExpansion: function(){
		var loaded;
		if(!this.rearranged){
			if (!this.has_infopage) {
				/* temporarily eniro.dk map yellow tab hit shouldn't be rearranged */
				var dk = $$('#results.dk_results')[0];
				if (!dk) {
				this.rearrangeDOM();
				}
			}
			var hitfeatures = this.ext.select(".hitfeatures");
			if (hitfeatures.length > 0) {
				this.ext.insert({after:hitfeatures[0]});
			}
			this.rearranged = true;
			var hide = this.e.select(".hide");
			if(hide[0]){
				var hide_link = hide[0].getElementsByTagName("a")[0];
				Event.observe(hide_link, "click", function(v){
					Event.stop(v);
					this.hide();
				}.bind(this));
			}
			this.attachDialogs();
		}
		var loaded = this.e.select(".loaded");
		if (loaded[0]) {
			loaded.invoke("show");
		}
		if (this.ads){ this.ads.hide(); }
		this.ext.style.display="block";
		this.e.addClassName('expanded');

		if (this.type === 'company' && !Eniro.Page.tab_is("map")) {
			var taglistLimit = this.e.select('.headings .limitedTags');
			var taglistExtend = this.e.select('.headings .extendedTags');
			if (taglistLimit.length > 0 && taglistExtend.length > 0) {
				taglistLimit.each(function(tagListItem) {
					tagListItem.removeClassName('limited');
					tagListItem.addClassName('closed');
				});
				taglistExtend.each(function(tagListExtendItem) {
				 	tagListExtendItem.removeClassName('closed');
				 	tagListExtendItem.addClassName('extended');
				});
			}
		}

		if (this.has_infopage) {
			this.e.addClassName('ip-expanded');
		}
		this.e.addClassName('visited');
		this.expanded = true;
		this.e.removeClassName("loading");
		this.loading  = false;
		if(!this.map){
			if(this.e.select('div.resultlistMap')[0]){
				this.map = new HitMap(this.e);
			}
		}
	},
	/* Get expansion content with ajax */
	getExtended: function(){
		var url = "";
        var ext_div = new Element("div", {'class': 'extended clearfix'});
        ext_div.setAttribute('class','extended clearfix');
		this.ext = this.e.appendChild(ext_div);
		var ext_container = this.e.select(".ext-container")[0];
		if (ext_container) {
			this.ext = ext_container.appendChild(new Element(ext_div));
		}
		var h3 = this.e.getElementsByTagName("h3")[0];
		var id = h3.id.substr(3);
		var a  = h3.getElementsByTagName("a");
		var lang = "", ax = "", forward_word = "", forward_area = "", match;
		if(a.length > 0){
			var href = a[0].href;
			if (match = href.match(/lang[=\/]([^\/&]+)?([&\/]?)/))        {         lang = match[1]; }
			if (match = href.match(/ax[=\/]([^\/&]+)?([&\/]?)/))          {           ax = match[1]; }
			if (match = href.match(/search_word[=\/]([^\/&]+)?([&\/]?)/)) { forward_word = decodeURIComponent(match[1]); }
			if (match = href.match(/geo_area[=\/]([^\/&]+)?([&\/]?)/))    { forward_area = decodeURIComponent(match[1]); }
		}
		if (this.type === "company") {
			url = "/query?what=yp_ext&forward_word=" + forward_word + "&forward_area=" + forward_area + "&advert_code=" + id;
		}
		else if(this.type == "people" || this.type == "person") {
			var ps_id = id;
			var phone = "";
			if(id.indexOf("_ph_") != -1){
				ps_id = id.substring(0, id.indexOf("_ph_"));
				phone = "&phone_number=" + id.substring(id.indexOf("_ph_") + 4);
			}
			url = "/query?what=wp_ext&ps_id="+ps_id+phone;
		}
		url += "&ax=" + ax;                                      // Add ax param
		url += Eniro.Page.tab() == "map" ? "&ajax=map":"";       // Add ajax param if we're on maps
		url += lang && lang != "#" ? "&lang="+lang : "";         // Add lang param
		url += "&random=" + (Math.random()*1000000000000000000); // Add rand param with random number to prevent caching
		var request = new Ajax.Updater(
			this.ext,
			url,{
				method: 'get',
				parameters: '',
				onComplete: function(){
					this.doExpansion();
				}.bind(this)
			});
		},
		rearrangeDOM: function(){
			this.ext = this.ext || this.e.select("div.extended")[0];
            	var map_arr = this.ext.select("*.map");
            	var map = false;
            	if (map_arr.length>0) {map=map_arr[0]};
			var additionalContactInfo = this.ext.select('.additional-contact-info');
			var routePlan = this.ext.select('.route-plan')[0];
			var localTransportation = this.ext.select('a.local-transportation')[0];
			var update = this.ext.select('.update')[0];
			
			if (this.type === "people" || this.type === "person") {
				/**
				this.ext.insert({
					before: new Element("div", {
						'class': 'block-2'
					})
				});
				*/
				if (map) {
					this.e.select("*.block-2")[0].appendChild(map);
				}
				if (update) {
					this.e.select('.tel')[0].appendChild(update);
					update.addClassName('loaded');
				}
				if (additionalContactInfo.length > 0) {
				  additionalContactInfo = additionalContactInfo[0];
					this.e.select("*.block-1")[0].appendChild(additionalContactInfo);
					additionalContactInfo.addClassName('loaded');
					var moreNumbers = additionalContactInfo.select("*.even-more-numbers")[0];
					var partnerBox = additionalContactInfo.select("*.partnerBox")[0];
					if (map) {
						partnerBox.addClassName("bottom");
					}
					else {
						this.ext.firstDescendant().insert({before:partnerBox});
					}
				}
			}
			if (this.type === 'company') {
				if (Eniro.Page.tab_is("map")) {
					var read_more = this.ext.select("a.read-more");
						if (read_more.length > 0) {
							read_more.each(function(link){
							link.setAttribute("target", "_blank");
						});
					}
				}
				
				var taglistLimit = this.e.select('.headings .limitedTags');
				var taglistExtend = this.e.select('.headings .extendedTags');
				if (taglistLimit.length > 0 && taglistExtend.length > 0) {
					taglistLimit.each(function(tagListItem) {
						tagListItem.removeClassName('limited');
						tagListItem.addClassName('closed');
					});
					taglistExtend.each(function(tagListExtendItem) {
						tagListExtendItem.removeClassName('closed');
						tagListExtendItem.addClassName('extended');
					});
				}
				
				var basicPhone = this.e.select("*.tel")[0];
				var additionalPhone = this.ext.select("*.additional-phone")[0];
				if(basicPhone && additionalPhone){
					$A(additionalPhone.getElementsByTagName('li')).each(function(phone){
						phone.addClassName("loaded");
						basicPhone.appendChild(phone);
					});
					additionalPhone.remove();
				}
				if(additionalContactInfo.length > 0){
				  additionalContactInfo = additionalContactInfo[0];
					var ci = this.e.select("*.contact-info");
					if (ci.length > 0) {
						ci[0].appendChild(additionalContactInfo);
						additionalContactInfo.addClassName('loaded');
					}
				}
				var additionalLinks = this.ext.select("*.additional-links");
				var links           = this.e.select("*.links");
				if(additionalLinks[0]){
					additionalLinks = additionalLinks[0];
					links           = links.length > 0 ? links[0] : new Element("ul", {'class':'links'});
					additionalLinks.select('li').each(function(link){
						link.addClassName("loaded");
						links.appendChild(link);
					});
				}
				var additionalInfo = this.ext.select("*.additional-info")[0];
				if(this.info && additionalInfo){
					var infoText = this.info.select("p")[0];
					infoText.appendChild(additionalInfo);
					additionalInfo.addClassName('loaded');
				}
				var nearby   = this.ext.select("div.nearby")[0];
				var headingtype = this.e.select(".headingtype").first();
				if(nearby){
					nearby.addClassName("loaded");
					if (headingtype) {
						headingtype.parentNode.insertBefore(nearby, headingtype)
					}
					else {
						getElementsByClassName(this.e,"div","block-1")[0].appendChild(nearby);
					}
				}
			}
			if(routePlan){
				if(this.e.select("*.adr").toString() != '') {
					this.e.select("*.adr")[0].appendChild(routePlan);
					routePlan.addClassName('loaded');
				}
			}
			if(localTransportation){
				if(this.e.select("*.adr").toString() != '') {
					this.e.select("*.adr")[0].appendChild(localTransportation);
					localTransportation.addClassName('loaded');
				}
			}	
			
			if(map){
				map.addClassName('loaded');
			}

			var headings = this.e.select(".headings")[0];
			var hitfeatures = this.ext.select(".hitfeatures")[0];		
			if(headings && hitfeatures){
				this.ext.insert({after:headings});
			}
			this.rearranged = true;
	},
	hide: function(){
		if (this.callbacks.before_hide) { this.callbacks.before_hide(this); }
		this.e.removeClassName('expanded');

		if (this.type === 'company') {
			var taglistLimit = this.e.select('.headings .limitedTags');
			var taglistExtend = this.e.select('.headings .extendedTags');
			if (taglistLimit.length > 0 && taglistExtend.length > 0) {
				taglistLimit.each(function(tagListItem) {
					tagListItem.addClassName('limited');
					tagListItem.removeClassName('closed');
				});
				taglistExtend.each(function(tagListExtendItem) {
				 	tagListExtendItem.addClassName('closed');
				 	tagListExtendItem.removeClassName('extended');
				});
			}
		}

		if (this.has_infopage) {
			this.e.removeClassName('ip-expanded');
		}
		this.expanded = false;
		this.e.select("div.extended")[0].hide();
		var loaded = this.e.select("*.loaded");
		if(loaded[0]) {
			loaded.each(function(e){ e.hide(); });
		}
		if(this.ads) { this.ads.show(); }
		if (this.callbacks.after_hide) { this.callbacks.after_hide(this); }
	},

	hover: function(){
		//debug(['hovered', this]);
		this.hoverMadeByList = true;
		if (this.callbacks.before_hover) { this.callbacks.before_hover(this); }
		if(!this.multi){
			this.e.addClassName("hithover"); 
		} else {
			this.e.addClassName("hithover_multi");
		}
		if (this.callbacks.after_hover) { this.callbacks.after_hover(this); }
	},

	unHover: function(){
		this.hoverMadeByList = true;
		if (this.callbacks.before_unhover) { this.callbacks.before_unhover(this); }
		if(this.multi){
			this.e.removeClassName("hithover_multi");
		} else {
			this.e.removeClassName("hithover");
		}
		if (this.callbacks.after_unhover) { this.callbacks.after_unhover(this); }
	}
});

var CompanyHit = Class.create(CompanyPeopleHit, {
	expand: function($super, v){
		if (this.callbacks.before_expand) { this.callbacks.before_expand(this); }
		$super(v);
		this.statsForExpand();
		if (this.callbacks.after_expand) { this.callbacks.after_expand(this); }
	},
	statsForExpand: function(){
		if(this.e.select("img.exp_stats")[0]){ return; }
		if((stat = this.e.select("img.stats")[0])){
			exp_stats = this.e.appendChild(new Element("img", {
				'class': 'stats exp_stats',
				src: stat.src.replace(/page_type=yp/, 'page_type=xyp'),
				width: 0,
				height: 0
			}));
		}
	}
});

/*
= Taglist
*/
var TagList = Class.create({
	initialize: function() {
		var container = $$("body")[0].select("div.results")[0];
		var extendTags_arr = container.select('.extendTags');
		var extendedTags_arr = container.select('.extendedTags');
		if(extendTags_arr.length > 0 ) {
			Event.observe(container, 'click', function(ev) {
				// show and hide the appropiate div
				element = ev.element();
				if (element.parentNode.hasClassName('extendTags')) {
					showHide(element.parentNode);
				}
			});
		}
		
		function showHide(e) {
			$(e.parentNode).removeClassName('limited');
			$(e.parentNode).addClassName('closed');
			extendTags_arr.each( function (elem, i) {
				if (elem == e) {
					extendedTags_arr[i].removeClassName('closed');
					extendedTags_arr[i].addClassName('extended');
					$break;
				}
			});
		}
		
		
	}
});

/**
 * This is only true for grouped hits (Visa fler).
 * Heading are basically keywords.
 * They have a .headingType, .limitedTags and .extendedTags
 * LimitedTags are shown initially, there is a link that toggles between
 * LimitedTags and ExtendedTags. Toggling is done by adding the className .expanded to the parent.
 * I will move the .expanded className to the parent to save us from looping.
 */
var Heading = Class.create({
	initialize: function(parent) {
		this.heading = $(parent);
		this.limitedTags = this.heading.select(".limitedTags");
		this.extendedTags = this.heading.select(".extendedTags");
		this.showMoreLink = this.heading.select(".extendedTagslink").first();
		this.showLessLink = this.heading.select(".limitedTagslink").first();
		this.showingLimited = true;
		this._click();
	},
	_toggle: function(event) {
		event.stop();
		this.showingLimited = !this.showingLimited;
		this.limitedTags.each(function(limitedTag) {
			if (this.showingLimited) {
				limitedTag.removeClassName("closed");
			}
			else {
				limitedTag.addClassName("closed");
			}
		}.bind(this));
		this.extendedTags.each(function(extendedTag) {
			if (this.showingLimited) {
				extendedTag.addClassName("closed");
			}
			else {
				extendedTag.removeClassName("closed");
			}
		}.bind(this));
	},
	_click: function() {
		if (this.showMoreLink) {
			this.showMoreLink.observe("click", this._toggle.bindAsEventListener(this));
		}
		if (this.showLessLink) {
			this.showLessLink.observe("click", this._toggle.bindAsEventListener(this));
		}
	},
	_debug: function() {
		if (window.console) {
			console.log(arguments);
		}
	}
});

Event.observe(document, "dom:loaded", function() {
	var results, ratingsReview;
	ratingsReview = $('mainResultsYP') ? $('mainResultsYP').hasClassName('ratingsReview') : false;
	if ((Eniro.Page.tab_is("yp") && Eniro.Page.is_resultpage()) && !ratingsReview) {
		results = new ResultList($$("body")[0].select("div.results")[0], {obj: CompanyHit, type: 'company'});
		if (results.hits && results.hits.length === 1 && !results.hits[0].multi) {
			results.hits[0].expand();
		}
	}
	else if (Eniro.Page.tab_is("person") && Eniro.Page.is_resultpage() && $("mainResultsPerson")) {
		results = new ResultList($$("body")[0].select("div.results")[0], {obj: CompanyPeopleHit, type: 'person'});
		if (results.hits && results.hits.length === 1) {
			results.hits[0].expand();
		}
	}
	var mycontactlist = $("mycontactlist");
	addressBook = false;
	if (mycontactlist) {
		mycontactlist.onclick = function() { return false; } // Safari 2 fix
		mycontactlist.observe("click", function(e) {
			var url = mycontactlist.href;
			e.stop();
			addressBook =  window.open(url, 'addressbook', 'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,width=670,height=600,top=0,left=0', false);
		});
	}
	var mycontactlinks = $$("div.contact");
	if (mycontactlinks) {
		mycontactlinks.each(function(it) {
		 it.setStyle({
			display : 'block'
			})
		});
	}
});

/**
 * flickering background fix for IE
 */
if (Prototype.Browser.IE){
	document.execCommand("BackgroundImageCache", false, true);
}
if (typeof jQuery != 'undefined') {
	jQuery(document).ready(function(){
		jQuery('.company-data-small.yritystele a').click(function() {
			var url = this.href;
			yritystele =  window.open(url, 'yritestele', 'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,width=570,height=600,top=0,left=0', false);
			return false;
		});
	});
}
