(function($){
	// TODO: make this more flexible
	$.fn.createSelect = function(options) {
		
		var defaults = {}
		
		var options = $.extend(defaults, options);
		
		return this.each(function() {
			var selectEl = $(this).before('<select></select');
			var master = $(this).prevAll('select');
			var lbl = $(this).children('h5');
			if(lbl.length > 0) {
				master.append('<option value="">' + lbl.text() + '</option>');
			}
			var slaves = $(this).children('ul');
			for (var i = 0; i < slaves.length; i++) {
				// if there's a title on the ul/element use that as optgroup label
				if($(slaves[i]).attr('title') != "") {
					master.append('<optgroup label="' + $(slaves[i]).attr('title') + '"></optgroup>');
					var optFlag = 1;
				}
				var slaveEls = $(slaves[i]).children();
				slaveEls.each(function() {
					if(optFlag == 1) {	
						$(master).children('optgroup').eq(i).append('<option value="' + $(this).children('a').attr('href') + '">' + $(this).children('a').text() + '</option>');
					}
					else {
						$(master).append('<option value="' + $(this).children('a').attr('href') + '">' + $(this).children('a').text() + '</option>');
					}
				});
			}
			
			$(this).before('<a class="download-btn download-btn-disabled" href="#"><span>Download</span></a>');
			$(this).remove();
								  
		});
	};

})(jQuery);

$(document).ready(function () {
	
	//HOMEPAGE NEWS
	$('#news-accordion .content:eq(0)').removeClass('display-none');
	$('#news-accordion li:gt(0)').removeClass('open');
	if ($('.blank-body div.latest-news').length > 0) {
		$('div.latest-news ul.navigation li a').click(function(e) {
			e.preventDefault();
			if ($(this).parent().hasClass('blog')) {
				$('div.latest-news ul.navigation li a.active').removeClass('active');
				$('div.latest-news ul.navigation li.blog a').addClass('active');
				$('div.latest-news ul#news-accordion').fadeOut('500', function() { 
					$('div.latest-news ul#blog').fadeIn('500');
				});
			} else {
				$('div.latest-news ul.navigation li a.active').removeClass('active');
				$('div.latest-news ul.navigation li.news a').addClass('active');
				$('div.latest-news ul#blog').fadeOut('500', function() { 
					$('div.latest-news ul#news-accordion').fadeIn('500');
				});
			}
		});
		$('div.latest-news ul.news-list li h3 a').live('click', function(e) {
			if ($(this).parent().parent().children('p.content').is(':visible')) {
				// if the content is visible, do nothing in particular -- i.e. let the click propagate normally
			} else {
				// the panel is closed, open it up and prevent default on header lnk
				e.preventDefault();
				$(this).parent().parent().parent().children('li.open').children('p.content').slideUp('500');
				$(this).parent().parent().parent().children('li.open').removeClass('open');
				$(this).parent().parent().children('p.content').slideDown('500');
				$(this).parent().parent().addClass('open');
				return false;
			}
		});
	};
	
	$('div.download-content').hide();
	$('a#download-vid').addClass('download-vid-closed');
	$('a#download-vid').click(function(e) {
		e.preventDefault();
		if ($("div.download-content").is(":hidden")) {
			$('a#download-vid').removeClass('download-vid-closed');
			$('a#download-vid').addClass('download-vid-open');
       		$("div.download-content").slideDown("slow");
     	} else {
			$('a#download-vid').removeClass('download-vid-open');
			$('a#download-vid').addClass('download-vid-closed');
      		$("div.download-content").slideUp("slow");
     	}
	});
	
	var initVal = $('input.input-text').val();

	$("input.input-text").focus(function() {
		if($(this).hasClass("empty")) {
			$(this).val('');
		}
	});

	$("input.input-text").blur(function() {
		if($(this).val()) {
			$(this).removeClass("empty");
		}
		else {
			if($(this).val() == initVal) {
				$(this).val('');
			}
			$(this).val(initVal);
		}
	});	
		
	// Wallpapers
	if ($('#wallpapers').length > 0) {
		
		// create select elements from list
		$('div.dl').createSelect();
				
		// 'Disable' btns until something is selected
		var btns = $('.download-btn');
		btns.addClass('download-btn-disabled');
		
		btns.each(function(i) {
			$(this).click(function(e) {
				if($(this).hasClass('download-btn-disabled')) {
					e.preventDefault();
				}
			});
		});
		
		$('.download select').each(function(i) {
			$(this).change(function(e) {
				var btn = $(this).nextAll('a.download-btn');					
				if($(this).val() !== "") {
					btn.attr('href', $(this).val());
					btn.removeClass('download-btn-disabled');
					btn.attr('target', '_blank');
				}
				else {
					btn.attr('href', '#');
					btn.addClass('download-btn-disabled');
					btn.attr('target', '_self');
				}
				
			});
		});
	}
	
	var shareItFB = {
		'overlayOpacity': 0.8,
		'overlayColor': '#000',
		'margin': 45,
		/*'titlePosition': 'over',
		'onComplete': function() {
			$("#fancybox-wrap").hover(function() {
				$("#fancybox-title").show();
			}, function() {
				$("#fancybox-title").hide();
			});
		},*/
		'titleShow': false,
		'onStart': function(selectedArray, selectedIndex, selectedOpts) {
			var lnkID = $(selectedArray[selectedIndex]).attr('id');
			if(!lnkID) {
				lnkID = '';
			}
			$('#fancybox-outer').shareIt({shareType: 'custom', triggerID: lnkID, sites: ['delicious', 'digg', 'facebook', 'reddit', 'twitter']});
		}
	};
	
	$('.fancybox, div.concept-art a').fancybox(shareItFB); 
	
	// This should be put into a function
	if($('#video-container').length > 0) {
		//EMBED
		// Multiple video embed
		// if($('ul.video-list').length > 0){	
			$('#video-container').append('<div class="embed-it"><a href="#">Embed</a></div>');
			var width = $('#video-player').width();
			var height = $('#video-player').height();	
			var first = $('ul.video-list li:first a');
			var video = first.attr('rel') + first.attr('id') + ".flv";
			var videoID = $('.video-list li:first-child').attr('id');
			var embed = '<object width="' + width + '" height="' + height + '"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://www.guildwars2.com/global/includes/flash/gw2player.swf?poster=http://www.guildwars2.com/global/includes/images/skills-video-poster.jpg&amp;video=' + video + '" /><embed src="http://www.guildwars2.com/global/includes/flash/gw2player.swf?poster=http://www.guildwars2.com/global/includes/images/skills-video-poster.jpg&amp;video=' + video + '" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed></object>';
			$('#video-container div.embed-it').append('<textarea onfocus="this.select()" onclick="this.select()" readonly="readonly" style="display:none">' + String(embed) + '</textarea>');
			$('#video-container div.embed-it a').live('click', function(e) {
				e.preventDefault();
				$('#video-container div.embed-it textarea').animate({opacity:'toggle'}, '500');
			});	
			$('#video-container').shareIt({shareType: 'custom', triggerID: videoID, sites: ['delicious', 'digg', 'facebook', 'reddit', 'twitter']});
		// }		
		
	}

	if(window.location.hash) {
		dispatcher();
	}
	
	// if there's a hash in the URI, deal with it
	function dispatcher() {
		
		var target = window.location.hash.substr(1);
		var currOffset = 0;
		var speed = 600; // animation speed
		
		// video stuff
		if($('ul.video-list li#' + target).length > 0) {
			/*currItem = $('ul.video-list li#' + target);
			currItem.children('a').addClass('active');*/
			currOffset = $('#video-player').offset().top - 50;
			$('html, body').animate({scrollTop: currOffset}, speed);
			
			videoSwitch($('ul.video-list li#' + target + ' a'));
		}
		// everything else
		else {
			if ($('#video-player').length > 0)
				videoSwitch($('ul.video-list li:first a'));
			
			if($('#' + target).length > 0) {
				currOffset = $('#' + target).offset().top - 50;
				/*currItem = $('ul.video-list li:first');
				currItem.children('a').addClass('active');*/
				$('html, body').animate({scrollTop: currOffset}, speed, function() {
					$('a#' + target).fancybox(shareItFB).trigger('click');
				});
			}	
		}
	} 
	

		//VIDEO
	if ($('#video-player').length > 0) {
		var currItem;
		if (window.location.hash && $('ul.video-list li#' + window.location.hash.substr(1))) {
			currItem = $('ul.video-list li#' + window.location.hash.substr(1));
			videoID = window.location.hash.substr(1);
			$('#video-container').shareIt({shareType: 'custom', triggerID: videoID, sites: ['delicious', 'digg', 'facebook', 'reddit', 'twitter']});
		} else {
			currItem = $('ul.video-list li:first');
		}

		currItem.children('a').addClass('active');
		
		$('ul.video-list li a').click(function(e) {
			e.preventDefault();
			$('ul.video-list li a.active').removeClass("active");
			$(this).addClass("active");
			currItem = $(this).parent();
			videoID = currItem.attr('id');
			
			videoSwitch($(this));
			
			$('#video-container').shareIt({shareType: 'custom', triggerID: videoID, sites: ['delicious', 'digg', 'facebook', 'reddit', 'twitter']});
			if ($('object#video-player').length > 0)
				$('object#video-player')[0].autoPlay($(this).attr('rel') + $(this).attr('id') + ".flv");
		});
		
		var vars;
		if ($("#skills ul.video-list").length > 0) {
			vars = {
				poster:"/global/includes/images/skills-video-poster.jpg", 
				video:$('ul.video-list li a.active').attr('rel') + $('ul.video-list li a.active').attr('id') + ".flv"
			}
		} else {
			vars = {
				poster:"/global/includes/images/video-poster.jpg", 
				video:$('ul.video-list li a.active').attr('rel') + $('ul.video-list li a.active').attr('id') + ".flv"
			}
		}
		var params = { 
			allowFullScreen:"true", 
			base:"", 
			bgcolor:"#000000", 
			menu:"false", 
			wmode:"opaque"
		}
		var attributes = {
			id: "video-player", 
			name: "video-player"
		}
		swfobject.embedSWF("/global/includes/flash/gw2player.swf?" + new Date().getTime(), "video-player", $('#video-player').width(), $('#video-player').height(), "9.0.124", "", vars, params, attributes);
	}
	

	
	//VIDEO SWITCH
	function videoSwitch(target) {
		if ($('div.download-content a').length > 0 && $('div.download-content a').attr('class') == "") {
			$('div.download-content a').attr('class', $('ul.video-list li:first a').attr('id').replace("_Small", ""));
			$('div.download-content a').attr('rel', $('ul.video-list li:first a').attr('rel'));
		}
		
		var downloadLinks = $('div.download-content a');
		var currURL = target.attr('rel');
		var currTrailer = target.attr('id').replace("_Small", "");
		downloadLinks.each(function(i) {
			$(this).attr('href', $(this).attr('href').replace($(this).attr('class'), currTrailer));
			$(this).attr('href', $(this).attr('href').replace($(this).attr('rel'), currURL));
			$(this).removeClass($(this).attr('class'));
			$(this).addClass(currTrailer);
			$(this).attr('rel', currURL);
		});
		
		if ($('div.embed-it').length > 0) {
			var width = $('#video-player').width();
			var height = $('#video-player').height();
			var video = currURL + target.attr('id') + ".flv";
			var embed = '<object width="' + width + '" height="' + height + '"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://www.guildwars2.com/global/includes/flash/gw2player.swf?poster=http://www.guildwars2.com/global/includes/images/skills-video-poster.jpg&amp;video=' + video + '" /><embed src="http://www.guildwars2.com/global/includes/flash/gw2player.swf?poster=http://www.guildwars2.com/global/includes/images/skills-video-poster.jpg&amp;video=' + video + '" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed></object>';
			$('div.embed-it textarea').attr('value', embed);
		}
	}
	
	// move the share this widget with the window
	if($('#share-this-widget').length > 0) {
	    var $widget = $("#share-this-widget");
	    var $window = $(window);
	    var $offset = $widget.offset();
	    var $initialMargin = $widget.css('marginTop');
	
	    $window.scroll(function() {
	        if ($window.scrollTop() > $offset.top) {
	            $widget.stop().animate({
	                marginTop: $window.scrollTop() - $offset.top
	            });
	        } else {
	            $widget.stop().animate({
	                marginTop: $initialMargin
	            });
	        }
	    });
	}
	
	jQuery.extend( jQuery.easing,
	{
		easeOutSine: function (x, t, b, c, d) {
			return c * Math.sin(t/d * (Math.PI/2)) + b;
		},
		easeInBack: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.70158;
			return c*(t/=d)*t*((s+1)*t - s) + b;
		}
	});
	
	// newsletter signup form animation
	var $up = "-90px";
	var $down = "-20px";
	$('a.signupToggle').toggle(function() {
		$('#newsletter-signup').animate({"top": $down}, "slow", "easeOutSine");
		$('#newsletter-signup a.signupToggle').addClass("signupToggleActive");
	},function() {
		if ($('#newsletter-signup').css('top') === '0px') {
				$('#newsletterErrorContainer').empty();
				$('#newsletter-signup').animate({"top": $up}, "slow");
		} else {
			$('#newsletter-signup').animate({"top": $up}, "slow", "easeInBack");	
		};
		$('#newsletter-signup a.signupToggle').removeClass("signupToggleActive");
	})
	
	$("input.input").focus(function(){
	     if(this.value === this.defaultValue){
	          this.value = '';
	     }
	});          
	$("input.input").blur(function() {                                                                              
	     if(this.value === ''){
	          $(this).val(this.defaultValue);        
	     }                                                                                           
	});

	
	
});

// Loads videos individually sans list
function loadSingleVideo(videoURL, loc){
		//EMBED FLASH PLAYER
	 
		$('#single-video-container').append('<div class="embed-it"><a href="#">Embed</a></div>');
		var width = $('#video-player').width();
		var height = $('#video-player').height();
		var embed = '<object width="' + width + '" height="' + height + '"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://www.guildwars2.com/global/includes/flash/gw2player.swf?poster=http://www.guildwars2.com/global/includes/images/skills-video-poster.jpg&video=' + videoURL + '" /><embed src="http://www.guildwars2.com/global/includes/flash/gw2player.swf?poster=http://www.guildwars2.com/global/includes/images/skills-video-poster.jpg&video=' + videoURL + '" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed></object>';
			$('#single-video-container div.embed-it').append('<textarea onfocus="this.select()" onclick="this.select()" readonly="readonly" style="display:none">' + String(embed) + '</textarea>');
			$('#single-video-container div.embed-it a').live('click', function(e) {
				e.preventDefault();
				$('#single-video-container div.embed-it textarea').animate({opacity:'toggle'}, '500');
			});	
		// Specify default start screen for videos here
	 	switch(loc){
			case ("en"):
				var posterURL = "/global/includes/images/video-poster.jpg";
			break;
			case ("fr"): 
			case("de"):
				posterURL= "/global/includes/images/video-poster.jpg";
			break;
			default:
				posterURL = "/global/includes/images/video-poster.jpg";
			break;
			
		}
		
		var vars = {
			video: videoURL,
			poster: posterURL 
		}
		
		var params = { 
			allowFullScreen:"true", 
			base:"", 
			bgcolor:"#000000", 
			menu:"false", 
			wmode:"opaque"
		}
		
		var attributes = {
				id: "video-player", 
				name: "video-player"
			}
		var videoID = ""; // requires a anchor to work properly

		swfobject.embedSWF("/global/includes/flash/gw2player.swf?" + new Date().getTime(), "video-player", $('#video-player').width(), $('#video-player').height(), "9.0.124", "", vars, params, attributes);
		
		$('#single-video-container').shareIt({shareType: 'custom', triggerID: videoID, sites: ['delicious', 'digg', 'facebook', 'reddit', 'twitter']});
		
	}



