$(document).ready(function () {
	initNav();
	initHeads();
	initDownloads();
	initVideos();
	initQuotes();
	initShare();
	initFeed("https://api.twitter.com/1/statuses/user_timeline.json?callback=feedLoaded&include_entities=true&include_rts=true&trim_user=false&contributor_details=true&screen_name=thearmed&count=5");

	$(window).scroll(function () { 
		if($("#nav").css("position")=="absolute"){
			$("#nav").css("top", $(window).scrollTop());
		}
	});

});

/* NAV */

var dl_y;
var media_y;

function initNav(){
	dl_y = $("#c_download").offset().top-95;
	media_y = $("#c_media").offset().top-95;
	$("#nav_logo").click(function(){
		$.scrollTo(0,500);
	});
	$("#nav_dl").click(function(){
		$.scrollTo(dl_y,500);
	});
	$("#nav_vid").click(function(){
		$.scrollTo(media_y,500);
	});
	$("#nav_feed").click(function(){
		$.scrollTo(media_y,500);
	});
	$("#nav_store").click(function(){
		window.open('http://thearmed.bigcartel.com/');
	});
	$(".nav_link").hover(function(){
		$(this).stop(false,false).css("color","#880000");
	}, function(){
		$(this).stop(false,false).css("color","#000000");
	});
	$(".nav_icon").hover(function(){
		$(this).stop(false,false).animate({"top": "0px"}, 150);
	}, function(){
		$(this).stop(false,false).animate({"top": "-12px"}, 150);
	});
}

/* HEADER IMAGE */

var c_head = "";
var heads_array = new Array();
var head_page_tmb_off = "#222";
var head_page_tmb_over = "#aaa";
var head_page_tmb_on = "#880000";
var auto_swap_head;

function initHeads(){
	heads_array.push({"id":"head_yb","src":"img/head/20111006_01.jpg","action":function(){
		$.scrollTo(dl_y,500);
	}});
	heads_array.push({"id":"head_merch","src":"img/head/20111006_02.jpg","action":function(){
		window.open('http://thearmed.bigcartel.com/');
	}});
	heads_array.push({"id":"head_dls","src":"img/head/20111006_03.jpg","action":function(){
		$.scrollTo(dl_y,500);
	}});
	for(var h=0;h<heads_array.length;h++){
		$("#head_rot_wrap").append('<div class="head_img" id="'+heads_array[h].id+'" index="'+h+'"><img src="'+heads_array[h].src+'"></div>');
		$("#head_pages").append('<div class="head_page_tmb" id="'+heads_array[h].id+'_tmb" active="false"></div>');
		$("#"+heads_array[h].id).click(function(){
			heads_array[$(this).attr("index")].action();
		});
	}
	$(".head_page_tmb").each(function(){
		$(this).click(function(){
			if($(this).attr("active")=="false") swapHead(this);
		});
		$(this).hover(function(){
			if($(this).attr("active")=="false") $(this).css("background-color",head_page_tmb_over);
		}, function(){
			if($(this).attr("active")=="false") $(this).css("background-color",head_page_tmb_off);
		});
	});
	swapHead($("#"+heads_array[0].id+"_tmb"));
}

function swapHead(new_head){
	var s_end;
	var s_start;
	if(new_head==null){
		if((parseInt($("#"+c_head).attr("index"))+1)<heads_array.length){
			new_head = $("#"+heads_array[parseInt($("#"+c_head).attr("index"))+1].id+"_tmb");
		} else {
			new_head = $("#"+heads_array[0].id+"_tmb");
		}
	}
	if(c_head==""){
		c_head = $(new_head).attr("id").substr(0,$(new_head).attr("id").length-4);
		$("#"+c_head).css("display","block").fadeIn(800);
		$("#"+$(new_head).attr("id")).attr("active","true").css("background-color",head_page_tmb_on);
	} else {
		var n_head = $(new_head).attr("id").substr(0,$(new_head).attr("id").length-4);
		if($("#"+c_head).attr("index")>$("#"+n_head).attr("index")){
			s_end = "300px";
			s_start = "-300px";
		} else {
			s_end = "-300px";
			s_start = "300px";
		}
		
		$("#"+c_head).stop(false,false).animate({"margin-left":s_end,"opacity":"0"},500, function() {
			$(this).css("display","none").css("margin-left","0px");
		});
		$("#"+n_head).css("display","block");
		$("#"+n_head).css("opacity","0");
		$("#"+n_head).css("margin-left",s_start);
		$("#"+n_head).stop(false,false).animate({"margin-left":"0px","opacity":"1"},500);
		c_head = n_head;
	}
	if(c_head=="head_yb"){
		head_page_tmb_off = "#fff";
		head_page_tmb_over = "#aaa";
		head_page_tmb_on = "#7af4f0";
	} else {
		head_page_tmb_off = "#222";
		head_page_tmb_over = "#aaa";
		head_page_tmb_on = "#880000";
	}
	$(".head_page_tmb").each(function(){
		$(this).attr("active","false").css("background-color",head_page_tmb_off);
	});
	$("#"+$(new_head).attr("id")).attr("active","true").css("background-color",head_page_tmb_on);
	clearTimeout(auto_swap_head);
	auto_swap_head = setTimeout("swapHead()",10000);
	
}

/* DOWNLOADS */

function initDownloads(){
	$(".dl_radio").each(function(){
		$(this).css("background-position","-"+(Math.floor(Math.random()*600))+"px -"+(Math.floor(Math.random()*305))+"px");
	});
	$(".dl_radio_content").each(function(){
		resetRadio(this);
	});
	$(".dl_title").mouseover(function(){
		handleTitleEvent("over",$(this).attr("dl_radio"));
	});
	$(".dl_title").mouseout(function(){
		handleTitleEvent("out",$(this).attr("dl_radio"));
	});
	$(".dl_title").click(function(){
		handleTitleEvent("click",$(this).attr("dl_radio"));
	});
	
	$("#dl_email").hover(function(){
		if($(this).val()=="ENTER.YOUR@EMAIL.HERE"){
			$(this).stop().animate({"padding-top":"180px"},250);
			$(this).css("background","none");
			$(this).css("opacity","1");
		}
	}, function(){
		$(this).stop().animate({"padding-top":"0px"},250);
	});
	$("#dl_email").focus(function(){
		if($(this).val()=="ENTER.YOUR@EMAIL.HERE"){
			$(this).val("");
			$(this).stop().css("padding-top","0px");
		}
	});
	$("#dl_email").focusout(function(){
		if($(this).val()==""){
			$(this).val("ENTER.YOUR@EMAIL.HERE");
			$(this).stop().css("padding-top","180px").animate({"padding-top":"0px"},250);
		}
	});
	$("#dl_submit").hover(function(){
		$(this).css("backgroundColor","#222222");
	}, function(){
		$(this).css("backgroundColor","#880000");
	});
	$("#dl_submit").click(function(){
		handleDownload();
	});
}

function resetRadio(radio){
	$(radio).mouseover(function(){
		$(this).stop(false,false).animate({"left": "-110px"}, 150);
	});
	$(radio).mouseout(function(){
		$(this).stop(false,false).animate({"left": "0px"}, 150);
	});
	$(radio).click(function(){
		$(this).stop(false,false).animate({"left": "-220px"}, 10);
		$(this).css("left","-220px");
		handleRadioCheck(this);
	});	
	$(radio).attr("enabled","false");
}

function handleTitleEvent(type,title){
	if(type=="over"){
		if($("#"+title+"ll").attr("enabled")=="false"){
			$("#"+title+"ll").stop(false,false).animate({"left": "-110px"}, 150);
		}
	} else if(type=="out"){
		if($("#"+title+"ll").attr("enabled")=="false"){
			$("#"+title+"ll").stop(false,false).animate({"left": "0px"}, 150);
		}
	} else if(type=="click"){
		if($("#"+title+"ll").attr("enabled")=="false"){
			$("#"+title+"ll").stop(false,false).animate({"left": "-220px"}, 10);
			$("#"+title+"ll").css("left","-220px");
			handleRadioCheck("#"+title+"ll");
		} else {
		
		}
	}
}

function handleRadioCheck(radio){
	$(radio).attr("enabled","true");
	$(radio).unbind("mouseover").unbind("mouseout").unbind("click");
	$(radio).click(function(){
		$(this).stop(false,false).animate({"left": "-110px"}, 10);
		$(radio).css("left","-110px");
		resetRadio(this);
	});
	var option = $(radio).attr("opt");
	if($("#"+option).attr("enabled")=="true"){
		$("#"+option).css("left","0px");
		resetRadio($("#"+option));
	}
}

function handleDownload(){
	if(validateEmailAddress($("#dl_email").val())==false){
		$("#dl_email").css("background-color","#880000");
		$("#dl_email").css("opacity","1").animate({opacity: 0},1200,function(){
			$("#dl_email").css("background","none").animate({opacity: 1},200)
		});
		return false;
	}
	var dl_checked = false;
	var downloads = [];
	downloads["yb_dl"] = 0;
	downloads["ce_dl"] = 0;
	downloads["tal_dl"] = 0;
	$(".dl_radio_content").each(function() {
		if($(this).attr("enabled")=="true"){
			downloads[$("#"+$(this).attr("dl_title")).attr("dl_radio")+"dl"] = $(this).attr("val");
			dl_checked = true;
		}
	});
	if(!dl_checked){
		$(".dl_radio_content").each(function() {
			$(this).css("background-color","#880000");
			$(this).css("opacity","1").animate({opacity: 0},200,function(){
				$(this).css("background","none").animate({opacity: 1},10)
			});
		});
		return false;
	}
	$.ajax({
		url: "register.php",
		global: false,
		type: "POST",
		data: {email: $("#dl_email").val(),
			yb: parseInt(downloads["yb_dl"]),
			ftce: parseInt(downloads["ce_dl"]),
			tal: parseInt(downloads["tal_dl"])},
		dataType: "html",
		async:false,
		success: function(msg){
			if(msg=="error"){
				alert("There was an error.");
			} else {
				startDownload(msg);
			}
		}
	});
}

function startDownload(file){
	window.open("download.php?dl="+file); 
}

function validateEmailAddress(emailAddress){
	if(emailAddress=="ENTER.YOUR@EMAIL.HERE") return false;
	expression = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
	if (!expression.test(emailAddress)){
		return false;
	}
	return true;
}

/* VIDEOS */

var yt_vids = [];
var curr_vid = 0;

function initVideos(){
	$("#vid_nav_prev").hover(function(){
		$(this).removeClass("vid_nav_off");
		$(this).addClass("vid_nav_on");
		$(this).find(".vid_nav_wrap").stop(false,false).animate({"left": "0px"}, 250);
	}, function(){
		$(this).removeClass("vid_nav_on");
		$(this).addClass("vid_nav_off");
		$(this).find(".vid_nav_wrap").stop(false,false).animate({"left": "-60px"}, 150);
	});	
	$("#vid_nav_prev").click(function(){
		changeVid(curr_vid-1);
	});
	$("#vid_nav_next").hover(function(){
		$(this).removeClass("vid_nav_off");
		$(this).addClass("vid_nav_on");
		$(this).find(".vid_nav_wrap").stop(false,false).animate({"left": "-60px"}, 250);
	}, function(){
		$(this).removeClass("vid_nav_on");
		$(this).addClass("vid_nav_off");
		$(this).find(".vid_nav_wrap").stop(false,false).animate({"left": "0px"}, 150);
	});
	$("#vid_nav_next").click(function(){
		changeVid(curr_vid+1);
	});
	$(".vid_title").fadeIn(1000);
	$("#vid_nav").css("display","none");
	jQuery.getFeed({
        url: "youtube.php",
        success: function(feed) {
			for(var i=0;i<feed.items.length;i++){
				yt_vids.push(feed.items[i]);
			}
			for(var v=0;v<yt_vids.length;v++){
				yt_vids[v].title = replaceQuotes(yt_vids[v].title);
			}
			changeVid(0);
			$("#vid_nav").css("display","block");
			//$("#vid_nav").fadeIn(1000);
		}
    });
}

function changeVid(i){
	var pre_i = i-1;
	var post_i = i+1;
	if(i<0){
		i = yt_vids.length-1;
		pre_i = yt_vids.length-2;
		post_i = 0;
	} else if(i==yt_vids.length){
		i = 0;
		pre_i = yt_vids.length-1;
		post_i = 1;
	}
	if(post_i>yt_vids.length-1){
		post_i = 0;
	}
	if(pre_i<0){
		pre_i = yt_vids.length-1;
	}
	yt_vids[i].title = replaceQuotes(yt_vids[i].title);
	$("#vid_main_title").html(yt_vids[i].title);
	var v_id = yt_vids[i].id.slice(yt_vids[i].id.lastIndexOf("/")+1,yt_vids[i].id.length);
	var v_embed = '<object width="715" height="427">\n';
	v_embed += '<param name="movie" value="http://www.youtube.com/v/'+v_id+'?fs=1&hd=1"</param>\n';
	v_embed += '<param name="allowFullScreen" value="true"></param>\n';
	v_embed += '<param name="allowScriptAccess" value="always"></param>\n';
	v_embed += '<param name="wmode" value="transparent"></param>\n';
	v_embed += '<embed src="http://www.youtube.com/v/'+v_id+'?fs=1&hd=1"\n';
	v_embed += 'type="application/x-shockwave-flash"\n';
	v_embed += 'allowfullscreen="true"\n';
	v_embed += 'allowscriptaccess="always"\n';
	v_embed += 'wmode="transparent"\n';
	v_embed += 'width="715" height="427">\n';
	v_embed += '</embed>\n';
	v_embed += '</object>';
	$("#vid_embed").html(v_embed);
	$("#vid_nav_prev").find(".vid_title").html(yt_vids[pre_i].title);
	$("#vid_nav_next").find(".vid_title").html(yt_vids[post_i].title);
	curr_vid = i;
}

function replaceQuotes(str){
	var tmp1;
	var tmp2 = str;
	var i = str.indexOf('"');
	if(i!=-1){
		var i2 = str.indexOf('"',i+1);
		if(i2!=-1){
			tmp1 = str.replace('"','&lsquo;');
			tmp2 = tmp1.replace('"','&rsquo;');
		}
	}
	if(tmp2==str){
		return str;
	} else {
		return tmp2;
	}
}

/* TWATS */

function initFeed(url){
	var script = document.createElement("script")
	script.type = "text/javascript";
	if (script.readyState){
		script.onreadystatechange = function(){
			if (script.readyState == "loaded" || script.readyState == "complete"){
				script.onreadystatechange = null;
			}
		};
	}
	script.src = url;
	document.getElementsByTagName("head")[0].appendChild(script);
}

function feedLoaded(tweets) {
  var statusHTML = [];
  for (var i=0; i<tweets.length; i++){
    var username = tweets[i].user.screen_name;
    var status = tweets[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
		return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
		return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
	if(tweets[i].retweeted_status){
		status = tweets[i].retweeted_status.text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
			return '<a href="'+url+'">'+url+'</a>';
		}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
			return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
		});
		statusHTML.push('<li class="feed_entry"><div class="feed_img"><img src="'+tweets[i].retweeted_status.user.profile_image_url+'"></div><div class="feed_text"><span>'+status+'</span><br /><span class="feed_time"><a href="http://twitter.com/'+tweets[i].retweeted_status.user.screen_name+'/statuses/'+tweets[i].retweeted_status.id_str+'">'+relative_time(tweets[i].created_at)+'</a></span><br /><span class="feed_rt"><a href="http://twitter.com/'+tweets[i].retweeted_status.user.screen_name+'/">'+tweets[i].retweeted_status.user.name+'</a> <img src="img/feed_rt.png"> by <a href="http://twitter.com/'+username+'/">'+tweets[i].user.screen_name+'</a></span></div></li>');
	} else {
		statusHTML.push('<li class="feed_entry"><div class="feed_img"><img src="'+tweets[i].user.profile_image_url+'"></div><div class="feed_text"><span>'+status+'</span><br /><span class="feed_time"><a href="http://twitter.com/'+username+'/statuses/'+tweets[i].id_str+'">'+relative_time(tweets[i].created_at)+'</a></span></div></li>');
	}
  }
  $("#feed_entry_list").html(statusHTML.join(""));
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return "less than a minute ago";
  } else if(delta < 120) {
    return "about a minute ago";
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + " minutes ago";
  } else if(delta < (120*60)) {
    return "about an hour ago";
  } else if(delta < (24*60*60)) {
    return "about " + (parseInt(delta / 3600)).toString() + " hours ago";
  } else if(delta < (48*60*60)) {
    return "1 day ago";
  } else {
    return (parseInt(delta / 86400)).toString() + " days ago";
  }
}

/* QUOTES */

var quotes = ["Your thoughts are precious nothing without an execution.","It's time to party and never stop.","We'll burn this house into the ground.","Treading water while the world around you keeps on falling apart.","Only accomplished in your own mind you've earned the name liar.","Up in your head all day. Nothing you've done is real.","We won't stop and we won't give at all.","We are not complacent or hobbyists.","You swing the hammer and just one by one, the fall.","I fight my war each day and every single night.","Patience is what they teach to keep you complacent.","You ever feel like you're being followed?","You're in a burning theater.","And that's what you get for judging me by a handshake.","We are the greatest band in the entire world.","Destroy garbage music."]
var use_quotes = [];

function initQuotes(){
	$("#foot_quote_wrap").css("opacity","0");
	$("#foot_rand_on").stop(false,true).animate({"clip":"rect(0px 166px 166px 166px)"},10);
	$("#foot_rand").hover(function(){
		$("#foot_rand_on").stop(false,false).animate({"clip":"rect(0px 166px 166px 0px)"},200);
	}, function(){
		$("#foot_rand_on").stop(false,true).animate({"clip":"rect(0px 166px 166px 166px)"},200);
	});
	$("#foot_rand").click(function(){
		randQuote();
	});
	$("#foot_share_fb").css("width","166px");
	$("#foot_share_tw").css("width","166px");
	randQuote();
}

function randQuote(){
	if(use_quotes.length==0){
		use_quotes = quotes.slice();
		jQuery.shuffle(use_quotes);
	}
	$(".foot_ldquo").stop(false,false).animate({"left":"-154px","opacity":"0"},400);
	$("#foot_quote").stop(false,false).animate({"left": "-20px"},600);
	$("#foot_quote_wrap").animate({"opacity": "0"},400,function(){
		$("#foot_quote").html(use_quotes[0]);
		$("#foot_quote_wrap").css("opacity","0").animate({"opacity": "1"},400)
		$("#foot_quote").stop(false,false).css("left", "20px").animate({"left": "0px"},300);
		$(".foot_ldquo").stop(false,false).css("left", "-124px").animate({"left":"-144px","opacity":"1"},300);
	})
	use_quotes.shift();
}

/* SHARE */

var t_sharehide;

function initShare(){
	$(".foot_share_copy p").css("display","none");
	$("#foot_share_on").stop(false,true).animate({"clip":"rect(0px 166px 166px 166px)"},10);
	$("#foot_share").attr("enabled","false");
	$("#foot_share").click(function(){
		if($(this).attr("enabled")=="false"){
			showShareTabs();
		}
	});
	$("#foot_share").hover(function(){
		clearTimeout(t_sharehide);
		$("#foot_share_on").stop(false,false).animate({"clip":"rect(0px 166px 166px 0px)"},200);
	}, function(){
		clearTimeout(t_sharehide);
		t_sharehide = setTimeout("hideShareTabs()",800);
	});
}

function showShareTabs() {
	$("#foot_share").attr("enabled","true");
	$("#foot_share_fb").hover(function(){
		$(this).click(function(){
			window.open('http://www.facebook.com/sharer/sharer.php?s=%20100&p[title]=The%20Armed&p[url]=http%3A%2F%2Fthearmed.com&p[images][0]=http%3A%2F%2Fthearmed.kurilkomatic.com/img/thumb.jpg&p[summary]='+encodeURIComponent($("#foot_quote").html()),'sharing','toolbar=0,status=0,width=640,height=405');
		});
		$("#foot_share_fb p").css("display","inline");
		$("#foot_share_fb").stop(false,false).animate({"left":"-190px","width":"190px"},400);
	}, function(){
		$(this).unbind("click");
		$("#foot_share_fb").stop(false,false).animate({"left":"-50px","width":"190px"},300);
	});
	$("#foot_share_tw").hover(function(){
		$(this).click(function(){
			window.open('http://www.twitter.com/share?url=http://thearmed.com&text='+$("#foot_quote").html().replace(/\s/g, "+"),'sharing','toolbar=0,status=0,width=640,height=405');
		});
		$("#foot_share_tw p").css("display","inline");
		$("#foot_share_tw").stop(false,false).animate({"left":"-240px","width":"190px"},400);
	}, function(){
		$(this).unbind("click");
		$("#foot_share_tw").stop(false,false).animate({"left":"-100px","width":"190px"},300);
	});
	$("#foot_share_fb").stop(false,false).animate({"left":"-50px","width":"190px"},280);
	$("#foot_share_tw").stop(false,false).animate({"left":"-100px","width":"190px"},300);
}

function hideShareTabs() {
	$("#foot_share").attr("enabled","false");
	$(".foot_share_copy p").css("display","none");
	$("#foot_share_fb").stop(false,false).animate({"left":"0px","width":"166px"},180);
	$("#foot_share_tw").stop(false,false).animate({"left":"0px","width":"166px"},200);
	$("#foot_share_on").stop(false,true).animate({"clip":"rect(0px 166px 166px 166px)"},200);
}
