var Friends = {
	init: function() {
		var self = this;
		self.timers = new Array();

		// Setup mainmenu background animation
		var width=0;
		$('UL.mainmenu LI A').each(function() {
			width += $(this).width()+39;
			$(this).bind({
				'mouseenter': function() { $(this).animate({backgroundColor: '#fdb813'}, "fast");},
				'mouseleave': function() { 
					if ($(this).parent().hasClass('shop')) $(this).animate({backgroundColor: '#FFFFFF'});
					else if ($(this).parent().hasClass('active')) $(this).animate({backgroundColor: '#fdb813'});
					else $(this).animate({backgroundColor: '#0452a5'});}
			});
		});

		// Setup character image map dialog & tooltip
		if ($('MAP#characters').length) {
			$('AREA').each(function() {
				$(this).bind('click', function() { self.showFriend(this); })
				$(this).attr('title', $($(this).attr('href')).find('H1').text());
			});

			$('AREA').tooltip({
				track: true,
				showURL: false,
				delay: 1,
				left: -40,
				top: -70
			});
		}

		if (!$('.slideshow').length) {
			$.backstretch('/wp-content/themes/friends/img/' + this.bg.img, {
				centeredX: this.bg.centeredX,
				centeredY: this.bg.centeredY,
				position: this.bg.position
			}, this.onResize);
		} else {
			$('.jCarouselLite UL LI').each(function(a) {
				var h = $(this).find('H1');
				var d = $(this).find('.myh');
				if (h.height() > 46) {
					h.css('top',216);
					d.css({
						'height': 106,
						'top': 210
					});
				} else {
					h.css('top', 255);
					d.css({
						'height': 70,
						'top': 246
					});
				}
			});
		}
		$(window).scroll(this.onResize).resize(this.onResize);

		// Fade in character intro text if needed
		if ($('#intro_info').length) {
			$('#intro_info').css({
				width: 1,
				height: 1,
				opacity: 0
			}).delay(500).show().animate({
				width: 450,
				height: 18,
				opacity: 1
			},500);//.bind('mouseover', this.hideIntroInfo);
		}

		// Animate in dialog box if needed
		if ($('.autoshow').length) {
			var x = ($(window).width() / 2) - (640/2);
			$('.autoshow').css({
				display: 'block',
				position: 'absolute',
				left: -650
			}).delay(500).animate({
				left: x
			}, 1000, 'bounceout');
		}

		if ($('.hbg').length) {
			$('.hbg').each(function() {
				$(this).height($(this).next().height()+16);
			});
		}


		$('DIV.game').each(function() {
			$(this).bind({
        'mouseenter': function() { 
					var game = this;
					var timer = setInterval(function() {
						var myt = $(game).data('timer');
						if (typeof(myt) == 'undefined' || myt == 0) {
							$(game).data('timer', timer);
							$(game).data('count', 0);
							$(game).data('stop', 0);
						}

						
						var c = $(game).data('count') || 0;
						c++;
						$(game).data('count', c);

						r = $(game).data('angle');
						if (c < 6) r = r + 2;
						else r = r - 2;
						$(game).data('angle',r);

						$(game).css('-moz-transform','rotate('+r+'deg)');
						$(game).css('-webkit-transform','rotate('+r+'deg)');
						$(game).css('-o-transform','rotate('+r+'deg)');
						$(game).css('-ms-transform','rotate('+r+'deg)');
						if (c == 10) {
							var stop = $(game).data('stop');
//							if (stop) {
								window.clearInterval(myt);
								$(game).data('timer',0);
	//						} else {
	//							$(game).data('count',0);
	//						}
						}
					}, 50);
				},
        'mouseleave': function() {
					$(this).data('stop',$(this).data('timer'));
				}
      });
		});

		$($('DIV.game')[0]).find('DIV').css('background-color', '#159B4C');
		$($('DIV.game')[1]).find('DIV').css('background-color', '#FFFFFF');
		$($('DIV.game')[2]).find('DIV').css('background-color', '#FFCD00');
		$($('DIV.game')[3]).find('DIV').css('background-color', '#FFCD00');
		$($('DIV.game')[4]).find('DIV').css('background-color', '#159B4C');
		$($('DIV.game')[5]).find('DIV').css('background-color', '#FFFFFF');

		

		if ($('.wallpaper').length) {
			$('A[rel="fancybox"]').fancybox();
		}

		setInterval(function() {
			$('.mainmenu LI.shop A').animate({backgroundColor: '#fdb813'}, 500, function() {
				$('.mainmenu LI.shop A').animate({backgroundColor: '#ffffff'}, 500);
			});
		}, 1500);

	},
	hideIntroInfo: function() {
		$('#intro_info').animate({opacity: 0}, 500, function() { $(this).hide(); });
	},

	showFriend: function(e) {
		this.hideIntroInfo();
		$('.blue_dialog').hide();
		$($(e).attr('href')).find('IMG').css('opacity',0);
		$($(e).attr('href')).find('DIV').hide();

		$($(e).attr('href')).css({
			left: $(window).width()/2 - 313,
			top: $(window).height()/2 - 198
		}).show('normal', function() {
			h = $($(e).attr('href')).find('DIV').height();
			$($(e).attr('href')).find('DIV').css('padding-top', 186- (h/2)).show();
			$($(e).attr('href')).find('IMG').animate({opacity: 1});
		});
		return false;
	},

	closeFriend: function() {
		$('.blue_dialog').hide();
	},

	playGame: function(game, size) {
		var s= size.split('x');
		var w = s[0];
		var h = s[1];

		$('#flash .inner').html('').flash({
			src: game,
			width: w,
			height: h
		});

		$('#flash').css({
			top: $(window).height()/2-(h/2),
			left: $(window).width()/2-(w/2)
		}).show();
		$('#overlay').show();

		$('#levelselect').hide();

		return false;
	},

	closeGame: function() {
		$('#flash .inner').html('');
		$('#flash, #overlay').hide();
		return false;
	},

	pickGameLevel: function(easy, easysize, medium, mediumsize, hard, hardsize) {
		$('#overlay').show();
		var o = $('#levelselect');

		$('#levelselect #easy').bind('click', function() { return Friends.playGame(easy, easysize); });
		$('#levelselect #medium').bind('click', function() { return Friends.playGame(medium, mediumsize); });
		$('#levelselect #hard').bind('click', function() { return Friends.playGame(hard, hardsize); });

		o.css({
			position: 'absolute',
			top: $(window).height()/2-(o.height()/2),
      left: $(window).width()/2-(o.width()/2)
		}).show();

		return false;
	},

	closeGameLevel: function() {
		$('#levelselect, #overlay').hide();
		return false;
	},

	playMovie: function(movie) {
		$('.sidebar_right LI').removeClass('active');
		$('#m'+movie).addClass('active');
		$('.movie_frame .inner').html('<iframe title="YouTube video player" width="700" height="405" src="http://www.youtube.com/embed/'+movie+'" frameborder="0" allowfullscreen></iframe>');
		return false;
	},

	showProduct: function(id) {
		$('#overlay').show();
		var o = $('#P'+id);
		o.css({
			top: $(window).height()/2-(o.height()/2),
			left: $(window).width()/2-(o.width()/2)
		}).show();
		return false;
	},

	closeProduct: function() {
		$('.product_details, #overlay').hide();
		return false;
	},

	checkIntro: function(e) {
		if ($.cookie("intro") == 'false') {
			Friends.stopIntro();
		} else $.cookie("intro", 'false');
	},

	stopIntro: function() {
		$('#skipintro').hide();
		$('#intro').css('top', 634);
		$('.slideshow').css({position: 'static', left: 'auto'});
		Friends.getMovie('FlashID').stopMovie();
		return false;
	},

	getMovie: function(movieName) {
		if (navigator.appName.indexOf("Microsoft") != -1 || navigator.vendor.indexOf("Apple") != -1) {
			return window[movieName];
		} else {
			return $('#'+movieName+' OBJECT')[0];
		}
	},

	switchLang: function(e) {
		path = document.location.href.replace('http://','');
		path = path.substr(path.indexOf('/'));
		document.location.href = $(e).attr('href') + path;
		return false;
	},

	share: function(t) {
    if (t == 'Facebook') {
      w = window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(location.href)+'&t='+encodeURIComponent(document.title), 'share', 'toolbar=0,status=0,width=626,height=436');
    } else if (t == 'Twitter') {
       w = window.open('http://twitter.com?status='+encodeURIComponent(document.title)+' ' + encodeURIComponent(location.href), 'sharer', 'toolbar=0,status=0,width=626,height=436');
    }
    if (w) {
      w.focus();   
      return false;
    }
	},

	doContact: function() {
		var x = ($(window).width() / 2) - (400/2);
		$('.autoshow').hide('fast');
		$('#contactform INPUT[name="Navn"]').val('');
		$('#contactform INPUT[name="Epost"]').val('');
		$('#contactform TEXTAREA[name="Kommentar"]').val('');

		$('#contactform').css({
			display: 'block',
      position: 'absolute',
      left: -650
		}).delay(500).animate({
			left: x
		}, 1000, 'bounceout');
	},

	hideContact: function() {
		$('#contactform').hide('fast');
		$('.autoshow').css({
			display: 'block',
			position: 'absolute',
			left: -650
		}).delay(500).animate({
			left: ($(window).width() / 2) - (640/2)
		}, 1000, 'bounceout');
		return false;
	},

	submitContactForm: function() {
		var options = {};
    var fields = ['Navn', 'Epost', 'Kommentar'];
    for (i in fields) {
      options[fields[i]] = $('#contactform [name="'+fields[i]+'"]').attr('value');
    }  
    $.getJSON('/api/friends/contact_form/', options, $.proxy(this.returnContactForm, this));

    return false;
  },

  returnContactForm: function(data) {
    if (data.status == 'ok') {
			hideContact();
    } else {
      alert('An unknown error occured. Please try again later.');
    }
  },

	onResize: function() {
		if ($('MAP#characters').length) {
			var rw = $('#backstretch IMG').width() / 1600;
			var rh = $('#backstretch IMG').height() / 800;

			$('AREA').each(function() {
				var pairs = $(this).attr("orig").split(', ');
				for(var i=0; i<pairs.length; i++) {
					var nums = pairs[i].split(',');
					nums[0] = nums[0] * rw;
					nums[1] = nums[1] * rh;
					pairs[i] = nums.join(',');
				}
				$(this).attr("coords", pairs.join(', '));
			});
		}
		if ($('.frame_adjustable').length) {
			var w = Math.floor($(window).width() / 252);
			if (w > 4) w = 4;
			$('.frame_adjustable').css('width', 252 * w);
		}

		// Center flash if visible
		if ($('#flash').is(':visible')) {
			$('#flash').css({
				top: $(window).height()/2-$('#flash').height() / 2,
				left: $(window).width()/2-$('#flash').width() / 2
			});
		}
		// Center product details if visible
		if ($('.product_details').is(':visible')) {
			var o = $('.product_details:visible');
			o.css({
				top: $(window).height()/2-(o.height()/2),
				left: $(window).width()/2-(o.width()/2)
			});
		}
		// Center blue dialog if visible
		if ($('.blue_dialog').is(':visible')) {
			var o = $('.blue_dialog:visible');
			o.css({
				top: $(window).height()/2-(o.height()/2),
				left: $(window).width()/2-(o.width()/2)
			});	
		}

		// Center blue dialog if visible
		if ($('.white_dialog').is(':visible')) {
			var o = $('.white_dialog:visible');
			o.css({
				top: $(window).height()/2-(o.height()/2),
				left: $(window).width()/2-(o.width()/2)
			});	
		}

		if ($('#overlay').is(':visible')) {
			$('#overlay').css('height', $(document).height());
		}
	}
}
$(document).ready(function() { Friends.init(); });

