var $car;
$(function () {
	$car = $('#carrot');
	popup.init();
	listen_faq();
	facebooklike($('.tellyourfb'));
	if ($('#slideshow').size()){
		slideshow.init();
	}
	$('.sub li').hover(function () {var $this = $(this);
	$this.find('.submenu-hover').show().css({
	left: $this.find('span').width() + 2
	});
	}, function () {
	$(this).find('.submenu-hover').hide();
	});
	 
	var $zipInp = $('#step1 input[name="zip"]');
	var $providerSel = $('select[name="provider"]');
	$zipInp.keyup(function () {
		if($zipInp.val().match(/^[0-9]{5}$/)) {
			$.ajax({
				dataType: 'text',
				url: '/feed/getProviders?q=' + $zipInp.val(),
				success: function (data) {
					data = data.replace('<xml version="1.0" encoding="utf-8">', '');
					data = data.replace('</xml>', '');
					var providers = data.split('<br />');
					providers.splice(providers.length-1, 1);
					
					$providerSel.empty().show().append('<option value="-1">SELECT YOUR PROVIDER</option>');
					
					for(var i = 0; i < providers.length; i++) 
						$providerSel.append('<option value="'+i+'">' + providers[i].substr(0, providers[i].indexOf('~')) + '</option>');
					
					$providerSel.change(function () {
						var $this = $(this);	
						$('.zip .data').html($zipInp.val());
						//$('.provider .data').html($this.val());
						if($this.val()!=-1){
						$('.provider .data').html( providers[$this.val()].substr(0, providers[$this.val()].indexOf('~')));
					}
						//if($this.val() == 'DIRECTV') popup.open(2);
					if($this.val()!=-1){
						if(providers[$this.val()].substr(0, providers[$this.val()].indexOf('~')) == 'DIRECTV') popup.open(2); 
						else{
							$('.perform [name="provider"]').val($this.find('option:selected').text());
							 popup.open(3);
							}
					}
						//console.log($this.val());
					});
				}
			});
		} else {
			$providerSel.hide();
		}
	});
	
	(function () {
		var $window = $(window)
		var $container = $('#container');
		var $logo = $('#logo');
		var $genremenu = $('.menu');
		var $social = $('.social');
		$window.resize(function () {
			realignNav();
		});
		function realignNav(){
			if($container.width() < 1280) {
				var num = (1280-$container.width())/2;
				$logo.css('left', -num);
				$genremenu.css('left', -num + 170);
				$social.css('right', 170 - num);
			} else {
				$logo.css('left', 0);
				$genremenu.css('left', 170);
				$social.css('right', 170);
			}
		}
		realignNav();
	})();
	
	//ipad and iphone fix - checking user agent
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
		
		$('#genre-menu li').bind('click', function (e) {
			var $this = $(this);
			var $menu = $this.closest('.menu');
			$('#genre-menu li').removeClass('current');
			$this.addClass('current');
			$('.menu').addClass('show');
			$('.menu-sublists', $menu).show();
			$('.sublist', $menu).hide();
			$('#sublist' + $this.index(), $menu).show();
			return false;
		});
		
		$("#genre-menu li").bind('touchend', function(){
			var $this = $(this);
			var $menu = $this.closest('.menu');
			$('#genre-menu li').removeClass('current');
			$this.addClass('current');
			$('.menu').addClass('show');
			$('.menu-sublists', $menu).show();
			$('.sublist', $menu).hide();
			$('#sublist' + $this.index(), $menu).show();
			return false;
		});
		
		// If you want to do something on touchend
		// $("#genre-menu li").bind('touchend', function(){
		// 		alert("Touch ended!");
		// });
		
	} else {
		
		$('#genre-menu li').bind('click', function (e) {
			var $this = $(this);
			var $menu = $this.closest('.menu');
			$('#genre-menu li').removeClass('current');
			$this.addClass('current');
			$('.menu').addClass('show');
			$('.menu-sublists', $menu).show();
			$('.sublist', $menu).hide();
			$('#sublist' + $this.index(), $menu).show();
			return false;
		});
		
	}
	
	$('.menuclose').bind('click', function () {
		$('.menu').removeClass('show');
		$('.menu-sublists').hide();
		$('#genre-menu li').removeClass('current');
		return false;
	});
	
	
	
	
	
	
	
	
	
	$('.sub').hover(function () {
		var $this = $(this);
		$this.find('.submenu-hover').show();
	}, function () {
		$(this).find('.submenu-hover').hide();
	});
	
	$('.row .more_info').live('mouseenter mouseleave', function (e) {
		var $this = $(this);
		var id = $this.attr('data-id');
		var $hover = $('#hover-'+id);
		if(e.type == 'mouseenter') {
			$('.submenu-hover').hide();
			$hover.show().css({
				left: $this.offset().left + $this.width() +26,
				top: $this.offset().top -20
			});
		} else {
			var t = 
			setTimeout(function () {
				$hover.hide();
			}, 250);
			$hover.hover(function () { clearTimeout(t); }, function () { $hover.hide(); });
		}
	});
	
	//$("[rel^='prettyPhoto[gallery1]', ]").prettyPhoto({
	$("[rel='prettyPhoto[gallery1]'], [rel='prettyPhoto[gallery4]']").prettyPhoto({
		horizontal_padding: 0,
		overlay_gallery: false,
		markup: '<div class="pp_pic_holder"> \
						<div class="pp_top"> \
							<div class="pp_left"></div> \
							<div class="pp_middle"></div> \
							<div class="pp_right"></div> \
						</div> \
						<div class="pp_content_container"> \
							<a class="pp_close" href="#">Close</a> \
							<div class="pp_left"> \
							<div class="pp_right"> \
								<div class="pp_content"> \
									<div class="pp_loaderIcon"></div> \
									<div class="pp_fade"> \
										<div class="pp_hoverContainer"> \
											<a class="pp_next" href="#">next</a> \
											<a class="pp_previous" href="#">previous</a> \
										</div> \
										<div id="pp_full_res"></div> \
										<div class="pp_details"> \
											<div class="top"> \
												<div class="ppt">&nbsp;</div> \
												<p class="pp_description"></p> \
											</div> \
											<div class="bottom"> \
												<div class="p_social"> \
													<div class="facebook"><a class="tellyourfb"><img width=50 height=24 src="/img/global/fblike.png"/></a></div><script type="text/javascript">facebooklike($(".tellyourfb"));</script> \
													<div class="twitter"><a href="https://twitter.com/share?text=Check%20this%20out%20from%203net%2C%20the%203D%20TV%20channel%20from%20Discovery%2C%20Sony%20and%20IMAX!&url=http%3A%2F%2F3net.com%2F" class="twitter-share-button" data-count="none">Tweet</a></div><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> \
													<div class="share"><span st_title="' + document.title + '" class="st_sharethis" displayText="ShareThis"></span><script language="javascript" type="text/javascript">stButtons.locateElements() </script></div> \
												</div> \
												<div class="clear"></div> \
											</div> \
										</div> \
									</div> \
								</div> \
							</div> \
							</div> \
						</div> \
						<div class="pp_bottom"> \
							<div class="pp_left"></div> \
							<div class="pp_middle"></div> \
							<div class="pp_right"></div> \
						</div> \
					</div> \
					<div class="pp_overlay"></div>'
	});
	
	$("[rel='prettyPhoto[gallery2]'], [rel='prettyPhoto[gallery3]']").prettyPhoto({
		horizontal_padding: 0,
		overlay_gallery: false,
		markup: '<div class="pp_pic_holder"> \
						<div class="pp_top"> \
							<div class="pp_left"></div> \
							<div class="pp_middle"></div> \
							<div class="pp_right"></div> \
						</div> \
						<div class="pp_content_container"> \
							<a class="pp_close" href="#">Close</a> \
							<div class="pp_left"> \
							<div class="pp_right"> \
								<div class="pp_content"> \
									<div class="pp_loaderIcon"></div> \
									<div class="pp_fade"> \
										<div class="pp_hoverContainer"> \
											<a class="pp_next" href="#">next</a> \
											<a class="pp_previous" href="#">previous</a> \
										</div> \
										<div id="pp_full_res"></div> \
										<div class="pp_details"> \
											<div class="top"> \
												<div class="ppt">&nbsp;</div> \
												<p class="pp_description"></p> \
											</div> \
											<div class="bottom"> \
												<div class="p_social"> \
													<div class="facebook"><a class="tellyourfb"><img width=50 height=24 src="/img/global/fblike.png"/></a></div><script type="text/javascript">facebooklike($(".tellyourfb"));</script> \
													<div class="twitter"><a href="https://twitter.com/share?text=Check%20this%20out%20from%203net%2C%20the%203D%20TV%20channel%20from%20Discovery%2C%20Sony%20and%20IMAX!&url=http%3A%2F%2F3net.com%2F" class="twitter-share-button" data-count="none">Tweet</a></div><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> \
												</div> \
												<div class="clear"></div> \
											</div> \
										</div> \
									</div> \
								</div> \
							</div> \
							</div> \
						</div> \
						<div class="pp_bottom"> \
							<div class="pp_left"></div> \
							<div class="pp_middle"></div> \
							<div class="pp_right"></div> \
						</div> \
					</div> \
					<div class="pp_overlay"></div>'
	});
	
	$("#slideshow a, #featured a").attr("tabindex", "-1");
	$('.st_sharethis').attr('st_title', document.title);
	
	$('.pp_next').live('mouseenter mouseleave', function (e) {
		if(e.type == 'mouseenter')
			$(this).css('background-image', 'url(/img/global/slidearrowright.png)');
		else
			$(this).css('background-image', '');
	});
	
	$('.pp_previous').live('mouseenter mouseleave', function (e) {
		if(e.type == 'mouseenter')
			$(this).css('background-image', 'url(/img/global/slidearrowleft.png)');
		else
			$(this).css('background-image', '');
	});
});


var facebooklike = function(button){
	var that = {};
	function init(){
		button.bind('click',function(){
			onButtonPress();
			return false;
		})
	}
	function onButtonPress(){
			var staticLoc = "http://" + document.domain + '/img/global/iPhoneFBShareImage.jpg';
			FB.ui({
				method: 'stream.publish',
				message: "",
				attachment: {
					name: window.location.href,
					media: [
					    {
					    "type": "image",
					    "src": staticLoc,
					    "href": window.location.href
					}],
					description: (
						'Check this out from 3net, the 3D Channel from Discovery, Sony and IMAX! Visit the site to see more of the best in 3D entertainment.'
					),
					href: window.location.href
				},
				
				user_prompt_message: 'Personal message here'
			}, function(response) {
				if (response && response.post_id) {
					//alert('Post was published.');
				} else {
					//alert('Post was not published.');
				}
			}
			)
	}
	init();
	
	return that;
}

function listen_faq(){
	$(".faq_drop_container a.question").click(function(){
		$(this).toggleClass("open");
		$(this).next().toggle("slow");
		return false;
	});
}

function submitToPro(){
		var error = false;
		var age = 0;
		error = checkForErrors();
		
		var $this = $("#submittopro");
		$("#submittopro .required").blur(function(){
			error = checkForErrors();
		});
		var $email = $this.find('[name="email"]');
		var $fname = $this.find('[name="firstname"]');
		var $lname = $this.find('[name="lastname"]');
		var $allow = $this.find('[name="allow"]');
		var $address = $this.find('[name="address"]');
		var $city = $this.find('[name="city"]');
		var $state = $this.find('[name="state"]');
		var $state = $this.find('[name="zip"]');
		var $birthMonth = $this.find('[name="month"]');
		var $birthDay = $this.find('[name="day"]');
		var $birthYear = $this.find('[name="year"]');
		var $provider = $("#step1").find('[name="provider"]');
		var bmth = 0;
		var bdy = 0;
		var byr = 0;
		
		
		if(!error) {
			if($birthMonth.val() == 'MM' || $birthMonth.val() == "" ){
				error = true;
				$birthYear.next().html('Please provide your birthdate.');
				$birthMonth.closest('.input').addClass('error');
			} else {
				bmth = parseInt($birthMonth.val(),10)-1;   // radix 10
				if (bmth <0 || bmth >11) {  // check valid month 0-11
					error = true;
					$birthYear.next().html('Please provide a valid birthdate.');
					$birthMonth.closest('.input').addClass('error');
				}
			}
			if($birthDay.val() == 'DD' || $birthMonth.val() == ""){
				error = true;
				$birthYear.next().html('Please provide your birthdate.');
				$birthDay.closest('.input').addClass('error');
			} else {
				bdy = parseInt($birthDay.val(),10);   // radix 10!
				var dim = 31;
				if (bdy <1 || bdy > dim) {  // check valid date according to month
						error = true;
						$birthYear.next().html('Please provide a valid birthdate.');
						$birthMonth.closest('.input').addClass('error');
				}
	
			}	
			var nowyear = 0;
			var todayxy = new Date();
			if($birthYear.val() == 'YYYY' || $birthMonth.val() == ""){
				error = true;
				$birthYear.next().html('Please provide your birthdate.');
				$birthDay.closest('.input').addClass('error');
			} else {
				byr = parseInt($birthYear.val()); 
				nowyear = todayxy.getFullYear();
				if (byr >= nowyear || byr < 1900) {  // check valid year
						error = true;
						$birthYear.next().html('Please provide a valid birthdate.');
						$birthMonth.closest('.input').addClass('error');
				}
	
			}
		
			//age check
			
			age = nowyear - byr;
			
			var nowmonth = todayxy.getMonth();
			var nowday = todayxy.getDate();
			if (bmth > nowmonth) {
				age = age - 1// next birthday not yet reached
				}  else if (bmth == nowmonth && nowday < bdy) {
					age = age - 1;
					}
	
		
			 if (age <= 12 && age !=0) {
			 	alert ("We are unable to process your request at this time.");  
				$provider.val("-1").attr("selected", true);
			 	error=true;
				popup.close();
			 	} else{
				//ajax here
				
				if($allow.is(':checked'))
					$allow.val('true');
				else
					$allow.val('false');
				
				dummyAjaxFunction($this.serialize());
				popup.open(5);
			}
				
		} else {
		
		}
		return false;
		
	}
	
//dummyAjaxFunction('firstname=Patrick&lastname=Miller&month=06&day=24&year=1991&email=pmiller624%40gmail.com&address=5665+Versailles+Ave.&city=Ann+Arbor&state=MI&zip=48103&allow=');

function dummyAjaxFunction(data){
	$.ajax({
		url: '/feed/email',
		type: 'post',
		data: data
	});
	//keep this:
	var $provider = $("#step1").find('[name="provider"]');
	$provider.val("-1").attr("selected", true);
}	

function checkForErrors(){
	var $this = $("#submittopro");
	var error = false;
	var $email = $this.find('[name="email"]');
	var $name = $this.find('[name="name"]');
	var $address = $this.find('[name="address"]');
	var $city = $this.find('[name="city"]');
	var $state = $this.find('[name="state"]');
	var $birthMonth = $this.find('[name="month"]');
	var $birthDay = $this.find('[name="day"]');
	var $birthYear = $this.find('[name="year"]');
	var $lname = $this.find('[name="lastname"]');
	var $fname = $this.find('[name="firstname"]');
	var $birthMonth = $this.find('[name="month"]');
	var $birthDay = $this.find('[name="day"]');
	var $birthYear = $this.find('[name="year"]');
	var $zip = $this.find('[name="zip"]');
	var bmth = 0;
	var bdy = 0;
	var byr = 0;
	
	$this.find('.errormsg').empty();
	$this.find('.input').removeClass('success').removeClass('error');
	
	if($email.val() == 'EMAIL' || $email.val() == '' || $email.val().indexOf('@')  == -1 || $email.val().indexOf('.')  == -1) {
		error = true;
		$email.next().html('Please provide a valid email address.');
		$email.closest('.input').addClass('error');
	} else {
		$email.closest('.input').addClass('success');
	}
	
	if($fname.val() == 'FIRST NAME' || $fname.val() == '' || $lname.val() == 'LAST NAME' || $lname.val() == '') {
		error = true;
		$lname.next().html('Please provide your name.');
		$lname.closest('.input').addClass('error');
	} else {
		$lname.closest('.input').addClass('success');
	}
	
	if($address.val() == 'ADDRESS' || $address.val() == '') {
		error = true;
		$address.next().html('Please provide your street address.');
		$address.closest('.input').addClass('error');
	} else {
		$address.closest('.input').addClass('success');
	}
	
	if($birthMonth.val() == 'MM' || $birthMonth.val() == '' || $birthMonth.val() == 'DD' || $birthDay.val() == '' || $birthYear.val() == 'YYYY' || $birthYear.val() == '') {
		error = true;
		$birthYear.next().html('Please provide birthday.');
		$birthYear.closest('.input').addClass('error');
	} else {
		$birthMonth.closest('.input').addClass('success');
	}
	
	if($city.val() == 'CITY' || $city.val() == '') {
		error = true;
		$city.next().html('Please provide your city.');
		$city.closest('.input').addClass('error');
	} else {
		$city.closest('.input').addClass('success');
	}
	
	if($state.val() == 0 || $zip.val() == 'ZIP' || $zip.val() == '' || !$zip.val().match(/^[0-9]{5}$/)) {
		error = true;
		$zip.next().html('Please enter your state and zip.');
		$zip.closest('.input').addClass('error');
	} else {
		$zip.closest('.input').addClass('success');
	}
	return error;
}


function showFooterPopUp(id){
	$('[data-popup]').hide();
	$(".fixed_footer_popup_container").add($car).show();
	$(".fixed_footer_popup_container").css('bottom', (parseInt($('.menu').attr('data-height'), 10) + 144) + 'px');
	if(id == -1) {
		$('#genre-menu li:first a').click();
		$car.css('left', $('.showst').offset().left - $('.fixed_footer_popup_container .menu').offset().left + 25);
	} else {
		$('#genre-menu li[data-id="'+id+'"] a').click();
		$car.css('left', $('.catet').offset().left - $('.fixed_footer_popup_container .menu').offset().left + 25);
	}
	$('.menuclose').click(function () { $(".fixed_footer_popup_container").add($('#carrot')).hide(); });
}
