function PreventPasting(e) {
 	if (window.event) {
		var key = window.event.keyCode;
		var isCtrl = window.event.ctrlKey;
		var isCmd = window.event.metaKey;
	} else {
		var key = e.which;
		var isCtrl = e.ctrlKey;
		var isCmd = e.metaKey;
	}
	
 	if(isCtrl || isCmd) {
		if (key == 86 || key == 118) { return false; };
	} return true;
}

function facebookUrlReplacer(siteUrl, appName, url) {
  var returnUrl = url
  .gsub('www.' + siteUrl + '/facebook/', 'apps.facebook.com/' +  appName + '/')
  .gsub(/(\?|\&)?fb_sig_in_iframe(.+?)$/, '');
  
  return returnUrl;
}

function updateChatterbox() {
	new Ajax.Request("ChatterboxGet.asp", {onComplete: function(e) {
		$('posts').update('');
		e.responseText.evalJSON().chatterbox.reverse().each(function(b) {
			if (decodeURIComponent(b.post) != "undefined") {
				$('posts').insert({top: template.evaluate({
					id: b.post_id, user_id: b.user_id, username: b.username, picture: b.picture, gender: b.gender, created_at: b.created_at, r: b.r, post: b.post, bc: b.bc, bch: b.bch
				})});
			}
		});
	}});	
}
function updateChatterboxStart() {
	new Ajax.Request("/Ajax/ChatterboxStart.asp", {onComplete: function(e) {
		$('posts').update('');
		e.responseText.evalJSON().chatterbox.reverse().each(function(b) {
			if (decodeURIComponent(b.post) != "undefined") {
				$('posts').insert({top: template.evaluate({
					id: b.post_id, user_id: b.user_id, username: b.username, post: b.post
				})});
			}
		});
	}});	
}

function updateLatestLoggedIn() {
	new Ajax.Request("/Ajax/LatestLoggedIn.asp?id=" + lastUpdatedID, {onComplete: function(e) {
		e.responseText.evalJSON().users.reverse().each(function(b) {
			if (typeof(b.id) != "undefined") {
				$('latest-logged-in-list').insert({top: latestLoggedInTemplate.evaluate({
 	 				user_id: b.user_id, username: b.username
  			})});
  			var listElements = $('latest-logged-in-list').childElements();
  			listElements.first().pulsate();
  			listElements.last().remove();

				lastUpdatedID = parseInt(b.id);
  		}
		});
	}});	
}

function showMoreOffers(e) {
	$$('.offer').invoke('show');
	e.parentNode.hide();
	$$('.offer').last().setStyle({borderBottom: '0', marginBottom: '-15px'});
}

function gbPopup(url) {
	window.open(url, 'gb', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=265,height=250');
	return false;
}

function urldecode(str) {
	str = str.replace('+', ' ');
	str = unescape(str);
	return str;
}

function CreateOrder(id, points, value, lang) {
	var text;
	
	switch(lang) {
		case 'sv': 		text = 'Är du säker på att du vill växla dina ' + points + ' poäng mot ett presentkort värt ' + value + ' kr?'; break;
		case 'sv-gp': text = 'Är du säker på att du vill växla dina ' + points + ' poäng mot prylen värt ' + value + ' kr?'; break;
	}

	if (!confirm(text)) {
		return false;
	} else {
		window.location.href='CreateOrderSave.asp?id=' + id;
	}
}

function ProfilePictureUploadCheck(lang) { 
	if (document.uploadProfileImg.file.value.length>2)
		return true;
	else {
		switch(lang) {
			case 'sv': 	alert("Du måste välja en bild för att ladda upp."); break;
		}
	  
		return false; 
	} 
} 

function Like(element, ot, oid, lang) {
	element = $(element);
	
	element.hide();
	
	switch(lang) {
		case 'sv': likeText = 'Gilla'; stopLikeText = 'Sluta gilla'; break;
		case 'no': likeText = 'Liker'; stopLikeText = 'Liker ikke'; break;
	}
	
	new Ajax.Request("Like.asp", {
		parameters: {object_type: ot, object_id: oid},
		onComplete: function(r) {
			element.update(r.responseText == '1' ? stopLikeText : likeText).appear();
		} 
	});
}

var UserValidation = Class.create({
	initialize: function() {
		
	},
	
	error: function(e, bln) {
		if (bln) {
			e.previousSiblings()[0].hide();
			e.previousSiblings()[1].show();
		} else {
			e.previousSiblings()[1].hide();
			e.previousSiblings()[0].show();
		}
	},

	username: function(e) {
		e.value = (e.value.match(/[a-zåäö0-9]+/i)) ? e.value : '';
		
		new Ajax.Request('/Ajax/CheckUsername.asp?username=' + e.value, {
			onComplete: function(t) {
				this.error(e, t.responseText == '1');
				
				if (e.value == '') {
					this.error(e, true);
				}
			}.bind(this)
		});
	},
	password: function(e) { this.error(e, (e.value.length < 6 || e.value.length > 30)) },
	firstname: function(e) { this.error(e, e.value == ''); },
	lastname: function(e) { this.error(e, e.value == ''); },
	address: function(e) { this.error(e, e.value == ''); },
	email: function(e) { this.error(e, !e.value.match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)); },
	postcode: function(e) {
		var postaddress = $('postaddress')
  	e.value = (e.value.match(/\d+/)) ? e.value.match(/\d+/) : '';
		
		new Ajax.Request('/Ajax/getPostAddress.asp?postcode=' + e.value, {
		  onComplete: function(t) {
		  	if (t.responseText == 'norsk') {
		  		if (e.value.match(/\d{3,6}/)) {
		  			this.error(e, false);
		  		} else {
		  			this.error(e, true);
		  		}
		  	} else {
		  		postaddress.value = urldecode(t.responseText);
			  	this.error(e, postaddress.value == '');
		  	}
		  }.bind(this)
		});
	},
//	postaddress: function(e) { this.error(e, e.value == ''); },
	gender: function(e) { this.error(e, e.value == ''); },
	address: function(e) { this.error(e, e.value == ''); },
	
	gender: function(e) { $('gender_accept').show(); }
});


var FaceBook = Class.create({
  initialize: function(api_key) {
    FB.init(api_key);
  },
  
  logout: function(url) {
  	FB.Connect.logoutAndRedirect(url);
  }
});

var TipOnFaceBook = Class.create(FaceBook, {
	initialize: function($super, api_key, auth, miniumFriends) {
		$super(api_key);
		
		this.auth = auth;
		this.miniumFriends = miniumFriends;		
	},
	
	run: function() {
		var mf = this.miniumFriends;
	
		FB_RequireFeatures(["Api"], function(){
			var api = FB.Facebook.apiClient;

	    FB.Connect.requireSession(function(exception){
				$('about_user').show();

         api.friends_get(new Array(), function(result, exception){
         	
         		var friends_count = result.length;
         		
         		if (friends_count >= mf) {
         			$('publish_button').show();
         		} else {
         			$('not_enough_friends').show();
         			$('friends_count').update(friends_count);
         		}
         });
	    });
		});	
	},
	
	publish: function(attachment, actionLink, header) {
   	$('about_user').hide();
   	$('loader').show();
		FB.Connect.streamPublish('', attachment, actionLink, null, header, this.steamCallback);
	},
	
	steamCallback: function(post_id, exception) {
		if (post_id != "null" && post_id != null) {
    	new Ajax.Request("/Facebook/point.asp?h=" + TipOnFaceBook.auth + "&pid=" + post_id, {onComplete: function() {  		
    		$('loader').hide();
	    	$('offer_done').show();
    	}});
  	}
	}
});

/* Clean up! */
clickedLoginButton = false;
function gmLogIn(fromElement, element) {
	if ($('log-in') == 'undefined' || $('log-in').className.indexOf('global') != -1)
		window.location.href = 'LogIn.asp';
	else {
	
		var s = document.body.style;
	
		if (!clickedLoginButton) {
			fromElement.setStyle({ position: 'relative', zIndex: '2', color: '#555' });
			fromElement.style.textShadow = '0 0 0 #FFF';
			$('reg-link').hide();
	
			if (s.WebkitBoxShadow !== undefined) {
				$(element).style.WebkitBoxShadow = '3px 3px 3px rgba(0,0,0,.3)';
			} else if (s.MozBoxShadow !== undefined) {
				$(element).style.MozBoxShadow = '3px 3px 3px rgba(0,0,0,.3)';
			}
			
			setTimeout(function() {	
				var button = document.createElement('div');
				button.id = 'loginButton';
				button.setStyle({
					backgroundColor: '#F5F5F5',
					width: '71px', height: '35px',
					position: 'absolute',	zIndex: '1',
					top: '-13px', right: '0'
				});
				
				$(element).insert({ top: button });
				$('username').focus();
			}, 100);
			
			topPosition = $('log-in').cumulativeOffset().top;
			new Effect.MoveBy(element, 17-topPosition, 0, {duration: 0.3,  transition: Effect.Transitions.spring });
			
			$$('#' + element + ' h4').first().fade({duration: .1});
			clickedLoginButton = true;
		} else {
			fromElement.setStyle({ color: '#FFF' });
			fromElement.style.textShadow = '1px 1px 1px #AA4E7C';
			$('reg-link').show();
			
			if (s.WebkitBoxShadow !== undefined) {
				$(element).style.WebkitBoxShadow = 'none';
			} else if (s.MozBoxShadow !== undefined) {
				$(element).style.MozBoxShadow = 'none';
			}
			
			$('loginButton').fade({duration: .1, afterFinish: function() { $('loginButton').remove() } });
			$$('#' + element + ' h4').first().appear({duration: .1});
			
			new Effect.MoveBy(element, topPosition-17, 0, {duration: 0.3,  transition: Effect.Transitions.spring });
			clickedLoginButton = false;
		}
	}
	return false;
}
/************/


function showSubmenu(e) {
	var li = e.parentNode;
	
	if (li.className.indexOf('active') == -1) {
		$(document.documentElement).observe('mouseup', function() {
			$(document.documentElement).stopObserving('mouseup');
			setTimeout(function() { li.removeClassName('active'); }, 50);
		});
	}
	
	li.addClassName('active');
	
	return false;
}

function displayMSNContacts(data) {
	if (data.errors.length > 0) {
  		data.errors.each(function(e) {
  			$('errors').descendants()[1].insert({
  			  bottom: (new Element('li')).update(e)
  			});
  		});
  		
  		$('errors').show();
  	} else {
  		$('login').hide();
  		$('contacts').show();
  		
  		var list;
  		  		
  		data.contacts.each(function(e) {
  			list = (new Element('li')).update(' ' + e);
  			list.insert({
  				top: new Element('input', {type: 'checkbox', checked: 'checked', name: 'email', value: e})
  			});
  			
  			$('contacts').descendants()[1].insert({ bottom: list });
  			
  		});
  		
  		$('contacts').show();
  		
  		if (data.contacts.length >= 20)
  			$('many_contacts').show();
  	}
}

var refSlideShow = Class.create({
  initialize: function(elementID, delay, dataSource, baseURL) {
  	this.delay = delay;
  	this.dataSource = dataSource;
  	this.baseURL = baseURL;
  	
  	this.slideImages = $$('#' + elementID + ' span');
  	this.slideCaption = $$('#' + elementID + ' figcaption')[0];
  	
  	this.count = 0;
  	
  	this.data = [];
  	this.fetch();
  	
  	setInterval(this.animate.bind(this), this.delay);
  },
  
  fetch: function() {
  	new Ajax.Request(this.dataSource, {
  		onSuccess: function(r) {
  			var tmpData = r.responseText.split("\n");
  			tmpData.pop();
  			this.data = this.data.concat(tmpData);
  			
  			return 'OK';
  		}.bind(this)
  	});
  },
  
  prepare: function() {
		this.tmp = this.data.last().split("|");
		this.data.pop();
		
		if (this.data.size() < 4) this.fetch();
		
  	if (this.count%2 == 0) {
			this.slideImages[1].style.top = '-200px';
			this.slideImages[1].childNodes[0].src = this.baseURL + this.tmp[1];
		} else {
			this.slideImages[0].style.top = '-200px';
			this.slideImages[0].childNodes[0].src = this.baseURL + this.tmp[1];
		}
		
		this.count++;
  },
  
  animate: function() {
		this.prepare();
		
		setTimeout(function() {  					
  		new Effect.Opacity(this.slideCaption, {duration:1, from:.65, to:0});
		}.bind(this), 2000);
		
		setTimeout(function() {
			new Effect.MoveBy(this.slideImages[0], 200, 0);
			new Effect.MoveBy(this.slideImages[1], 200, 0);
		}.bind(this), 3000);
		
		setTimeout(function() {
			this.slideCaption.update(this.tmp[0])
			new Effect.Opacity(this.slideCaption, {duration:1, from:0, to:.65});
		}.bind(this), 3500);
		
  }
});

function newEvents() {
	Event.observe('event_link', 'mouseover', function() {
		$('events').blindDown({duration: .3});
	});
	Event.observe('event_link', 'mouseout', function() { $('events').hide(); });
	Event.observe('events', 'mouseover', function() { this.show();	});
	Event.observe('events', 'mouseout', function() { this.hide(); });
}