if (typeof console === 'undefined') {
	console = { log : function(){} };
}
var lastKeyPress = 0;
var isTimeoutId;
var dymTimeoutId;
var hashTimeoutId;
YAHOO.util.Event.addListener("query", "keyup", function(e){
	var isCallback = function(){
		//console.log(query);
		instantSearch(query);
	}
	var dymCalback = function(){
		// Start - Did You Mean
		var callback = {
			success: function (o) {
				if(o.responseText != '0'){
					var html = 'Mente du: ';
					var suggestions = response = eval('(' + o.responseText + ')');
					for (i = 0; i < suggestions.length; i++){
						html+= '<a onclick="instantSearch(null,null,\'query='+suggestions[i]+'\');return false;" href="/?query='+suggestions[i]+'">'+suggestions[i]+'</a>';
						if(i > 1) break;
						if(i < suggestions.length-1) html+= ' eller ';
					}
					document.getElementById('didyoumean').innerHTML = html;
					//document.getElementById('didyoumean').innerHTML = 'Mente du: <a onclick="instantSearch(null,null,\'query='+o.responseText+'\');return false;" href="/?query='+o.responseText+'">'+o.responseText+'</a>';
					document.getElementById('didyoumean').style.display = 'inline';
				} else {
					document.getElementById('didyoumean').style.display = 'none';
				}
			}
		}
		YAHOO.util.Connect.asyncRequest("GET", "/index/didyoumean?query="+query,callback);		
		// End - Did You Mean
	}
	var nowTime = new Date().getTime();
	if(this.value.length == 0) goToHome();
	var same = (query == encodeURIComponent(this.value));
	query = encodeURIComponent(this.value);
	if(this.value.length > 0 && !same){
		if((nowTime - lastKeyPress) > 250){
			isCallback();
			if((nowTime - lastKeyPress) > 750){
				dymCalback();
			}
			lastKeyPress = nowTime;
			return false;
		} else {
			if(isTimeoutId)clearTimeout(isTimeoutId);
			if(dymTimeoutId)clearTimeout(dymTimeoutId);
			lastKeyPress = nowTime
			isTimeoutId = setTimeout(isCallback, 250);
			dymTimeoutId = setTimeout(dymCalback, 750);
			return false;
		}
	} else {
		lastKeyPress = nowTime;
	}
});

var hash = "";
function locationHashChanged(){
	console.log('2: '+location.hash);
	console.log('3: '+hash);
	if (location.hash !== hash){
		if(location.hash == ""){
			document.getElementById('content').innerHTML = "";
		} else {
			var qs = location.hash.replace('#','');
			if(qs.indexOf('=')==-1){
				loadContent(qs);
			} else {
				instantSearch(null, null, qs);
			}
			var vars = qs.replace('+',' ').split("&");
			var pairs = new Array();
			for (var i = 0; i < vars.length; i++) {
				tmp = vars[i].split("=");
				pairs[tmp[0]] = tmp[1];
			}
			document.getElementById('query').value = pairs['query'] ? decodeURI(pairs['query']) : '';
			console.log('PAIRS: '+pairs['query']);
		}
		hash = location.hash;
		console.log('4 '+hash);
	} else console.log('FAIL');
}
window.onhashchange = locationHashChanged; 

function email(sDom, sUser){
	return(sUser+"@"+sDom.replace(/%23/g,"."));
}
if ( typeof EC == 'undefined' ) {
	var EC = {};
	
}
if ( typeof EC.Sendsms == 'undefined' ) {
	EC.Sendsms = {};
	
}
if ( typeof EC.Sendemail == 'undefined' ) {
	EC.Sendemail = {};
	
}
function sendemail( to, code, linkelm ){
	// set data
	docto = document.getElementById("to");
	docto.value = code;
	docemailheader = document.getElementById("emailHeader");
	docemailheader.innerHTML = "Send e-post til: " + to;
	EC.Sendemail.currentlink = linkelm;
	
	// show dialog
	YAHOO.email.container.emaildialog.show();

}
function sendsms( k, c, t, linkelm ){
	// set data
	docc = document.getElementById("c");
	docc.value = c;
	dockey = document.getElementById("k");
	dockey.value = k;
	doct = document.getElementById("t");
	doct.value = t;
	EC.Sendsms.currentlink = linkelm;
	
	// show dialog
	YAHOO.sms.container.smsdialog.show();

}
YAHOO.namespace("email.container");
function initEmail() {
	
	// Define various event handlers for Dialog
	var handleSubmit = function() {
		this.submit();
	};
	var handleCancel = function() {
		this.cancel();
	};
	var handleSuccess = function(o) {
	  /*returncodes:
	    0 - OK
	    1 - tomt meldingsfelt
	    3 - exception
	    */
	    
		var response = o.responseText;
		EC.Sendemail.currentlink.parentNode.removeChild(EC.Sendemail.currentlink.parentNode.lastChild);
		if ( response === '0' ){
			EC.Sendemail.currentlink.parentNode.innerHTML= EC.Sendemail.currentlink.parentNode.innerHTML + "<span><img src=\"/Gfx/1890/ok_icon.gif\" alt=\"Melding sendt\" title=\"Melding sendt\" class=\"tt\" /></span>";
			
		}else{
			EC.Sendemail.currentlink.parentNode.innerHTML= EC.Sendemail.currentlink.parentNode.innerHTML + "<span><img src=\"/Gfx/1890/error_icon.gif\" alt=\"Manglende eller ugyldig verdi\" title=\"Manglende eller ugyldig verdi\" class=\"tt\" /></span>";
			
		}
		initTooltips();
	};
	
	 
	
	var handleFailure = function(o) {
		var response = o.responseText;
		var message = '';
		if ( response === '1' ) message = 'Manglende eller ugyldig verdi';
		if ( response === '2' ) message = 'Beklager, en feil har oppstått';
		EC.Sendemail.currentlink.parentNode.innerHTML= EC.Sendemail.currentlink.parentNode.innerHTML + "<span><img src=\"/Gfx/1890/error_icon.gif\" alt=\""+message+"\" title=\""+message+"\" class=\"tt\" /></span>";
		initTooltips();
	};

	// Instantiate the Dialog
	YAHOO.email.container.emaildialog = new YAHOO.widget.Dialog("emaildialog", 
							{width : "400px",
							  fixedcenter : true,
							  visible : false, 
							  constraintoviewport : true,
							  buttons : [ {text:"Send", handler:handleSubmit, isDefault:true},
	 								  {text:"Avbryt", handler:handleCancel} ]
									 } );
		// Validate the entries in the form to require that both first and last name are entered
	YAHOO.email.container.emaildialog.validate = function() {
		var data = this.getData();
/*		if ( data.phone == "" || data.phone.length != 8 ) {
		if ( !data.phone.match( /^[49][0-9]{7}$/ ) ) {
			alert("Skriv inn ditt mobilnummer.");
			return false;
		} else {*/
			return true;
		//}
	};
	
	

	// Wire up the success and failure handlers
	YAHOO.email.container.emaildialog.callback = {success: handleSuccess,
					    	failure: handleFailure
					    	 };
					    	

	
	// Render the Dialog
	YAHOO.email.container.emaildialog.render();

}
YAHOO.namespace("sms.container");
function initSms() {
	// Define various event handlers for Dialog
	var handleSubmit = function() {
		this.submit();
	};
	var handleCancel = function() {
		this.cancel();
	};
	var handleSuccess = function(o) {
	  /*returncodes:
	    0 - OK
	    1 - generell feil
	    2 - grenseverdi nådd
	    3 - exception
	    */
		var response = o.responseText;
		if ( response === '0' ){
			EC.Sendsms.currentlink.parentNode.innerHTML="<div class=\"smsresult\"><img src=\"/Gfx/1890/ok_icon.gif\" alt=\"Melding Sendt\" title=\"Melding sendt.\"/></div>";
		}else if (response === 'SUCCESS' ){
			EC.Sendsms.currentlink.parentNode.innerHTML="<b>Sendt</b>";
		}else{
			EC.Sendsms.currentlink.parentNode.innerHTML="<div class=\"smsresult\"><img src=\"/Gfx/1890/error_icon.gif\" alt=\"Melding Sendt\" title=\"Beklager, en feil har oppstått\" /></div>";
		}
	};
	var handleFailure = function(o) {
		alert("Beklager. En feil har oppstått" );
	};
	// Instantiate the Dialog
	YAHOO.sms.container.smsdialog = new YAHOO.widget.Dialog("smsdialog", 
							{width : "250px",
							  fixedcenter : true,
							  visible : false, 
							  constraintoviewport : true,
							  buttons : [ {text:"Send", handler:handleSubmit, isDefault:true},
	 								  {text:"Avbryt", handler:handleCancel} ]
									 } );
	YAHOO.sms.container.smsdialog2 = new YAHOO.widget.Dialog("smsdialog2", 
			{width : "250px",
			  fixedcenter : true,
			  visible : false, 
			  constraintoviewport : true,
			  buttons : [ {text:"Send", handler:handleSubmit, isDefault:true},
						  {text:"Avbryt", handler:handleCancel} ]
					 } );
		// Validate the entries in the form to require that both first and last name are entered
	YAHOO.sms.container.smsdialog.validate = function() {
		var data = this.getData();
		if ( !data.phone.match( /^[49][0-9]{7}$/ ) ) {
			alert("Skriv inn ditt mobilnummer.");
			return false;
		} else {
			return true;
		}
	};
	YAHOO.sms.container.smsdialog2.validate = function() {
		var data = this.getData();
		if ( !data.mobile.match( /^[49][0-9]{7}$/ ) ) {
			alert("Skriv inn ditt mobilnummer.");
			return false;
		} else {
			return true;
		}
	};
	// Wire up the success and failure handlers
	YAHOO.sms.container.smsdialog.callback = {success: handleSuccess,
					    	failure: handleFailure
					    	 };
	YAHOO.sms.container.smsdialog2.callback = {success: handleSuccess,
	    	failure: handleFailure
	    	 };					    	
	// Render the Dialog
	YAHOO.sms.container.smsdialog.render();
	YAHOO.sms.container.smsdialog2.render();
}
function initTooltips(){

	var tt = YAHOO.util.Dom.getElementsByClassName( "tt" );
	tooltip = new YAHOO.widget.Tooltip("ttdesc", {  
		context:tt,
		showDelay:1,
		hidedelay:1});
}
var ids = "";
var prefixed_ids  = "";
function logInit() {
	YAHOO.util.Connect.asyncRequest("POST", "/index/log",{},"query="+query+"&ids="+prefixed_ids+"&page="+page+"&hits="+hits+"&ipp="+ipp);
}
function fbInit() {
	var callback = {
		success: function (o) {
			response = eval('(' + o.responseText + ')');
			for(var key in response){
				var html = '<fb:like href="http://www.facebook.com/pages/-/'+response[key]+'" send="true" layout="button_count" width="140" show_faces="false"></fb:like>';
				var button = '<a target="_blank" href="http://www.facebook.com/pages/-/'+response[key]+'" alt="Facebook"><img class="tt" title="Facebook" src="/Gfx/gul_no/fb_icon.png"></a>';
				document.getElementById('fb'+key).innerHTML = html;
				document.getElementById('buttons'+key).innerHTML = button + document.getElementById('buttons'+key).innerHTML;
				initTooltips();
				FB.XFBML.parse(document.getElementById('fb'+key));
			}
		}
	}
	if(ids){
		YAHOO.util.Connect.asyncRequest("POST", "/extrainfo/fbinfo",callback,"ids="+ids);
	}
}
function twInit() {
	var callback = {
		success: function (o) {
			response = eval('(' + o.responseText + ')');
			for(var key in response){
				var button = '<a target="_blank" href="http://twitter.com/'+response[key]+'" alt="Twitter"><img class="tt" title="Twitter" src="/Gfx/gul_no/tw_icon.png"></a>';
				var html = '<a href="https://twitter.com/'+response[key]+'" class="twitter-follow-button">Follow @'+response[key]+'</a>';
				document.getElementById('tw'+key).innerHTML = html;
				document.getElementById('buttons'+key).innerHTML = button + document.getElementById('buttons'+key).innerHTML;
				var tag = document.createElement('script');
				tag.setAttribute("type","text/javascript");
				tag.setAttribute("src", "//platform.twitter.com/widgets.js");
				document.getElementById('tw'+key).appendChild(tag);
				initTooltips();
			}
		}
	}
	if(ids){
		YAHOO.util.Connect.asyncRequest("POST", "/extrainfo/twinfo",callback,"ids="+ids);
	}
}
function messageInit() {
	var callback = {
		success: function (o) {
			response = eval('(' + o.responseText + ')');
			for(var key in response){
				document.getElementById('message'+key).innerHTML = '<img style="margin-left:-12px;margin-right:2px;" src="/Gfx/gul_no/bubble.png" />'+response[key];
			}
		}
	}
	if(ids){
		YAHOO.util.Connect.asyncRequest("POST", "/extrainfo/message",callback,"ids="+ids);
	}
}
YAHOO.util.Event.onDOMReady(initSms);
YAHOO.util.Event.onDOMReady(initEmail);
YAHOO.util.Event.onDOMReady(initTooltips);

function countSearch(){
    YAHOO.util.Connect.asyncRequest( 'GET', '/index/asyncsearch?' + qs + '&restype=' +type, {
		// Count hits on opposite search
		success : function(o) {
			if(o.responseText){
				response = eval('(' + o.responseText + ')');
				document.getElementById('tab'+type).innerHTML =  type + ' ('+response.count+')';
				document.getElementById('asyncSearchCount').innerHTML =  response.counttext;
				if(response.count > 0){
					document.getElementById('asyncSearchMoreLink1').href = document.getElementById((type == 'Bedrift' ? 'business':'private')+'TabLink').href;
					document.getElementById('asyncSearchMoreLink1').style.display = 'block';
					document.getElementById('asyncSearchMoreLink2').href = document.getElementById((type == 'Bedrift' ? 'business':'private')+'TabLink').href;
					document.getElementById('asyncSearchMoreLink2').style.display = 'block';
					document.getElementById('asyncSearchResult').innerHTML =  response.html;
					document.getElementById('asyncSearchTable').style.display = 'block';					
					YAHOO.util.Connect.asyncRequest("POST", "/index/log",{},"query="+query+"&ids="+response.ids+"&page="+page+"&hits="+response.count+"&ipp="+response.ipp);
				}
			}
		}
    });
}
function instantSearch(q,_page,_url){
	if(_page == undefined) _page = '1';
	var qs = 'query=' + (q ? q:'');
	qs = _url == undefined ? qs : _url;
	//console.log('QS: '+ qs);
	if(qs.indexOf('page=')==-1) qs += '&page='+_page;
	
	if(hashTimeoutId)clearTimeout(hashTimeoutId);
	
    YAHOO.util.Connect.asyncRequest( 'GET', '/index/instantsearch/?'+qs, {
		success : function(o) {
			if(o.responseText){
				window.scrollTo(0,0);
				response = eval('(' + o.responseText + ')');
				if(response.count > 0){
					document.getElementById('content').innerHTML =  response.html;
					//YAHOO.util.Connect.asyncRequest("POST", "/index/log",{},"query="+query+"&ids="+response.ids+"&page="+page+"&hits="+response.count+"&ipp="+response.ipp);
					console.log('query: '+qs);
					console.log('ids: '+response.ids);
					console.log('page: '+page);
					console.log('count: '+response.count);
					console.log('ipp: '+response.ipp);			
				} else {
					document.getElementById('content').innerHTML = "";
				}
				if(!q){
					hash = '#'+qs;
					console.log('1: '+hash);
					window.location.hash = decodeURI(qs);
				} else {
					var setHash = function(){
						hash = '#'+decodeURI(qs);
						console.log('5: '+hash);
						window.location.hash = decodeURI(qs);
					}
					hashTimeoutId = setTimeout(setHash, 1250)
				}
			}
		}
    });
}
YAHOO.util.Event.onDOMReady(countSearch);
function showExtraInfo( id, k, destination ){

	if ( !document.getElementById( destination ).isopen ) {
	
		var resHandle = {
			success : function(o) {
				document.getElementById( this.destination + '-row' ).style.display = 'table-row';
				var elem = document.getElementById( this.destination );
				elem.innerHTML = o.responseText;
				
				var attributes = {height: {from: 0, to: 90}};
				
				var anim = new YAHOO.util.Anim(this.destination, attributes, 0.60, YAHOO.util.Easing.elasticOut);
				anim.animate();
				
				elem.isopen = true;
				
			}
		     
		}
		 
		resHandle.destination = destination;
		YAHOO.util.Connect.asyncRequest( 'GET', '/extrainfo?c=' + id + '&k=' + k, resHandle );
	
	} else {
	
		var attributes = {height: {from: 90, to: 0}};
		var elem = document.getElementById( destination );
		
		elem.innerHTML = "";
		
		var anim = new YAHOO.util.Anim( elem, attributes, 0.60, YAHOO.util.Easing.easeIn );
		anim.animate();
		setTimeout("document.getElementById('"+elem.id +"-row' ).style.display = 'none'", 600);
		elem.isopen = false;
	
	}

}
function loadContent(page){
	YAHOO.util.Connect.asyncRequest( 'GET', '/index/static/page/'+page, {
		success : function(o) {
			if(o.responseText){
				document.getElementById('content').innerHTML = o.responseText;
				window.scrollTo(0,0);
			}
			hash = '#'+page;
			console.log('6: '+hash);
			window.location.hash = page;
		}
    });
}
function goToHome(){
	document.getElementById('content').innerHTML = "";
	window.location.hash = '';
}
