$(document).ready(function() { 
    
    // generate popups for global nav items
    $("a[rel=popup], area[rel=popup]").click(function(){
           popupWindow = window.open(this.href,this.title,'menu=no,toolbar=no,width=500,height=600,scrollbars=1,resizable=0,directories=no,location=no,screenX=0,screenY=0,top=48,left=48');
           popupWindow.focus()
           return false;
    })


    $("a[rel=youtube], area[rel=youtube]").click(function(){
           popupWindow = window.open(this.href,this.title,'menu=no,toolbar=no,width=800,height=600,scrollbars=1,resizable=0,directories=no,location=no,screenX=0,screenY=0,top=48,left=48');
           popupWindow.focus()
           return false;
    })

    $("a[rel=external], area[rel=external]").click(function(){
           popupWindow = window.open(this.href,this.title,'toolbar=yes,status=yes,location=yes,menubar=yes,directories=yes,resizable=yes,scrollbars=yes');
           popupWindow.focus()
           return false;
    })
    
    // submit user's flash version with the FAQ form
	var flash = deconcept.SWFObjectUtil.getPlayerVersion();
    $("input#flash").val(flash.major + '.' + flash.minor + '.' + flash.rev);

    
    // Precheck optin
	if (!$("div").hasClass("error")) {
    	$("input[name=primary_opt_in]").attr("checked", "checked");
    }
    
    // highlight password fields if errors are found (since they will auto clear)
    if ($("div").hasClass("error")) {
    	$("#password").addClass("error");
    	$("#confirm_password").addClass("error");
    }
    
    
    
    // TOP NAV
    // Show sub menus on hover
    $("#main_nav ul li").hover(
    	function() {
    		$(this).children("ul").show();
    		$(this).children("a.main").addClass("main_hover");
    		$(this).css("cursor","pointer");
    	},
   		function() {
   			$(this).children("ul").hide();
   			$(this).children("a.main").removeClass("main_hover");
    		$(this).css("cursor","default");
   		}
    );
    // Gets action from attribute on links / Updates nav form / Submits
    $("#main_nav a").click(function() {
    	new_action = $(this).attr("nav_action");
    	$("form#top_nav_form").attr("action",new_action);
    	document.top_nav_form.submit();
    	return false;
    });
    
    
    // POPUPS - ALWAYS MAKE SURE TO REFRESH CID INSIDE A POPUP AS ORIGINAL CID WILL CAUSE FLOW ISSUES
    // Create dim effect, add popup
    $("a.popup_link").click(function() {
    	// Clear existing dimmer/modal divs (just to be safe) and then add them back in
    	$("#modal").remove();
    	$("#dimmer").remove();
    	$("body").prepend('<div id="dimmer"></div>');
    	$("body").prepend('<div id="modal"><a class="close_window"></a><div id="modal_content"></div></div>');
    	
    	// Simulate form post / Fill #modal_content with return
    	if ($(this).attr("link_action")) {
    		link_action = $(this).attr("link_action");
    		var cid = $("form#get_cid input[name=cid]").val();
    		$.post(link_action, { cid: cid }, function(data) {
    			$("#modal #modal_content").html(data);		
    			
				// Forgot Password AJAX Submission
				$("form#forgot_password .submit input").click(function() {
					// Refresh cid / Submit form / Show errors if return == FAIL || Show thanks if return == SUCCESS
					cid = $("form#forgot_password input[name=cid]").val();
					email = $("form#forgot_password input[name=email]").val();
					$.post("my_password", { cid: cid, email: email }, function(response) {
						if (response == "SUCCESS") {
							$("#forgot_password_start").hide("default");
							$("#forgot_password_thanks").show("default");
						} else {
							$("#forgot_password_start p.error").hide("");
							$("#forgot_password_start p.error").show("default");
							$("form#forgot_password #email").addClass("error");
						}
					});
					
					return false;
				});
    		});
    	}
    	
    	// Cleanup on window close
    	$("#modal .close_window").click(function() {
    		$("#modal").remove();
    		$("#dimmer").remove();
    	});
    	
    	return false;
    });
    
    // Offer Popups
    $("a.callout_link").click(function() {
    	// get offer name for dynamic title
    	offer_title = $(this).attr("href");
		offer_title = offer_title.replace('display_page?page=','');
    	// setup for dynamic width/height
    	offer_width = '720';
    	if (offer_title == 'troops_offer') {
    		offer_height = '726';
    	} else {
    		offer_height = '470';
    	}
    	// use Math.random to give popups a unique id so more than one can be open
    	popupWindow = window.open($(this).attr("href"), offer_title, 'width='+offer_width+',height='+offer_height+',toolbar=no,status=no,location=no,menubar=no,directories=no,resizable=no,scrollbars=no');
    	popupWindow.focus();
    	return false;
    });
	$("#offer .close_window").click(function() {
    	window.close();
    });
    
    // Track Offers
    $("a.track_offer").click(function() {
    	current_offer = $(this).attr("offer_name");
    	$.post("offer_printed", { offer: current_offer });
    });
    
    
    // CODE ENTRY
    // Show Receipt field if numeric code
	var receipt_regex = /^\d{14,15}$/;
    $("#code").keyup(function () {
        if ( receipt_regex.test( $(this).val() ) ) {
            $("#receipt_field").show("default");
        }
        else {
            $("#receipt_field").hide("default");
            $("#receipt_field input").val("");
        }
    });
    // Show receipt on error if field has 14 or 15 digits
    if ( receipt_regex.test($("#code").val()) ) {
 	  	$("#receipt_field").show();
    }
    
    
    // Tour Events
    // Zebra striping on tour dates table
    var i = 1;
    $("#tour_dates table tbody tr").each(function() {
    	if (i % 2 == 0) {
    		$(this).addClass("even");
    	}
    	i += 1;
    });
    

	// Commas!
	$(".number").each(function() {
		number = $(this).html();
		number = '' + number;
		number = number.replace(/-/,'');	// bug fix: points spent was reading the hyphen as a character so we are removing all hyphens from the string
		number = number.replace(/\+/,'');	// do the same for plus signs
		if (number.length > 3) {
			var mod = number.length % 3;
			var output = (mod > 0 ? (number.substring(0,mod)) : '');
			for (i=0 ; i < Math.floor(number.length / 3); i++) {
				if ((mod == 0) && (i == 0))
					output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
				else
					output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
				}
			$(this).html(output);
		}
	});
	
	
	// /summer code entry label inside of the input
	magic_input = $("#summer_code_entry_form #code_field input");
	magic_text = "Enter your code here";
	// insert directions on page load
	if (magic_input.val() == "") {
		magic_input.val(magic_text);
	}
	// remove directions on click
	magic_input.click(function() {
		if (magic_input.val() == magic_text) {
			magic_input.val("");
		}
	});
	// re-insert directions on blur
	magic_input.blur(function() {
		if (magic_input.val() == "") {
			magic_input.val(magic_text);
		}
	});
});

function updatePointBalance(new_point_balance) {
	// take number from flash and comify
	// TO DO: Make comifyer a function so that the code is not duplicated
	number = new_point_balance;
	number = '' + number;
	if (number.length > 3) {
		var mod = number.length % 3;
		var output = (mod > 0 ? (number.substring(0,mod)) : '');
		for (i=0 ; i < Math.floor(number.length / 3); i++) {
			if ((mod == 0) && (i == 0))
				output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
			else
				output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
			}
	} else {
		output = number;
	}
	$("#points_num").html(output);
}

function openWindow(link) {
  window.open(link, '_blank', 'width=800,height=600,toolbar=yes,status=yes,location=yes,menubar=yes,directories=yes,resizable=yes,scrollbars=yes');
}

function popup(link) {
	popup = window.open(link,'new_popup','menu=no,toolbar=no,width=500px,height=600,scrollbars=1,resizable=0,directories=no,location=no,screenX=0,screenY=0,top=48,left=48');
	popup.focus();
}

function showFBViral() {
  $('#open_fb_modal').triggerHandler('click');
  $('#facebook_viral').show();
}

function goHome() {
	document.top_nav_home.submit();
}

