$(function(){
	positionFooter();
  usedAjax();

	//Start the timer
	if(typeof endDate !== 'undefined') {
		$('#timeleft .timer').countdown({
			until: endDate,
			format: 'HMS',
			layout: '{hn}hrs {mn}mins {sn}secs',
			alwaysExpire: true,
			onExpiry: function(){
				$('#timeleft .timer').countdown('destroy').text('This Bundle is no longer available').addClass('expired');
			}
		});//.after('<br />' + endDate.toString());
	}
	
	$("#signup").validate({
		rules: {
			pwd: "required",
			cpwd: {
				equalTo: "#pwd"
			}
		},
		messages : {
			cpwd : {
				equalTo : "This field must match the first password entered."
			}
		}
	});
	$("#account").validate({
		rules: {
			pwd: "required",
			cpwd: {
				equalTo: "#npwd"
			}
		},
		messages : {
			cpwd : {
				equalTo : "This field must match the first password entered."
			}
		}
	});
	$("#signin, #forgot_pass, #contact").validate();
	
	//Checkout page, update quantity
	$('#purchase_bundle #btn_quantity_update').click(update_checkout_qty);
	
	$("#purchase_bundle #Month, #purchase_bundle #Year, .certificate_name").addClass('required');
	$("#purchase_bundle").validate({
		submitHandler: function(form) {
			$('image, submit', form).attr('disabled', true);
			form.submit();
 		}
	});
		
	//Checkout page, disable enter button on form fields
	$("#purchase_bundle").keypress(function(e) {
		if (e.which == 13) {
			update_checkout_qty();
			return false;
		}
	});
	$("#purchase_bundle #quantity").keypress(function(e){
		$('.payment-div').slideUp('fast', function(){
			$('.payment-div').empty();
		});
	});
	
	$(".dailymail").focusClear();
		
	//Fix for div height on main page:
	var minHeight = 500;
	$('#slider img').each(function(i, element) {
		if(minHeight > $(element).height()) minHeight = $(element).height();
	});
	
	$('#slider').nivoSlider({pauseTime:5000}).height(minHeight);
});

$(window).load(function(){
	//look for the cookie
	var dismissedEmailBox = $.cookie('dismissed_email');
	var pop_bypass = getUrlVars()["pop_bypass"];
	
	if(dismissedEmailBox != 'true' && window.location.protocol != 'https:' && !$('body').hasClass('logged-in') && pop_bypass != 1)
	{
		$.fancybox(
			'body',
			{
	        	'type'				: 'iframe',
				'href'				: '/subscribe/landing.php',
				'autoDimensions'	: false,
				'width'         	: 595,
				'height'        	: 440,
				'scrolling'			: 'no',
				'showCloseButton'	: true,
				'onClosed'			: closedEmailBox
			}
		);
	}	
});

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function update_checkout_qty() {
	//Get the value of the total box.
	var qty = $("#purchase_bundle #quantity").val();
	
	//Redirect the browser to the correct place:
	window.location.search = "?quantity=" + qty;
}

function positionFooter(){
	if($(document.body).height() < $(window).height()) {
		$("#footer").css({'marginTop':($(window).scrollTop()+$(window).height()-$("#footer").height()-$("#wrapper").height())+"px"})
	}	
}

// flag to indicate that ajax is currently running
var usedAjaxRunning = false;

// handle the ajax around marking a bundle used or unused
function usedAjax(){
  $('.mark').click(function(){
    var order_number = $(this).attr('data-id');
    var direction = $(this).attr('data-direction');
    var section = $(this).attr('data-section');
    var number = $(this).attr('data-number');
    
    // variablize what you clicked for context in the ajax function
    var that = $(this);
    
    // get all the bundles
    var bundles = $(this).parents('td').find('.bundle');
    
    // get the number of bundles in this deal
    var num_bundles = bundles.length;
    
    // get the number of active bundles in this deal
    var active_bundles = 0;
    
    // for each bundle
    bundles.each(function(){
      // if it's not hidden
      if ($(this).css('display') != 'none') {
        // increment active_bundle count
        active_bundles += 1;
      }
    });
    
    if (usedAjaxRunning == false) {
      usedAjaxRunning = true;
      
      // run the ajax
      $.ajax({
        url: '/dev/inc/makeused.php?order_number=' + order_number + '&direction=' + direction + '&number=' + number,
        success: function(data){
          if (data == '1') {
            // what do we do after the ajax returns?
            if (section == 'available' || section == 'used') {
              // if we're marking the last bundle used (in available), or marking the first bundle unused (in used), vanish the row
              if (active_bundles == 1) {
                // get the tr and the next tr (which is a separator)
                var tr = that.parents('tr');
                var next = tr.next();

                if ($.browser.msie) {
                  tr.find('td').fadeOut();
                  next.find('td').fadeOut();
                } else {
                  tr.fadeOut();
                  next.fadeOut();
                }
              // if we're marking one used, but it's not last, just fade out that bundle
              } else {
                that.parents('.bundle').fadeOut();
              }
            } else if (section == 'all' || section == 'expired') {
              // in the all or expired sections, we just change the link
              if (direction == 'unused'){
                that.html('Mark As Used').attr('data-direction', 'used');
                that.parents('td').find('.bundle[data-number=' + number + ']').removeClass('usedBundle')
              } else {
                that.html('Mark As Unused').attr('data-direction', 'unused');
                that.parents('td').find('.bundle[data-number=' + number + ']').addClass('usedBundle');
              }
            }
          } else {
            // alert('There was an error marking that bundle. Please refresh and try again.');
          }
          
          // unset the flag now that we're done
          usedAjaxRunning = false;
        }
      });
    }
    
    return false;
  });
}

function fb_loggedin() {
	if(typeof redirect == "undefined")
		window.location.href = 'http://www.inbundles.com/';
	else	
		window.location.href = 'http://www.inbundles.com/' + redirect + '/';
}

function fb_logout() {
 FB.getLoginStatus(function(response) {
  if (response.authResponse) {
    FB.logout(function(response) {
      window.location.href = 'http://www.inbundles.com/user/signout/?lgout=1';
    });
  } else {
  	window.location.href = 'http://www.inbundles.com/user/signout/?lgout=1';
  }
 });
 return false;
}

//Search box clear
$.fn.focusClear = function(){
    return this.focus(function(){
        if (this.value == this.defaultValue) {
            this.value = "";
        }
    }).blur(function(){
        if (!this.value.length) {
            this.value = this.defaultValue;
        }
    });
};

function closedEmailBox()
{
	//set a cookie so that it doesn't show up again.
	$.cookie('dismissed_email', 'true', {
		expires: 180,
		path: '/', 
		domain: 'inbundles.com'
	});	
}

