var config = {"base_path":""}
var currentPanel = 0;
var currentTimer;
var breakingDelayedTimer;
var navigationTimer;
var navigationOutTimer;
var overnavdelay=250;
var cardOverlayDelay = 400;
var cardOverlayTimer;
var cardOverlayOutTimer;
var currentSendCat;
var expandedCards = new Array();
var stars = new Array();
var loginVote = false;
var cardOverlayHit = false;
var cardThumbHit = false;
var cardOverlayViewCount = 0;
var cacheFriendList = null;
var navOpen = false;
var autorefresh = null;
var fbc = {};


//Global Functions
function addHandler(obj, evnt, handler) {
    if (obj.addEventListener) {
        obj.addEventListener(evnt.replace(/^on/, ''), handler, false);
    // Note: attachEvent fires handlers in the reverse order they
    // were attached. This is the opposite of what addEventListener
    // and manual attachment do.
    //} else if (obj.attachEvent) {
    //    obj.attachEvent(evnt, handler);
    } else {
        if (obj[evnt]) {
            var origHandler = obj[evnt];
            obj[evnt] = function(evt) {
                origHandler(evt);
                handler(evt);
            }
        } else {
            obj[evnt] = function(evt) {
                handler(evt);
            }
        }
    }
}

function validateEmail(e){
    /*
    var pattern = new RegExp(/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/);
    return pattern.test(e);
    */
    return (e.search(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i) != -1);
}
function subscribe(email) {
	$.get(config.base_path + "/user/subscribe", {'email': email}, function(r){
            $("div.link-button .ajax").hide();
            $("#popup").jqmHide();
			if (r.status=="OK"){
				showMessage("You're really close. To complete your subscription, click on the activation link in the email you've been sent.","Newsletter Subscribe");
			} else {
				showMessage(r.error,"Newsletter Subscribe");
			}
		},
		'json'
	);
}
function unsubscribe(email) {
    $.get(config.base_path + "/user/subscribe", {'email': email, 'op': 'unsubscribe'}, function(r){
		var popup = $("#popup");
		if (r.status=="OK"){
			if($("body").hasClass("staticunsubscribe")){
               showMessage("You have successfully and unfortunately unsubscribed. We will not take this personally.", "Unsubscribe Confirmation.");
			} else {
				popup.removeClass().addClass("message");
				$(".content",popup).html('<div class="message">You have successfully and unfortunately unsubscribed. We will not take this personally.</div>')
				$("div.link-button a.unsubscribe",popup).hide();
				$("div.link-button a.button",popup).html("Close").addClass("close").unbind("click").click(function(){
					popup.jqmHide();
				});							
			}
		} else {
			if($("body").hasClass("staticunsubscribe")){
				showMessage("Error: " + r.error, "Alert");
			} else {
				popup.removeClass().addClass("message");
				$(".content",popup).html('<div class="message">Error: ' + r.error + '</div>')
				$("div.link-button a.unsubscribe",popup).hide();
				$("div.link-button a.button",popup).html("Close").addClass("close").unbind("click").click(function(){
					popup.jqmHide();
				});
			}
		}
		$("div.link-button .ajax").hide();
	}, 'json');

}

function staticunsubscribe(email) {
    $.get(config.base_path + "/user/subscribe", {'email': email, 'op': 'unsubscribe'}, function(r){
		var popup = $("#popup");
		if (r.status=="OK"){
            $("#uns_status").attr('value', 'OK');
            $("#uns_redirect_form").submit();
		} else {
            $("#uns_status").attr('value', r.status);
            $("#uns_error").attr('value', r.error);
            $("#uns_redirect_form").submit();
		}
	}, 'json');

}

function subscribeUser(user_id) {
					$.get(config.base_path + "/user/subscribe", {'op': 'subscribe-user'}, function(r){
                        var popup = $("#popup");
						if (r.status=="OK"){
                            showMessage("You have been subscribed", "Alert");
						} else {
                            showMessage("Unable to subscribe", "Alert");
						}
						$("div.link-button .ajax").hide();
                        }, 'json');
                    return false;
}

function unsubscribeUser(user_id) {
					$.get(config.base_path + "/user/subscribe", {'op': 'unsubscribe'}, function(r){
                        var popup = $("#popup");
						if (r.status=="OK"){
                            showMessage("You have been unsubscribed", "Alert");
						} else {
                            showMessage("Unable to unsubscribed", "Alert");
						}
						$("div.link-button .ajax").hide();
                        }, 'json');
                    return false;
}

function postConfirm_newsletterPopup(email){

    var popup = $("#popup");
    popup.css("position","absolute");
    if($.browser.msie) popup.css("top",document.documentElement.scrollTop+150);
    else popup.css("top",window.pageYOffset+150);

    $(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>")
    popup.removeClass().addClass("postconfirm_newsletter");
    $("h3",popup).html('Newsletter Signup');
    $(".link-button .need-account",popup).hide();

    $("div.link-button a.unsubscribe",popup).removeAttr("onclick");
    $("div.link-button a.unsubscribe",popup).html("Cancel").unbind("click").click(function(){
        $("#popup").jqmHide();
        return false;
    }).show();

    $(".content",popup).load("/static/popup-postconfirm-newsletter.php", {e:email}, function(){
         $(".link-button .button",popup).html("Sign Up &raquo;").unbind("click").click(function(){
            var e = $("#postconfirm-newsletter-email").val();
            $.get(config.base_path + "/user/subscribe", {'email': e}, function(r){
                $("div.link-button .ajax").hide();
                    if (r.status=="OK"){
                        $("div.link-button a.unsubscribe",popup).hide();
                        $("#postconfirm-newsletter-email", popup).hide();
                        $(".quote", popup).hide();
                        $(".descrip", popup).html("Thanks. An activation link has been sent to <i>"+e+"</i>");
                        $(".error", popup).hide();
                         $(".link-button .button",popup).html("Close").unbind("click").click(function(){
                           $("#popup").jqmHide();
                         });
                    } else {
                        $(".error", popup).html(r.error).show();
                    }
            }, 'json');
            return false;
        });
    });
    $(".close",popup).unbind("click").click(function(){
        $("#popup").jqmHide();
    });
    popup.jqmShow();
    return false;

}

var g_callback;
var g_logoutfirst;

function loginPopShowSpinner(){
    $('.fbconnect_holder .ajax').show();
    $(window).blur(function(){
        $('.fbconnect_holder .ajax').hide();
    });
}

function loadLoginPopup(callback, email, logoutfirst, top_msg){
        g_callback = callback;
        g_logoutfirst = logoutfirst;

        var popup = $("#popup");
        popup.css("position","absolute");
        if($.browser.msie) popup.css("top",document.documentElement.scrollTop+150);
        else popup.css("top",window.pageYOffset+150);

        $(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>")
        popup.removeClass().addClass("login");
        $("h3",popup).html("Log In");
        $("div.link-button a.unsubscribe",popup).hide();
        
        //$(".link-button .button",popup).show();
        $(".link-button .need-account",popup).click(function(){
            $("#global-nav .popup-register").click()
                    return false;
        });
        var qs = new Array();
        if(logoutfirst) qs.push("lf=1");
        if(top_msg) qs.push("show_anonsend_message="+escape(top_msg));
        
        if(Boolean(typeof email!='undefined' && email) &&
           Boolean(typeof email!='undefined' && email) ){
            qs.push("defemail="+email);
        }
        $(".content",popup).load("/static/popup-login.php?"+qs.join("&"), null, function(){
            $("#popup-login-submit-button .button",popup).html("Log In &raquo;").unbind("click").click(function(){
                    submitPopup("login", callback, logoutfirst);
                    return false;
            });
            $("#popup .fields .secloginfields input").keydown(function(e){
                if(e.keyCode == 13) $("#popup-login-submit-button .button",popup).click();
            });

        });

        $(".close",popup).click(function(){$("#popup").jqmHide();});

        popup.jqmShow();
        return false;
}

function toggleBirthdayTooltip(){
    return;
    var bday_notif = $.cookies.get('bday_notif', true);
    if(!(bday_notif)){
        var expire=new Date();
        expire.setDate(expire.getDate()+365);
        $("#global-nav .bday_tooltip").click(function(e){
            e.preventDefault();
            $.cookies.set('bday_notif', 'true', { path: '/', expiresAt: expire });
            location.href="/user/birthdays";
        }).fadeIn(400);
        $("#global-nav .bday_tooltip .close").click(function(e){
            e.preventDefault();
            $.cookies.set('bday_notif', 'true', { path: '/', expiresAt: expire });
            $("#global-nav .bday_tooltip").fadeOut(400);
            return false;
        });
    }
}

function initLoginStatus(){
    var param = { 'cur':escape(window.location) };
    var remkey = $.cookies.get('remember_key', false);
    if(remkey) param['remkey'] = remkey;
    $.get("/user/fls", param, function(data){
        if(data.logged){
            var up = $.cookies.get('usrprof', true);
            if(up){
                $("#global-nav ul.options li.logged-in-row .name").html(up.s);
            }
            $("#global-nav ul.options li.lgdout").remove();
            $("#global-nav ul.options li.lgdin").show();

            var expire=new Date();
            expire.setDate(expire.getDate()+90);
            if(remkey && data.rem_key) $.cookies.set('remember_key', data.rem_key, { path:'/', expiresAt:expire });
        }
        else {
            if(remkey) $.cookies.del('remember_key', {path:'/'});
        }

        if(data.fb.connected){
            if(data.fb.perm_bday>0){
                $("#global-nav ul.fb_bday").css('margin-top', '4px');
                if(data.fb.global_bdays!=null){
                    $("#global-nav ul.fb_bday .bdays").html(data.fb.global_bdays);
                    $("#global-nav ul.fb_bday li.label").show().parent().show();
                }
                else if(!data.bdays_enabled){
                    $("#global-nav ul.fb_bday li.label").append(' <a href="/user/birthdays" class="reenable">Enable &raquo;</a>').show().parent().show();
                    $("#global-nav ul.fb_bday li.label .reenable").unbind("click").click(function(e){
                        e.stopPropagation();
                        $.get('/user/aj_birthdays?a=enable', null, function(data){
                            if(data.status=="OK") location.href='/user/birthdays';
                        }, 'json');
                    });
                }
            }
            else {
                    $("#global-nav ul.fb_bday li.icon").css('margin-top', '6px');
                    $("#global-nav ul.fb_bday li.label_get a").unbind("click").click(function(e){
                        e.stopPropagation();
                        showBirthdayPerm(function(){
                            $.get('/user/aj_birthdays?a=up_perm', null, function(){
                                location.href="/user/birthdays";
                            });
                        });
                        return false;
                    });
                    $("#global-nav ul.fb_bday li.label_get").show().parent().show();
                    toggleBirthdayTooltip();
            }
            fbc.uid = data.fb.id;
            fbc.connected = true;
        }
        else {
            fbc.connected = false;
            $("#global-nav ul.fb_bday li.icon").css('margin-top', '6px');
                $("#global-nav ul.fb_bday li.label_get a").unbind("click").click(function(e){
                    e.stopPropagation();
                    onFBLoginPress(function(){
                        reloadPage();
                    });
                    return false;
                });
            $("#global-nav ul.fb_bday li.label_get").show().parent().show();
            toggleBirthdayTooltip();
        }

        return false;
    }, 'json');
    return false;
}

function initGlobalNav(){
	$("#popup").jqm(); //.keydown(function(e){ if(e.keyCode==13) $(this).find("div.link-button a.button").click(); }).jqm();
	$("#popup .close").click(function(){$("#popup").jqmHide();});
	$("#global-nav .popup-login").click(function(e){
            e.preventDefault();
            if($("body").hasClass("invites") || $.find("#invites_div").length>0){
                if(Boolean(typeof guest_email!='undefined' && guest_email)){
                    var up = $.cookies.get('usrprof', true);
                    var curEm = up.e.toLowerCase();
                    var invEm = guest_email.toLowerCase();
                    if(curEm==invEm) reloadPage();
                    else openLogoutPopup(invEm, curEm);
                }
                else loadLoginPopup(function(){
                    reloadPage();
                });
            }
            else {
                loadLoginPopup(function(){
                    reloadPage();
                });
            }
        });
        $("#global-nav .global-logout").unbind('click').click(function(e){
            e.preventDefault();
            $.get(config.base_path + "/user/ajlogout",null,function(data){
                $.cookies.del('usrprof', {path:'/'});
                var user_body_classes = new Array("inbox", "createcards", "sentcards", "favorited", "profile-invited", "profile-invites");
                var is_profilepage = false;
                for(var i in user_body_classes){
                    if($("body").hasClass(user_body_classes[i])){
                        is_profilepage = true;break;
                    }
                }
                if(data.logout=="FACEBOOK"){
                    FB.logout(function(response){
                        if(is_profilepage){location.href='/';return false;}
                        else reloadPage();
                    });
                }
                else {
                    if(is_profilepage){location.href='/';return false;}
                    else reloadPage();
                }
            },"json");
            return false;
        });
	$("#global-nav .popup-newsletter").click(function(e){
                e.preventDefault();
		var popup = $("#popup");
		if($.browser.msie){
			popup.css("top",document.documentElement.scrollTop+150);
		} else {
			popup.css("top",window.pageYOffset+150);
		}

		$(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>")
		popup.removeClass().addClass("newsletter");
		$("h3", popup).html("Newsletter Subscribe");
		$("div.link-button a.unsubscribe",popup).css("display","block");
		$(".link-button .button",popup).html("Submit &raquo;").unbind("click").click(function(){
			submitPopup("newsletter");
			return false;
		});
                $(".link-button .button",popup).show();
		$(".content",popup).load("/static/popup-newsletter.php");
		
		$("div.content div.fields input",popup).keydown(function(e){
			if(e.keyCode == 13) $("#popup .link-button .button").click();
		});
		$(".close",popup).click(function(){$("#popup").jqmHide();});
		
		popup.jqmShow();
	});
	$("#global-nav .popup-register").click(function(e){
            e.preventDefault();
		var popup = $("#popup");
		if($.browser.msie){
			popup.css("top",150);
		} else {
			popup.css("top",150);
		}
		
		if(!popup.hasClass("register")){
			$(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>")
			popup.removeClass().addClass("register");
			$("h3",popup).html("Register. It's Free and Relatively Easy!");
			$("div.link-button a.unsubscribe",popup).hide();
			$(".link-button .button",popup).html("Register &raquo;").unbind("click").click(function(e){
                                e.preventDefault();
				submitPopup("register");
				return false;
			});
                        $(".link-button .button",popup).show();
			$(".content",popup).load("/static/popup-register.php",function(){
				$("#popup.register input").focus(function(){
					if($(this).hasClass("register-error")){
						if($(this)[0].id=="popup-register-username"){
							$(this).val("").removeClass("register-error").next().removeClass("error").html("User Name is public");
						} else {
							$(this).val("").removeClass("register-error").next().hide();
						}
						$(this).prev().removeClass("label-error");
					}
				})
			});
		}

		$("div.content div.fields input",popup).keydown(function(e){
			if(e.keyCode == 13) $("#popup .link-button .button").click();
		});	
		$(".close",popup).click(function(){$("#popup").jqmHide();});
			
		popup.jqmShow();
	});
	$("#global-nav .popup-forgot").click(function(e){
            e.preventDefault();
		var popup = $("#popup");
		if($.browser.msie){
			popup.css("top",document.documentElement.scrollTop+150);
		} else {
			popup.css("top",window.pageYOffset+150);
		}
		
		if(!popup.hasClass("forgot")){
			$(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>")
			popup.removeClass().addClass("forgot");
			$("div.link-button a.unsubscribe",popup).hide();
			$("h3",popup).html("Password recovery tool");			
                        $(".link-button .button",popup).html("Recover &raquo;").unbind("click").click(function(){
				submitPopup("forgot");
				return false;
			});
                        $(".link-button .button",popup).show();
			$(".content",popup).load("/static/popup-forgot.php",function(){
				$("#popup.forgot input").focus(function(){
					if($(this).hasClass("register-error")){
						$(this).val("").removeClass("forgot-error").next().remove();
						$(this).prev().removeClass("label-error");
					}
				})
			});
		}

		$(".close",popup).click(function(){$("#popup").jqmHide();});
		
		$("div.content div.fields input",popup).keydown(function(e){
			if(e.keyCode == 13) $("#popup .link-button .button").click();
		});
		
		popup.jqmShow();
	});

	// show popups on action hashes. this is used by the chrome extension to link to signup/password reminder forms
	var hash = location.hash.toString();
	if (hash == "#do=signup") $("#global-nav .popup-register").click();
	else if (hash == "#do=forgotpassword") $("#global-nav .popup-forgot").click();
}

function navOver(id){
    clearTimeout(navigationOutTimer);
    navigationTimer = setTimeout("$('.nav-dropdown').hide();showNav('"+id+"');overnavdelay=0;navOpen=true;",overnavdelay);
}
function navOut(){
    navigationOutTimer = setTimeout("overnavdelay=250;navOpen=false;",500);
    clearTimeout(navigationTimer);
}
function navClick(id, u){
    if(navOpen) { location.href=u; return true; }
    return false;
}
function initNav(){
	//Navigation Scripts
        $("#menu-wrp .menu li a").click(function(e){  e.preventDefault(); if(!navClick($(this).attr("href"))){ $(this).parent().trigger("mouseenter"); } });
        $("#header .nav-dropdown a.nav_close").click(function(e){ e.preventDefault(); $(this).parent().hide(); navOut(); });
        $("#menu-wrp .menu li").bind("mouseleave", function(){clearTimeout(navigationTimer);});
	$(".nav-dropdown").children().bind("mouseenter", function(){$(this).parent().show();});
	$(".nav-dropdown").children().bind("mouseleave", function(){$(this).parent().hide();navOut();});
        $("#menu-wrp .menu li:eq(0)").bind("mouseenter", function(){navOver('someecards-nav');});
	$("#menu-wrp .menu li:eq(1)").bind("mouseenter", function(){navOver('invites-nav');});
	$("#menu-wrp .menu li:eq(2)").bind("mouseenter", function(){navOver('someusercards-nav');});
	$("#menu-wrp .menu li:eq(3)").bind("mouseenter", function(){navOver('create-nav');});
	$("#menu-wrp .menu li:eq(4)").bind("mouseenter", function(){navOver('inbox-nav');});
	$("#menu-wrp .menu li:eq(5)").bind("mouseenter", function(){navOver('somestore-nav');});
	//$("#menu-wrp .menu li:eq(6)").bind("mouseenter", function(){ navOver('blog-nav'); });

        //Click Propogation Stops
	$("#more-search-wrp").click(function(e){
		if((e.clientY - $(this).offset().top) >= 50)
			e.stopPropagation();
		else if((e.clientX - $(this).offset().left) >= 650)
			e.stopPropagation();
	});
	$("#searchbox, #more-search-wrp .options").click(function(e){e.stopPropagation();});

	$("#search").focus(function(e){
		if(this.value=="search for something") this.value="";

		e.stopPropagation();
		showSearch(this);
	}).click(function(e){e.stopPropagation();});
}
function movePanel(nextPanel, rotate){
	var numPanels = $("#panels > li").size();
	clearTimeout(currentTimer);

	if((currentPanel+nextPanel)<0) nextPanel = numPanels-1;
	else if(currentPanel+nextPanel==numPanels) nextPanel = 0;
	else nextPanel = currentPanel+nextPanel;

	$("#panels > li").hide();
	$("#panels > li:eq(" + nextPanel + ")").show();
        $("#breakingcard_img_holder ul li:eq("+nextPanel+")")
        var nxtpos = $("#breakingcard_img_holder ul li:eq("+nextPanel+")").position();
        $("#breakingcard_img_holder ul").animate({left:-nxtpos.left+"px"}, 400);
	$(".panel-numbers ul li").removeClass("on");
	$(".panel-numbers ul li:eq(" + nextPanel  + ")").addClass("on");
	
	currentPanel = nextPanel;

	if(rotate) currentTimer = setTimeout("movePanel(1, true)",5000);
}
function showSearch(item){
	if($("#more-search-wrp").css("display")=="none"){
		$("#header").addClass("on");
		$("#more-search-wrp").show().animate({"height":"124px"},
			250,
			function(){
				$(this).css("min-height","124px").css("height","auto");
				if ($.browser.msie && $.browser.version == 6)  $(this).css("height","124px");
			}
		);
		$("body").click(function(e){hideSearch();});
	}
}
function hideSearch(){
	$("#more-search-wrp").css({"height":"124px","min-height":""}).animate({"height":"55px"},
		250,
		function callback(){
			$(this).hide();
			$("#header").removeClass("on");
			if(document.getElementById("search").value=="") document.getElementById("search").value="search for something";
			$("body").unbind("click");
		}
	);
	
	return false;
}
function expandCard(curr,cardNum){
	var item = $(curr);
	var card = item.parents("li.card");
	
	if(item.html()=="Expand »"){
		expandedCards.push({"name":"card"+cardNum,"height":card.height(),"other":card.hasClass("other")});
		$("div.mini-info",card).animate(
			{height: "1px"},
			500,
			function(){
				item.html("Collapse &laquo;");
				card.removeClass("other");
				$(this).hide();
				
				var expand = $("div.expandable",card);
				if(expand.html() == ""){
					expand.html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>");
					expand.animate({height: "37px"},250,function(){
						expand.load(
							config.base_path + "/user/expand?sid="+cardNum,
							function(){ 
								expand.animate(
									{height: "500px"},
									500,
									function(){ 
										$(this).css("height","auto").css("position","relative");
										$(".add-to-fav a", expand).click( function(){
                                           return favoriteCard(this);
                                        });	
									 }
								); 
							}
						);
					});
				} else expand.animate({height: "500px"},250,function(){$(this).css("height","auto").css("position","relative");});
			}
		);
	} else {
		$("div.expandable",card).animate(
			{height: "1px"},
			500,
			function(){
				item.html("Expand &raquo;");
				$(this).hide();
				for(i=0; i<expandedCards.length; i++){
					if(expandedCards[i].name==("card"+cardNum)){
						$("div.mini-info",card).animate({height: expandedCards[i].height+"px"},250);
						if(expandedCards[i].other) card.addClass("other");
						expandedCards.splice(i,1);
						break;
					}
					
				}
				
			}
		);
	}
}
function submitPopup(type, callback, logoutfirst){
	var popup = $("#popup");
	var inputs = $("input",popup);
	var error = false;
        if(!logoutfirst) logoutfirst = false;
	
	$("div.link-button .ajax").hide();

	switch (type){
		case "login":
                       var handle = $.trim($("#popup-login-email").val());
                       var pass = $("#popup-login-password").val();
                       //var makelink = ($(".fbidsec_makelink").val()=="true");
                       var rem = $("#popup-login-remember:checked").length>0;
                       if(handle==""){
                            var jqT = $("#popup-login-email");
                            jqT.val("Please enter e-mail/username");
                            jqT.addClass("register-error error").focus(function(){
                                $(this).val("");
                                $(this).removeClass("register-error error").unbind("focus");
                            }).keydown(function(){$(this).removeClass("register-error error").unbind("focus").unbind("keydown");});
                           error = true;
                       }
                       if(pass==""){
                            var jqT = $("#popup-login-password");
                            jqT.addClass("register-error error").focus(function(){
                                $(this).val("");
                                $(this).removeClass("register-error error").unbind("focus");
                            }).keydown(function(){$(this).removeClass("register-error error").unbind("focus").unbind("keydown");});
                           error = true;
                       }
                       
			if(!error){
				$("div.link-button .ajax").show();
                                $.post(config.base_path + "/user/popup_login", {"popup-login-email":handle,
                                                                                                        "popup-login-password":pass,
                                                                                                        "popup-login-remember":rem,
                                                                                                        "logoutfirst":logoutfirst},function(r){
					var rVal = eval("(" + r + ")");
					if((rVal.status=="FAIL") && (rVal.error_code=="1")) {
						$(inputs[1]).val("");
						$(inputs[0]).val("Invalid e-mail/username").addClass("error").focus(function(){
							this.value = "";
							$(this).removeClass("error").unbind("focus").unbind("keydown");
						}).keydown(function(){$(this).removeClass("error").val("").unbind("focus").unbind("keydown");});
					} else if((rVal.status=="FAIL") && (rVal.error_code=="2")) {
						if(!$.browser.msie) inputs[1].type = "text";
						$(inputs[1]).val("Invalid Password").addClass("error").focus(function(){
							this.value = "";
							if(!$.browser.msie) this.type = "password";
							$(this).removeClass("error").unbind("focus").unbind("keydown");
						}).keydown(function(){this.value = "";if(!$.browser.msie) this.type = "password";$(this).removeClass("error").val("").unbind("focus").unbind("keydown");});
					} 
					else if((rVal.status=="FAIL") && (rVal.error_code=="3")) {
						reloadPage();
					} else {
                                                $("div.link-button a.unsubscribe",popup).hide();
                                                $("div.link-button a.button",popup).html("Close").addClass("close").unbind("click").click(function(){
                                                $("div.link-button a.button",popup).removeClass("close");
                                                popup.jqmHide();
                                                                }).focus();
                                                $("div.link-button .ajax").hide();
                                               
                                                if(loginVote){
                                                        $("body > .jqmOverlay").remove();
                                                        cardVote(loginVote);
                                                }
                                                else if(callback) $(callback);
                                                else reloadPage();
					}
					$("div.link-button .ajax").hide();
				});
			}
		
			break;
      case "forgot":
            $("div.link-button .ajax").show();
			$.post(config.base_path + "/user/popup_forgot",$("form",popup).serialize(),function(r){
                    $("div.link-button .ajax").hide();
                    if(r == "1") {
						$(inputs[0]).val("Invalid E-Mail or Username").addClass("error").focus(function(){
							this.value = "";
							$(this).removeClass("error").unbind("focus").unbind("keydown");
						}).keydown(function(){$(this).removeClass("error").val("").unbind("focus").unbind("keydown");});
                    } else {
                        popup.removeClass().addClass("message");
                        $(".content",popup).html('<div class="message"><hr />Recovery link has been sent to your email</div>');
                        $("div.link-button a.forgot",popup).hide();
                        $("div.link-button a.button",popup).html("Close").addClass("close").unbind("click").click(function(){
                                $("div.link-button a.button",popup).removeClass("close");
                                popup.jqmHide();
                        }).focus();
                    }
                });
            break;
        case "register":
            submitRegister();
            break;
        case "newsletter-unsubscribe":
        case "newsletter":
                inputs.each(function(i){
                        var validEmail = (this.value.search(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i) >= 0) ? true : false;
                        var jqT = $(this);
                        if(this.value == ""){
                                jqT.addClass("error").focus(function(){
                                        this.value = "";
                                        jqT.removeClass("error").unbind("focus").unbind("keydown");
                                }).keydown(function(){$(this).removeClass("error").val("").unbind("focus").unbind("keydown");});
                                this.value = "Please enter e-mail";
                        } else if(!validEmail) {
                                jqT.addClass("error").focus(function(){
                                        this.value = "";
                                        jqT.removeClass("error").unbind("focus").unbind("keydown");
                                }).keydown(function(){$(this).removeClass("error").val("").unbind("focus").unbind("keydown");});
                                this.value = "Please enter valid e-mail";
                        } else {
                                $("div.link-button .ajax").show();
                                if(type=="newsletter-unsubscribe") unsubscribe($("#popup-newsletter-email",popup).val());
            else subscribe($("#popup-newsletter-email",popup).val());
                        }
                });

                break
	};
}
function showNav(id){
    $("#"+id).show();
    $("#"+id+" .tab .navcor-tr").show();
}
function showMessage(m,h,f){
	var popup = $("#popup");
	popup.removeClass().addClass("message");
	$(".content",popup).html('<div class="message"><hr />' + m + '</div>');
	$("h3",popup).html(h);
	$("div.link-button a.unsubscribe",popup).hide();
	$("div.link-button a.button",popup).html("Close").addClass("close").unbind("click").click(function(){
        $("div.link-button a.button",popup).removeClass("close");
		popup.jqmHide();
		if(f) f.call(this);
		return false;
	});	
	$("div.close",popup).unbind("click").click(function(){
		popup.hide();
		if(f) f.call(this);
	});
	
	if($.browser.msie){
		popup.css("top",document.documentElement.scrollTop+150);
	} else {
		popup.css("top",window.pageYOffset+150);
	}
	popup.jqmShow();	
	$("div.link-button a.button",popup).focus();					
}

function activateCardOverlay(thumb_id, thumb_data){
    $('#'+thumb_id).hover(
        function(){
            cardThumbHit = true;
            var inv = $("body.invites").length>0,
                usr = ($("body#someusercards").length>0 || thumb_data.usercard!=undefined),
                cid = $(this).attr("id").substring(12),
                vid = $(this).hasClass("is_video"),
                fbdockid = $("#overlay_fbdockid").val(),
                dispHei = 236,
                fbimg = '',
                imghtml = '';
            
            if($("#cardthumb_overlay #overlay_cid").val()==cid) {
                cardOverlayShow(thumb_id, thumb_data);
                return;
            }
            $("#cardthumb_overlay #overlay_cid").val(cid);
            
            // user cards
            if(usr) {
                dispHei = 300;
                fbimg = thumb_data.thumb_img;
                if(thumb_data.img){
                    fbimg = thumb_data.img;
                    imghtml = '<a href="'+thumb_data.href+'"><img src="'+thumb_data.img+'" alt="'+thumb_data.title+'" style="margin-top:5px;" /></a>';
                }
                else {
                    var user_vars = '';
                    for(var i in thumb_data.usercard) user_vars += (i+"="+thumb_data.usercard[i]+"&");
                    imghtml = '<object width="419" height="300"><embed type="application/x-shockwave-flash" ';
                    imghtml += 'src="'+usercards_object_path+'" allowScriptAccess="always" allowfullscreen="false" width="419" height="300" ';
                    imghtml += 'flashvars="'+user_vars+'" /></object>';
                }
            }
            // video cards
            else if(vid){
                dispHei = 276;
                fbimg = thumb_data.thumb_img;
                var video_vars = '';
                for(var i in thumb_data.video) video_vars += (i+"="+thumb_data.video[i]+"&");
                imghtml = '<object width="425" height="278"><embed type="application/x-shockwave-flash" ';
                imghtml += 'src="'+video_object_path+'" id="overlay-video_preview" name="overlay-video_preview" bgcolor="#FFFFFF" quality="high" wmode="transparent" ';
                imghtml += 'flashvars="'+video_vars+'" height="278" width="425" /></object>';
            }
            // reg cards
            else {
                if(thumb_data.age_gate >0 && !age_gate_check(thumb_data.age_gate)){
                    imghtml = '<a href="'+thumb_data.href+'"><img src="http://static.someecards.com/someecards/sec/images/AgeGateCard.jpg" alt="'+thumb_data.title+'" /></a>';
                }
                else {
                    imghtml = '<a href="'+thumb_data.href+'"><img src="'+thumb_data.img+'" alt="'+thumb_data.title+'" /></a>';
                }
                
                fbimg = thumb_data.img;
            }

            if(thumb_data.custom_height){
                dispHei = thumb_data.custom_height;
            }

            // social bar
            var tw_u = thumb_data.href, post_tw = '';
            if(thumb_data.short_url) tw_u = thumb_data.short_url;
            if(thumb_data.post_tw) post_tw = thumb_data.post_tw;
            $("#cardthumb_overlay .social-twitter").attr("href", 'http://twitter.com/share?via=someecards&counturl='+thumb_data.href+'&url='+tw_u+'&text='+escape(thumb_data.title)+escape(post_tw)).click(function(){
                window.open($(this).attr("href"),"twitter_tweet","left=200,top=200,width=500,height=200,personalbar=no,toolbar=no,scrollbars=yes,location=yes,resizable=yes");return false;
            });
            $("#cardthumb_overlay .social-myspace").attr("href", 'http://www.myspace.com/Modules/PostTo/Pages/?u='+encodeURIComponent(thumb_data.href));
            $("#cardthumb_overlay .social-stumbleupon").attr("href", 'http://www.stumbleupon.com/submit?url='+thumb_data.href).click(function(){
                window.open($(this).attr("href"),"stumble_it","left=200,top=200,width=450,height=400,personalbar=no,toolbar=no,scrollbars=yes,location=yes,resizable=yes");return false;
            });
            $("#cardthumb_overlay .social-invite").attr("href", thumb_data.href+"#invite");
            $("#cardthumb_overlay .social-email").attr("href", thumb_data.href);
            $("#cardthumb_overlay .social-facebook").unbind("click").click(function(e){
                e.preventDefault(); 
                toggleFBDock('#'+fbdockid);
                bindFBDock(fbdockid,
                      {'name':thumb_data.title,
                       'description':'Source: someecards.com',
                       'href':thumb_data.href,
                       'short_url':tw_u,
                       'media': [{'type':'image', 'src':fbimg, 'href':thumb_data.href}]}, true
                );
            });

            // image
            $("#cardthumb_overlay #cont .display").html(imghtml).css("height", dispHei+'px');
            
            cardOverlayPosition(thumb_id, dispHei, thumb_data);
            cardOverlayShow(thumb_id, thumb_data);
        },
        function(){
            cardThumbHit = false;
            cardOverlayHide();
        }
    );
}

var viewedCardsOverlay = new Array();
function cardOverlayShow(thumb_id, thumb_data){
    if($("#cardthumb_overlay").is(":hidden")){
        clearTimeout(cardOverlayOutTimer);
        cardOverlayTimer = setTimeout("$('#cardthumb_overlay').fadeIn(200);cardOverlayDelay=0;",cardOverlayDelay);
    }
    if(overlay_tracking){
        var cid = $('#'+thumb_id).attr("id").substring(12),
             card_type = 0;
        if($("body#someusercards").length>0 || thumb_data.usercard) card_type = 1;
        else if($("body.invites").length>0) card_type = 2;
        for(var k in viewedCardsOverlay)
            if(viewedCardsOverlay[k]==(card_type+"_"+cid)) return;
        viewedCardsOverlay.push(card_type+"_"+cid);
    }
}
function cardOverlayPosition(thumb_id, disp_hei, thumb_data){
    var thumb = $('#'+thumb_id),
         pos = thumb.parent().position(),
         offset = thumb.offset(),
         overlay_height = disp_hei, 
         leftOffset = pos.left,
         topOffset = offset.top-(overlay_height+94);

    if($.browser.msie) topOffset += 50;

    //if($("body#someusercards").length>0) topOffset += 60;
    if(leftOffset>450) leftOffset = offset.left - ($("#cardthumb_overlay").width() -110);
    else if(leftOffset>350) leftOffset = offset.left - ($("#cardthumb_overlay").width() - 180);
    else if(leftOffset>220) leftOffset = offset.left - ($("#cardthumb_overlay").width()/2 - 55);
    else if(leftOffset>100) leftOffset = offset.left - 80;
    else leftOffset = offset.left;

    if($(".categories-list").length>0){
        leftOffset = offset.left;
        topOffset = offset.top - (overlay_height+44);
    }

    $("#cardthumb_overlay").removeClass('video');
    //if($.browser.msie) topOffset += 50;
    var topshadow_width = $("#cardthumb_overlay").width()-10;
    $("#cardthumb_overlay .shadow .top table .l, #cardthumb_overlay .shadow .bot table .l").css("width", topshadow_width+"px");
    $("#cardthumb_overlay")
        .css({top:(topOffset)+"px", left:(leftOffset)+"px"})
        .unbind("mouseenter").bind("mouseenter", function(){
            cardOverlayHit = true;
            cardOverlayShow(thumb_id, thumb_data);
        })
        .unbind("mouseleave").bind("mouseleave", function(){
            cardOverlayHit = false;
            cardOverlayHide();
        });

}
function cardOverlayHide(){
    clearTimeout(cardOverlayTimer);
    setTimeout('cardOverlayHide_timeout()', 40);
    $("#cardthumb_overlay .status-message").html('').hide();
    var fbdockid = $("#overlay_fbdockid").val();
    $("#"+fbdockid).hide();
}
function cardOverlayHide_timeout(){
    if(!cardOverlayHit && !cardThumbHit){
        $("#cardthumb_overlay").hide();
        cardOverlayOutTimer = setTimeout("cardOverlayDelay=400;",150);
        clearTimeout(cardOverlayTimer);
        $("#cardthumb_overlay #overlay_cid").val("-1");
        if(overlay_tracking){
            if(viewedCardsOverlay.length > 0){
                $.get(config.base_path + "/card/ctv", { 'clist':viewedCardsOverlay }, function(data){
                    viewedCardsOverlay = new Array();
                }, 'json');
            }
        }
    }
}

function bindComments_pagination(pid){
    $("#comments_div .pagination .pages li a").unbind('click').click(function(e){
        e.preventDefault();
        var pg = $(this).attr("title");
        $.get(config.base_path+"/card/ajcomments", { 'a':'getpage', 'pg':pg, 'pid':pid }, function(data){
            if(data.status=='OK'){
                $("#comments_list").html(data.list);
                $("#comments_div .pagination .pages").html(data.pages);
                $("#comments_div .comment_current_page").html(data.current_page);
                bindComments_pagination(pid);
                location.href="#comments";
            }
        }, 'json');
    });
}

function bindCommentSubmit(){
    $("#comment_form #comment_submit").unbind('click').click(function(e){
        e.preventDefault();
        $(this).unbind("click").click(function(e){ e.preventDefault(); });

        var name = $.trim($("#comment_name").val()), 
              email = $.trim($("#comment_email").val()),
              body = $.trim($("#comment_text").val()),
              notify = ($("#comment_notify:checked").length>0),
              paa = ($("#comment_paa:checked").length>0),
              newsletter = ($("#comment_newsletter_subscribe:checked").length>0),
              challenge = $("input#recaptcha_challenge_field").val(),
              response = $.trim($("input#recaptcha_response_field").val()),
              errdiv = $("#comment_form .comment_errors"),
              has_error = false,
              is_post = false,
              up = $.cookies.get('usrprof', true);
         if($(this).parent().find(".card_id").length>0){
              var card_id = $(this).parent().find(".card_id").val(),
                    card_type = $(this).parent().find(".card_type").val();
         }
         else if($(this).parent().find(".post_id").length>0){
              var post_id = $(this).parent().find(".post_id").val(),
                    post_type = $(this).parent().find(".post_type").val(),
                    is_post = true;
         }

        if(name=='' || email=='' || body==''){
            errdiv.html("Please complete all required fields.");
            has_error = true;
        }
        else if(!validateEmail(email)){
            errdiv.html("Please enter a valid email.");
            has_error = true;
        }
        else if(!up && response=='') {
            errdiv.html("Please enter the words in the CAPTCHA image.");
            has_error = true;
        }

        if(has_error){
            toggleCommentsError(true);
            bindCommentSubmit();
            return;
        }


        var params = {
            a:'postcomment', e:email, n:name, c:body, notify:(notify?1:0), paa:(paa?1:0), subnews:(newsletter?1:0),
            captcha_challenge:challenge, captcha_response:response
        }
        if(is_post){
            params['post_id'] = post_id;
            params['post_type'] = post_type;
        }
        else {
            params['card_id'] = card_id;
            params['card_type'] = card_type;
        }

        $("#comment_form .ajax_loader").show();
        $.post(config.base_path+'/card/ajcomments', params, function(data){
            $("#comment_form .ajax_loader").hide();
            if(data.status=="OK"){
                toggleCommentsError(false);
                $("#comments_div ul#comments_list li.be_first_comment").hide();
                $("#comments_div ul#comments_list").prepend(data.comment_html).children(':first').hide().slideDown();

                var count_tab = $("li#comments_tab"),
                      is_post = false;

                if($(".feed_share_holder .feed_share li.comments").length>0){
                    count_tab = $(".feed_share_holder .feed_share li.comments");
                    is_post = true;
                }
                var curcnt = $.trim(count_tab.find("b").html());
                if(curcnt=='' && !is_post) count_tab.css("width", "129px");
                count_tab.find("b").html("("+data.comment_count+")");

                if(data.subscribed){
                    $(".submit_row .newsletter_row").css("padding-top", "5px").html('<span class="success">Thanks! An email has been sent to confirm your subscription.</span>');
                }

                $("#comment_text").val('');
                $("#comment_form .captcha_row").slideUp();
            }
            else {
                errdiv.html(data.error);
                toggleCommentsError(true);
            }
            if(!up && Recaptcha) Recaptcha.reload();
            bindCommentSubmit();
        }, 'json');

    });
    bindCommentFlag();
}
function bindCommentFlag(){
    $("#comments_div ul li a.flag_comment").unbind('click').click(function(e){
        e.preventDefault();
        if($(this).hasClass("flagged")) return;
        var comm_id = $(this).parent().parent().parent().find("input.comment_id").val();
        var is_post = ($(".feed_share_holder .feed_share li.comments").length>0)?1:0;

        $.post(config.base_path+'/card/ajcomments', {a:'flag', comment_id:comm_id, is_feed_post:is_post}, function(data){
            $("#comments_div ul li input.comment_id[value="+data.comment_id+"]").parent().find("a.flag_comment").addClass("flagged").html('flagged');
        }, 'json');
    });
}
function toggleCommentsError(show){
    var errdiv = $("#comment_form .comment_errors");
    if(show){
        if(!errdiv.is(":visible")) errdiv.slideDown();
    }
    else {
        if(errdiv.is(":visible")) errdiv.slideUp();

    }
}

function openGOAForm(email, first_name, last_name){
        var popup = $("#popup");
        popup.css("position","absolute");
        if($.browser.msie) {
            if(document.documentElement.scrollTop<50) popup.css("top",200);
            else popup.css("top",document.documentElement.scrollTop+150);
        }
        else {
            if(window.pageYOffset<50) popup.css("top",200);
            else popup.css("top",window.pageYOffset+150);
        }
        //popup.css("top",200);
        
        $(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>")
        popup.removeClass().addClass("goa_overlay");
        $("h3",popup).html("Help Protect America’s Great Outdoors!");
        
        $("div.link-button a.unsubscribe",popup).attr("href", "#").removeAttr("onclick").html("Cancel").unbind("click").click(function(){
            $("#popup").jqmHide();
            return false;
        }).show();

        $(".link-button .need-account",popup).hide();
        $(".content",popup).load("/static/popup-goa.php?", null, function(){
            var cur_u = location.href;
            if(cur_u.indexOf('ago_tx')<=0){
                if(cur_u.indexOf('?')>0) cur_u += "&ago_tx=1";
                else cur_u += "?ago_tx=1";
            }
            $("#goa_form input.thank_you").val(cur_u);
            //autopopulate
            if(Boolean(typeof email!='undefined' && email)) $("#goa_form input.email").val(email);
            else if(Boolean(typeof goa_sender_email!='undefined' && goa_sender_email)) $("#goa_form input.email").val(goa_sender_email);
            if(Boolean(typeof first_name!='undefined' && first_name)) $("#goa_form input.first_name").val(first_name);
            else if(Boolean(typeof goa_sender_firstname!='undefined' && goa_sender_firstname)) $("#goa_form input.first_name").val(goa_sender_firstname);
            if(Boolean(typeof last_name!='undefined' && last_name)) $("#goa_form input.last_name").val(last_name);
            else if(Boolean(typeof goa_sender_lastname!='undefined' && goa_sender_lastname)) $("#goa_form input.last_name").val(goa_sender_lastname);

            $(".link-button .button",popup).html("Send &raquo;").unbind("click").click(function(){
                var gf_email = $.trim($("#goa_form input.email").val());
                var gf_fname = $.trim($("#goa_form input.first_name").val());
                var gf_lname = $.trim($("#goa_form input.last_name").val());
                var gf_msg = $.trim($("#goa_form .msg_row textarea").val());

                if(gf_email=="" || gf_fname=="" || gf_lname=="" || gf_msg==""){
                    $("#goa_form .errors").html("* All fields are required.");
                    return false;
                }
                if(!validateEmail(gf_email)){
                    $("#goa_form .errors").html("* Please enter a valid email.");
                    return false;
                }
                $(".sending_spinner", popup).show();
                $("#goa_form").submit();
                
                return false;
            }).show();
        });
        $(".close",popup).css('z-index','1000').click(function(){$("#popup").jqmHide();});

        popup.jqmShow();
        $(".jqmOverlay").css("opacity", "0.8");
        return false;
}

function openGOAForm_thanks(static){
        var popup = $("#popup");
        popup.css("position","absolute");
        if($.browser.msie) {
            if(document.documentElement.scrollTop<50) popup.css("top",200);
            else popup.css("top",document.documentElement.scrollTop+150);
        }
        else {
            if(window.pageYOffset<50) popup.css("top",200);
            else popup.css("top",window.pageYOffset+150);
        }
        //popup.css("top",200);

        $(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>")
        popup.removeClass().addClass("goa_overlay_thanks");
        $("h3",popup).html("Thank you for your support!");

        $("div.link-button a.unsubscribe",popup).attr("href", "#").removeAttr("onclick").html("Close").unbind("click").click(function(){
            $("#popup").jqmHide();
            return false;
        }).show();

        var is_st = '';
        if(Boolean(typeof static!='undefined' && static)){
            is_st = 'static=1';
        }

        $(".link-button .need-account",popup).hide();
        $(".content",popup).load("/static/popup-goa_thankyou.php?"+is_st, null, function(){
            
            $(".link-button .button",popup).html("Send &raquo;").unbind("click").click(function(){
                location.href="/americas-great-outdoors-cards/stephen-colbert-americas-great-outdoors";
            }).show();
        });
        $(".close",popup).css('z-index','1000').click(function(){$("#popup").jqmHide();});

        popup.jqmShow();
        $(".jqmOverlay").css("opacity", "0.8");
        return false;
}

function track_jserror(msg, url, line){
    var u = location.href;
    var cid = $.cookies.get('tjse_cid', false);
    if(!cid) cid = 0;
    var m = "Url: "+url+" [Line "+line+"]<br />Msg: "+msg;
    if(url==undefined && line==undefined && (msg!=undefined && msg!=null)){
        var s = '';
        for(var i in msg) s += i+" = "+msg[i]+"<br />";
        m += "<br />"+s;
    }
    var bsz = $(window).width()+" x "+$(window).height();
    var scr = screen.width+" x "+screen.height;
    $.post(config.base_path + '/tjse', { u:u, cid:cid, e:m, bsz:bsz, scr:scr }, function(data){
        var expire=new Date();
        expire.setDate(expire.getDate()+30);
        $.cookies.set('tjse_cid', data.cid, { path: '/', expiresAt: expire });
    }, 'json');
}

$(document).ready(function(){
    $("#preload_mcback").remove();
    $(".feed_share .fbpost a").unbind('click').click(function(e){
        e.preventDefault();
        toggleFBDock("#mc #fb"+$(this).attr("id"));
    });
    
    bindCommentSubmit();

    $("#send-card-view div.send-workflow div.login").keydown(function(e){
            if(e.keyCode==13){
                    $("div.submit-login a.login-btn", $(this)).click();
            }
    });

    $("#newsletter").keydown(function(e){
            if(e.keyCode==13){
                    $("img", $(this)).click();
            }
    });

    $(".embedperma textarea#permalink, .embedperma textarea#embed").click(function(){
        $(this).select();
    });

    //Add to Favorites
    $(".add-to-fav a, a.add-to-fav").unbind("click").click( function(){
    return favoriteCard(this);
    });
    $(".remove-fav a, a.remove-fav").unbind("click").click( function(){
        return removeFromFav(this);
    });

    // Check if it's a supported browser and offer an extension
    if (navigator.userAgent.match(/ Chrome\//)) {
	var marker = $('<div id="extensionMarker" style="display:none"></div>');
	$("body").append(marker);
	if (marker.css("font-size") != "160px") extensionInstallerPopup("Google Chrome", "https://chrome.google.com/extensions/detail/hkdnlpfjhfmemgakjiccbjfnehpakdjk");
    }

    //Popups
    $(".popup-newsletter").unbind("click").click(function(){
            var popup = $("#popup");
            if($.browser.msie){
                    popup.css("top",document.documentElement.scrollTop+150);
            } else {
                    popup.css("top",window.pageYOffset+150);
            }

            $(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>")
            popup.removeClass().addClass("newsletter");
            $("h3", popup).html("Newsletter Subscribe");
            $("div.link-button a.unsubscribe",popup).css("display","block").html("Unsubscribe from the newsletter.");
            $(".link-button .button",popup).html("Submit &raquo;").unbind("click").click(function(){
                    submitPopup("newsletter");
                    return false;
            });
            $(".link-button .button",popup).show();
            $(".content",popup).load("/static/popup-newsletter.php");

            $("div.content div.fields input",popup).keydown(function(e){
                    if(e.keyCode == 13) $("#popup .link-button .button").click();
            });
            $(".close",popup).click(function(){$("#popup").jqmHide();});

            popup.jqmShow();
            return false;
    });
    $("#saved ul li .del a, .card-info .administration a.delete_uc").click(function(){
        if (confirm("Are you sure you want to delete this card ?")){
            if($(this).hasClass('delete_uc'))
                window.location = this.href;
            else{
                $.get(this.href);
                $(this).parents("li.card").remove();
            }
            return false;
        }
    });

});

function resetAutoRefresh(){
    clearTimeout(autorefresh);
    autorefresh = setTimeout(function(){ reloadPage(); }, 1000*600);
}

function extensionInstallerPopup(browser, link) {
	if (typeof localStorage == "object" && localStorage.showExtensionInstaller == "0") return;
	var bar = $('<div class="extensionInstaller"><div class="left"><img class="logo" src="http://cdn.someecards.com/someecards/sec/images/browser-extension/icon.png" align="absmiddle">Check out our <a href="' +
		    link + '">' + browser + '" Extension</a>. View and share latest e-cards, posts or any Web page easy.</div><div class="right"><a href="' + link + '" class="install">Install</a><a href="#" title="Close" class="close"></a></div>');
	bar.find("a").click(extensionInstallerClose);
	$("body").prepend(bar);
	bar.slideDown();
}

function extensionInstallerClose() {
	$(".extensionInstaller").hide();
	if ($(this).hasClass("close") && typeof localStorage == "object") {
		localStorage.showExtensionInstaller = "0";
		return false;
	}
	return true;
}

function initNewsletterModule(){
    var newsletter_default = "enter your email address";
    $(".newsletter_module .input_holder .email_input").focus(function(){
        var i = $.trim($(this).val()).toLowerCase();
        if(i==newsletter_default) $(this).css("color", "#000000").val('');
    }).blur(function(){
        var i = $.trim($(this).val());
        if(i=="") $(this).css("color", "#989898").val(newsletter_default);
    });
    $(".newsletter_module .submit_holder").click(function(){
        var e = $(".newsletter_module .input_holder .email_input").val();
        $(".newsletter_module .status_msg").hide();
        if(!validateEmail(e)){
            $(".newsletter_module .status_msg span").removeClass().addClass("error").html("Invalid Email");
            $(".newsletter_module .status_msg").fadeIn();
            return false;
        }

	$.getJSON(config.base_path + "/user/subscribe", {'email': e}, function(r){
            if (r.status=="OK"){
                $(".newsletter_module .status_msg span").removeClass().addClass("success").html("Success: An email has been sent to confirm subscription");
                setTimeout('$(".newsletter_module .status_msg").fadeOut();$(".newsletter_module .input_holder .email_input").val("").blur();', 6000)
            }
            else {
                $(".newsletter_module .status_msg span").removeClass().addClass("error").html(r.error);
            }
            $(".newsletter_module .status_msg").fadeIn();
	});
        return false;
    });
}


function initBreakingCards(){
	//Nav Panel Controls
	$("#breaking-cards .controls a").click(function(){
		var control = $(this).attr("class");
		switch(control){
			case "pause":
				$(this).hide().siblings('.play').show();
				clearTimeout(currentTimer);
				currentTimer=0;
				break;
			case "play":
				$(this).hide().siblings('.pause').show();
				currentTimer = setTimeout("movePanel(1, true)",3500);
				break;
			case "prev": movePanel(-1, true); break;
			case "next": movePanel(1, true); break;
		}
		return false;
	});
	$("#panels > li:eq(0)").show();

	$("#breaking-cards .panel-numbers ul li").hover(
		function(){$(this).addClass("on");},
		function(){if(currentPanel != ($(this).html()-1) )$(this).toggleClass("on");}
	).click(function(){
                $("#breaking-cards .pause").hide().siblings('.play').show();
                clearTimeout(currentTimer);
                clearTimeout(breakingDelayedTimer);
                movePanel( ($(this).html()-currentPanel-1), false);
                breakingDelayedTimer = setTimeout(function(){
                	currentTimer = setTimeout("movePanel(1, true)",3500);
                },3500);
            });

        $("#breakingcard_img_holder ul li a img.lazy").each(function(i, el){
            $(this).attr("src", $(this).attr("title")).removeAttr("title").removeClass();
        });

	currentTimer = setTimeout("movePanel(1, true)",3500);

}

function initCardTabs(){
    //Send Worlflow Change
    $("#mc div.send-workflow div.send-data-wrp div.send-cat ul li").bind("click", function(){
            var curLoc = location.href;
            curLoc = curLoc.substring(curLoc.indexOf("/",8));

            var locSplit = curLoc.split("#");
            var type = $(this).html().toLowerCase();
            var hashId = "";
            if (type.indexOf('discuss') > -1) hashId = "#comments";
            else if (type.indexOf('email') > -1) hashId = "#email";
            else if (type.indexOf('link') > -1) hashId = "#link";
            else if (type.indexOf('invitation') > -1) hashId = "#invite";
            else if (type.indexOf('submit') > -1) hashId = "#submit";
            location.href = locSplit[0]+hashId;
            switchPanel_str(hashId);

            return false;
    });
    
    var curLoc = location.href;
    var locSplit = curLoc.split("#");
    var curTab = "email";
    if(locSplit.length > 1 && locSplit[1]!=""){
        curTab = locSplit[1].toLowerCase();
    }
    switchPanel_str(curTab);
}

function switchPanel_str(type){
    $("#send-card-view div.send-data-wrp div.send-cat").siblings().hide();
    $("#mc .send-workflow .send-data-wrp .send-cat ul li").removeClass("active");
    var tabId = "";
    type = $.trim(type).toLowerCase();
    var acc = new Array("comments", "email", "social", "link", "instant", "submit", "invite");
    var found = false;
    for(var i in acc){
        if(type.indexOf('discuss') > -1){
            type = 'comments';found = true;break;
        }
        else if(type.indexOf('invitation') > -1){
            type = 'invite';found = true;break;
        }
        else if(type.indexOf(acc[i]) > -1){
            type = acc[i];found = true;break;
        }
    }
    if(!found) type = "email";
    if($("body").hasClass("invites") && (type!="link" && type!="comments"))
        type = "invite";
    var tabholder_sel = "#send-card-view div.send-data-wrp ";
    if (type.indexOf('comments') > -1 && $(tabholder_sel+"#comments_div").length>0) {
        $(tabholder_sel+"#comments_div").show();
        tabId = "#comments_tab";
    } else if (type.indexOf('email') > -1 && $(tabholder_sel+"div.send-data").length>0) {
        $(tabholder_sel+"div.send-data").show();
        tabId = "#email_tab";
    } else if (type.indexOf('link') > -1 && $(tabholder_sel+"div.embedperma").length>0) {
        $(tabholder_sel+"div.embedperma").show();
        tabId = "#linkembed_tab";
    } else if (type.indexOf('submit') > -1 && $(tabholder_sel+"div.submitcard").length>0) {
        $(tabholder_sel+"div.submitcard").show();
        tabId = "#submitcard_tab";
    } else if (type.indexOf('invite') > -1 && $(tabholder_sel+"#invites_div").length>0) {
        $(tabholder_sel+"#invites_div").show();
        tabId = "#invites_tab";
    }
    //} else if (type.indexOf('social') > -1) {
    //    $(tabholder_sel+"div.social-web").show();
    //} else if (type.indexOf('instant') > -1) {
    //    $(tabholder_sel+"div.im").show();
    else {
        $(tabholder_sel+"div.send-data").show();
        tabId = "#email_tab";
    }

    $(tabholder_sel+tabId).addClass("active");
    $(".send-data-wrp .send-cat .notch").css("left", ($(tabId).position().left+$(tabId).width()/2 + 8)+"px");
    $(".send-data-wrp .send-cat .notch").css("display", "block");


}

function sortBy(id){
	//Sort Functions
	$(id + " .sort-by a").click(function(){
		var sort = $(this).html().replace(/ /g,"-").toLowerCase();
		var parent = $(this).parent();
		
		$(this).addClass("active").siblings().removeClass("active");
		$(this).siblings(".more-link").hide().siblings("."+sort).show();

		if(parent.parent()[0].tagName=="H2")
			parent = parent.parent();
		parent.siblings(".click-panel").hide();
		parent.siblings(".click-panel."+sort).show();

		return false;
	});
}

function switchNewsletter(curr){
	var popup = $("#popup");
	if($(curr).html() == "Unsubscribe from the newsletter."){
		$("h3",popup).html("Unsubscribe From Newsletter");
		$(".content p",popup).html("Can't handle the effort of deleting our occasional emails?  We hear that.");
		$(".unsubscribe",popup).html("Subscribe to the newsletter.");
		$(".link-button .button",popup).unbind("click").click(function(){
			submitPopup("newsletter-unsubscribe");
			return false;
		});
	} else {
		$("h3",popup).html("Newsletter Subscribe");
		$(".content p",popup).html("Get and delete updates on new cards, categories, site features, and upcoming holidays!");
		$(".unsubscribe",popup).html("Unsubscribe from the newsletter.");
		$(".link-button .button",popup).unbind("click").click(function(){
			submitPopup("newsletter");
			return false;
		});
		
	}
}

function initFilters(){
	  $("#sort .filters-link").toggle(
	    function(e){
	      $(this).html("&nbsp;&nbsp;&nbsp;close");
	      $(this).css("border-bottom","0");
	      $(".filters").slideDown(250);
	      $("#sort .filters").focus();

	      e.stopPropogation;
	      $("body").click(function(e){if(e.originalTarget.className != "filters")$("#sort .filters-link").click();});

	    },
	    function(e){
	      $(".filters").slideUp(250,function callback(){$(".filters-link").css("border-bottom","1px #b5b4b4 solid");});
	      $(this).html("Filters &raquo;");
	      $("body").unbind("click");
	    }
	  );

	  $("#sort .filters").keypress(function(e){
	    if(e.keyCode==13){submitFilterBySearch();}
	  }).click(function(e){e.stopPropagation();});

	  //Advanced Sort filter clicks
	  $("#sort .filters ul li a").bind("click", function(){
	    var t = $(this), all = t.parents("ul").find("a.all");
	    all.removeClass("active");
	    t.toggleClass("active");
	    if(t.parents("ul").find("a.active").length == 0) all.addClass("active");
	    return false;
	  });
	  $("#sort .filters ul li a.all").unbind().click(function(){
	    $(this).parent().siblings().find("a").removeClass("active");
	    $(this).toggleClass("active");
	    return false;
	  });
}

function initProfile(){
	//Profile Save-Edit-Cancel
	var origVal = new Array($("#profile-info .section").length);
	for(i=0; i<origVal.length; i++) origVal[i] = new Array();
	$("#profile-info .section").each(function(i){ 
		$(this).find("input,select").each(function(){ 
			origVal[i].push($(this).val()); 
		}) 
	});
	$("#profile-info .save-cancel a, #profile-info .edit a").click(function(e){
            e.preventDefault();
		var contents=$(this).parents(".section");
		if($(this).html() == "edit"){
			$(this).parent().hide().prev().show();
			if(contents.hasClass("picture")){
				var lc = $(".load-content",contents);
				lc.html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>").show();
                                $.get(config.base_path + "/user/pics", function(data){
					lc.html('<ul class="images"></ul><div id="pagination"><ul class="pages"></ul><div class="clearer"></div></div><div class="clearer"></div>');
					for(i=0; i<data.images.length; i++){
						var curr_image = ($("#user_avatar").attr("src")==data.images[i].src) ? 'class="selected"' : '';
						$("ul.images",lc).append('<li><img src="' + data.images[i].src + '" height="57" width="57" ' + curr_image + '/><br /><input type="radio" name="user-picture" value="' + data.images[i].imageNum + '"></li>');
					}
					
					lc.find("img, span").show();
					lc.find("img").click(function(){
						$(".load-content input:radio[name=user-picture]:checked").prev().prev().removeClass("selected");
						$(this).addClass("selected").next().next().click();
					});
					$("#pagination").nymPag({
						start:1,
						count: avatarCount,
						display: avatarCount,
						list:"ul.pages",
						onClick: function(e, i){
							getMorePics(i, lc);
						}
					});
				},"json");
				
			} else {
				contents.find("input, label, span").show().end().find("p").hide();
				contents.find("select").addClass("selectOn").show();
			}
		} else {
			var index = $("#profile-info .section").index(contents);
			if($(this).html() == "save") {
				if(contents.hasClass("picture")){
					if($(".load-content input:radio[name=user-picture]:checked").length == 0){
						showMessage('Select an Image!', 'Profile Updated');
						return false;
					} else {
						 $("p img",contents)[0].src = $(".load-content input:radio[name=user-picture]:checked").prev().prev()[0].src;
					}
				} else {
					var p = contents.find("p");
					p.html("");
					contents.find("input,select").each(function(i){ 
						if($(this)[0].id.indexOf("confirm") < 0){
							if(!contents.hasClass("password")){
								p.html(p.html() + $(this).val() + " ");
								origVal[index][i] = $(this).val();
							} else {
								p.html("**********");
								$(this).val("");
							}
						} else {
							$(this).val(origVal[index][i]);
						}
					})
				}
                $.ajax({
                        'url': config.base_path + '/user/pics',
                        'type': 'post',
                        'async': false,
                        'data': {'picture' : $("p img",contents)[0].src},
                        'success': function(data) {
                            if(data == "OK") {showMessage("Picture Saved","Profile Updated");}
                            else {showMessage("Unable to save picture","Profile Error");}
                         }
                });
			} else {
				contents.find("input,select").each(function(i){$(this).val(origVal[index][i]);});
			}
			$(this).parent().hide().next().show();
			contents.find("p").show().end().find("input, label, span").hide();
			contents.find("select").removeClass("selectOn").hide();
			if(contents.hasClass("picture")) contents.find(".load-content").hide();
		}
		return false;
	});	
	
}

function getMorePics(i, lc){
	var images = $("ul.images",lc);
	images.html("");
	lc.prepend("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>").show();
    $.get(config.base_path + "/user/pics?page="+i, function(data){
		$("span.loading",lc).remove();
		for(i=0; i<data.images.length; i++){
			var curr_image = ($("#user_avatar").attr("src")==data.images[i].src) ? 'class="selected"' : '';
			images.append('<li><img src="' + data.images[i].src + '" height="57" width="57" ' + curr_image + '/><br /><input type="radio" name="user-picture" value="' + data.images[i].imageNum + '"></li>');
		}
				
		lc.find("img").click(function(){
			$(".load-content input:radio[name=user-picture]:checked").prev().prev().removeClass("selected");
			$(this).addClass("selected").next().next().click();
		});
	},"json");	
}

function reloadPage() {
   if(location.pathname.indexOf("/invitations/preview")>-1){
       location.href = "/invitations/preview";
       return false;
    }
    location.reload(true);
    return false;
}




/**** SEARCH FUNCTIONS ****/
function submitSearch() {
    if($("#search").val() == "search for something") $("#search").val("");
    var term = $("#search").val();

    if ($("#usercards").attr('checked')) {
        location.href= config.base_path + "/usercards/search?t=" + encodeURI(term);
        return false;
    }

    var category_id = $("select#search_category_list option:selected").val();
    if ($("#search_invites").attr('checked')) category_id = $("select#search_invite_category_list option:selected").val();
    var search_in_text = $("#card-text:checked").val() !== undefined ? 1 : 0;
    var search_in_tags = $("#tags-text:checked").val() !== undefined ? 1 : 0;

    /*
    $("input:hidden#search_form_card_text").val(search_in_text);
    $("input:hidden#search_form_tags_text").val(search_in_tags);
    $("input:hidden#search_form_category_id").val(category_id);
    */
    var inc_cat = (category_id!='')?'&cid='+category_id:'';
    var sb_tags = '', sb_txt = '';
    if(!search_in_tags || !search_in_text){
        sb_tags = (search_in_tags)?'&stg=1':'';
        sb_txt = (search_in_text)?'&stxt=1':'';
    }

    if ($("#posts-checkbox").attr('checked')) {
        location.href= config.base_path + "/post/search?t=" + encodeURI(term) + inc_cat + sb_tags + sb_txt;
    }
    else if ($("#search_invites").attr('checked')) {
        location.href= config.base_path + "/invitations/search-cards/newest?t=" + encodeURI(term) + inc_cat + sb_tags + sb_txt;
    }
    else if($("#more-search .options input#store").attr("checked")){
       term = term.replace(" ", "-");
       location.href= "http://www.cafepress.com/someecards/s_" + escape(kw);
    }
    else {
        var post = config.base_path + "/search-cards/newest?t=" + encodeURI(term) + inc_cat + sb_tags + sb_txt;
        //location.href= post;
        $("#search_form_sv").val("true");
        $("form#search_form").attr("action", post);
        return true;
    }
    return false;

    //$("form#search_form").submit();
    //return true;
}

function submitTopSearch(a) {
    var searchTerm = a.firstChild.nodeValue;
    $("input:text#search").val(searchTerm);
    submitSearch();
    $("form#search_form").submit();
}

function submitSearchByTag(a) {
    var searchTerm = a.firstChild.nodeValue;
    $("input:text#search").val(searchTerm);
    $("#tags-text").attr('checked', true);
    submitSearch();
}

function disableCardsSearch(obj) {
    if (obj.checked) {
        $("#search_category_list").attr('disabled', 1);
        $("#search_invite_category_list").attr('disabled', 1);
        $("#tags-text").attr('disabled', 1);
        $("#card-text").attr('disabled', 1);
        $("#topsearchers").hide();
        $("#topsearchers-disabled").show();
		$("#search_form").attr("action","/usercards/search");
    }
}

function enableCardsSearch(obj) {
    if (obj.checked) {
        $("#search_category_list").attr('disabled', 0);
        $("#search_category_list").show();
        $("#search_invite_category_list").attr('disabled', 0);
        $("#search_invite_category_list").hide();
        $("#tags-text").attr('disabled', 0);
        $("#card-text").attr('disabled', 0);
        $("#topsearchers").show();
        $("#topsearchers-disabled").hide();
        $("#search_form").attr("action","/search-cards/newest");
    }
}

function enableInviteCardsSearch(obj) {
    if (obj.checked) {
        $("#search_category_list").hide(); //attr('disabled', 0);
        $("#search_invite_category_list").show();
        $("#search_invite_category_list").attr('disabled', 0);
        $("#tags-text").attr('disabled', 0);
        $("#card-text").attr('disabled', 0);
        $("#topsearchers").show();
        $("#topsearchers-disabled").hide();
		$("#search_form").attr("action","/search-cards/newest");
    }

}

function enablePostsSearch(obj) {
    if (obj.checked) {
        $("#search_category_list").attr('disabled', 0);
        $("#search_category_list").show();
        $("#search_invite_category_list").hide();
        $("#tags-text").attr('disabled', 0);
        $("#card-text").attr('disabled', 0);
        $("#topsearchers").hide();
        $("#topsearchers-disabled").show();
    }
}

function toggleStoreSearch(obj) {
    if (obj.checked) {
        $("#search_category_list").attr('disabled', 1);
        $("#search_category_list").show();
        $("#search_invite_category_list").hide();
        $("#topsearchers").hide();
        $("#topsearchers-disabled").show();
        $("#tags-text").attr('disabled', 1);
        $("#card-text").attr('disabled', 1);
    }
    else {
        $("#search_category_list").attr('disabled', 0);
    }
}

function submitFilterByTag(tag) {
    var url = $("#cur_url").val();
    if (url.indexOf("?") == -1) url += "?tag=" + tag;
    else {
        if (url.indexOf('tag') == -1) url += "&tag=" + tag;
        else url = url.replace(/tag=[^&]+/, "tag=" + tag);
    }
    location.href = url;
}

function submitFilterByRecipient(rec) {
    var url = $("#cur_url").val();
    if (url.indexOf("?") == -1) url += "?recipient=" + rec;
    else {
        if (url.indexOf('recipient') == -1) url += "&recipient=" + rec;
        else url = url.replace(/recipient=\d+/, "recipient=" + rec);
    }
    location.href = url;
}

function submitFilterBySearch() {
    var url = $("#cur_url").val();
    var term = $("input:text#cat-search").val();
    if (url.indexOf("?") == -1) url += "?term=" + term;
    else {
        if (url.indexOf('term') == -1) url += "&term=" + term;
        else url = url.replace(/term=[^&]+/, "term=" + term);
    }
    location.href = url;
}

function submitFilterByCategory(value) {
    var url = $("#cur_url").val();
    if (url.indexOf("?") == -1) url += "?refine_category=" + value;
    else {
        if (url.indexOf('refine_category') == -1) url += "&refine_category=" + value;
        else url = url.replace(/refine_category=[^&]+/, "refine_category=" + value);
    }
    location.href = url;
}

function submitFilterByVideo() {
    var url = $("#cur_url").val();
    if (url.indexOf("?") == -1) url += "?video=1";
    else if (url.indexOf('video') == -1) url += "&video=1";
    location.href = url;
}

function submitClearFilter() {
    $("input:hidden#filter-tag").val('all');
    $("input:hidden#filter-recipient").val('all');
    $("input:hidden#filter-word").val('-no-');
    $("form#filter-form").submit();
}




/***** FEED FUNCTIONS *****/
function submitPostSend() {
    if($(".submit-preview .send-btn").hasClass("locked")) return false;
    $(".submit-preview .send-btn").addClass("locked");

    var message = $("#message").val();
    var date = $("input#deliv-date").val();
    var to  = $("#recip-email").getReceivers();
    var num = 0;
    var send_type = $("select#send_type option:selected").val();
    var is_anonymous = $("#is_anonymous").val();
    var allowed_num_for_anonymous = $("#allowed_num_for_anonymous").val();

    if(!Boolean(typeof to!='undefined' && to) || to.length<=0 || (typeof to == "string")){
        if(typeof to == "string") showMessage(to, "Alert");
        else showMessage("You must specify recipient(s)", "Alert");
        $(".submit-preview .send-btn").removeClass("locked");
        return false;
    }

    num = to.length;

    if(num > 25){
        showMessage("Only 25 recipients allowed at a time.", "Alert");
        $(".submit-preview .send-btn").removeClass("locked");
        return false;
    }

    if (is_anonymous == 1) {
        var sender_name  = $("#senders-name").val();
        var sender_email = $("#senders-email").val();
        var captcha_response = $("#recaptcha_response_field").val();
        var captcha_challenge = $("#recaptcha_challenge_field").val();

        if($.trim(captcha_response)==''){
            showMessage("Please enter the captcha words as you see them.", "Alert");
            $(".submit-preview .send-btn").removeClass("locked");
            $(".submit-preview .ajax_spinner").hide();
            return false;
        }

        if (!validateEmail(sender_email)) {
            showMessage("Error: The address in the \"From\" field is an an unrecognized format.", "Alert");
            $(".submit-preview .send-btn").removeClass("locked");
            return false;
        }

        if (num > allowed_num_for_anonymous) {
            showAnonsendError(2, true);
            $(".submit-preview .send-btn").removeClass("locked");
            return false;
        }

        $("input:hidden#sendcard_sender_name").val(sender_name);
        $("input:hidden#sendcard_sender_email").val(sender_email);
        $("input:hidden#captcha_response").val(captcha_response);
        $("input:hidden#captcha_challenge").val(captcha_challenge);
    }


    var to_formatted = new Array();
    for(var t in to){
        if(Boolean(typeof to[t].email!='undefined' && to[t].email))
            to_formatted.push(to[t].email);
    }

    $("input:hidden#sendcard_message").val(message);
    $("input:hidden#sendcard_to").val(to_formatted.join(", "));
    $("input:hidden#sendcard_date").val(date);
    $("input:hidden#sendcard_send_type").val(send_type);

    $("input:hidden#sendcard_subscribe").val( $("#news-opt-in").attr('checked') ? 1 : 0);
    $("input:hidden#sendcard_notify").val( $("#notify").attr('checked') ? 1 : 0);
    $("input:hidden#sendcard_send_copy").val( $("#send-copy").attr('checked') ? 1 : 0);
    $("input:hidden#sendcard_notify_miss").val( $("#notify-three-day").attr('checked') ? 1 : 0);

	//Convert to Military Time
	var time =  $("#time").val();
	if((time != "Now") && (time != "Midnight") && (time != "Noon")){
        var am = (time.substring(time.length-2)=="am") ? true : false;
        var h = parseInt(time.substring(0,2));
        if(time.length == 6) time = "0"+time;
		if(am){
			if(h == 12) h=0;
		} else {
			if(h < 12) h+= 12;
		}
		if(h < 10) h = "0"+h;
		time = h + time.substring(2,5);
	}
    $("input:hidden#sendcard_when").val(time);

    $(".submit-preview .ajax_spinner").show();

    var form_data = $('form#sendcard_form').serializeArray();

    $.ajax({
            'url': config.base_path + '/post/send',
            'async': false,
            'dataType': 'json',
            'type': 'post',
            'data': form_data,
            'success': function(data) {
                if (data.status == 'OK') {
                    var hash = data.hash;
                    location.href = "/post/confirm-send/" + hash;
                }
                else {
                    //popup.jqmHide();
                    var errNum = data.errorNum;
                    if (errNum == 3)
                        showCommonError();
                    else if(errNum == 100){
                        showMessage("There was an error sending your card. Please try again later.", "Alert");
                    }
                    else if(errNum == 200){
                        showMessage("The captcha you entered was incorrect.", "Alert");
                        Recaptcha.reload();
                    }
                    else
                        showAnonsendError(errNum, true);

                    $(".submit-preview .send-btn").removeClass("locked");
                    $(".submit-preview .ajax_spinner").hide();
                }
            }

        });

        return false;
}

function submitPostSendAfterLogin() {
     $("#is_anonymous").val(0);
    submitPostSend();
}





/*** AGE GATE ***/
function calculate_age_gate(birth_year, birth_month, birth_day) {
    var today_date = new Date();
    var today_year = today_date.getFullYear();
    var today_month = today_date.getMonth();
    var today_day = today_date.getDate();
    var age = today_year - birth_year;
    if ( today_month < (birth_month - 1)) age--;
    if (((birth_month - 1) == today_month) && (today_day < birth_day)) age--;
    return age;
}
function age_gate_me(age_gate_id, age_gate_ttl) {
    year = $('#age-year').val();
    month = $('#age-month').val();
    day = $('#age-day').val();
    if (year > 0 && month > 0 && day > 0) {
        var age = calculate_age_gate(year, month, day);
        if (age >= 21) age_gate_open(age_gate_id, age_gate_ttl, age);
        else $("#age-gate-error").html('Sorry, you have to be over 21 to view this section.').show();
    }
    return false;
}
function age_gate_open(age_gate_id, age_gate_ttl, age) {
    var gate_name = 'agegate_' + age_gate_id;
    var futdate = new Date();
    var expdate = futdate.getTime();
    age_gate_ttl = parseInt(age_gate_ttl);
    if(isNaN(age_gate_ttl)) age_gate_ttl = 0;
    if ((age_gate_ttl > 0)) {
        if(age_gate_ttl==9999) expdate += (60 * 15 * 1000);
        else expdate += (3600 * age_gate_ttl * 1000);
    }
    else expdate +=  ((3600*24*365)*1000);
    futdate.setTime(expdate);
    $.cookies.set(gate_name, age, { path: '/', expiresAt: futdate });

    $('#takeover_holder').show();
    $("#age-gate-overlay").remove();
}
function age_gate_check(age_gate_id){
    var gate_name = 'agegate_' + age_gate_id;
    if($.cookies.get(gate_name)) return true;

    var age_gate_user =  $.cookies.get('usrprof');
    if (age_gate_user && age_gate_user.d && age_gate_user.d.toString().indexOf('-')>0) {
        var user_dob = age_gate_user.b.split('-');
        if($.isArray(user_dob) && user_dob.length > 2){
            var age = calculate_age_gate(user_dob[0], user_dob[1], user_dob[2]);
            return (age >= 21);
        }
    }
    return false;
}
function initAgeGate(age_gate_id, age_gate_ttl) {
    if(age_gate_check(age_gate_id)){
        age_gate_open(age_gate_id, age_gate_ttl, age);
        return;
    }
    $(".extensionInstaller").hide();

    var age_gate_html = '<div id="age-gate-selecta"><h1>Age Restricted Area</h1><div id="age-gate-left">&nbsp;</div><div id="age-gate-form"><h2>Are you at least 21 years old and capable of using pulldown menus?<br />Excellent - just enter your date of birth to get started!</h2>';
    age_gate_html += '<div id="age-gate-inner"><form id="age-gate-keeper" method="post" onsubmit="return age_gate_me(' + age_gate_id + ', ' + age_gate_ttl + ');"><table cellpadding="5" cellspacing="0" border="0"><tr class="form-el labels"><td>MONTH</td><td>DAY</td><td>YEAR</td></tr>';
    age_gate_html += '<tr class="form-el fields"><td><select id="age-month" name="month" class="sep" style="min-width: 136px;"><option value="00"> </option><option value="01">January</option><option value="02">February</option>';
    age_gate_html += '<option value="03">March</option><option value="04">April</option><option value="05">May</option><option value="06">June</option><option value="07">July</option><option value="08">August</option><option value="09">September</option>';
    age_gate_html += '<option value="10">October</option><option value="11">November</option><option value="12">December</option></select></td><td><select id="age-day" name="day" class="sep" style="min-width: 66px;"><option value="00"> </option>';
    var currentMonth = 01; while (currentMonth < 32) { age_gate_html += '<option value="' + currentMonth + '">' + currentMonth + '</option>'; currentMonth++; }
    age_gate_html += '</select></td><td><select id="age-year" name="year" style="min-width: 86px;"><option value="00"> </option>';
    var currentYear = new Date().getFullYear(); currentYear -= 8; while (currentYear > 1930) { age_gate_html += '<option value="' + currentYear + '">' + currentYear + '</option>'; currentYear--; }
    age_gate_html += '</select></td></tr><tr class="form-el submit"><td colspan="3"><img src="http://static.someecards.com/someecards/sec/images/age-gate/btn_cancel.jpg" onclick="window.location.href = \'/\';" /><a href="#" id="submit_agegate"><img src="http://static.someecards.com/someecards/sec/images/age-gate/btn_submit.jpg" /></a></td></tr></table></form>';
    age_gate_html += '</div></div><div id="age-gate-right">&nbsp;</div>';
    age_gate_html += '<div id="age-gate-error"></div></div>';
    $('body').append('<div id="age-gate-overlay"></div>');
    $('#takeover_holder').hide();
    $('#age-gate-overlay').show().html(age_gate_html);

    $("#submit_agegate").unbind('click').click(function(e){
        e.preventDefault();
        if(parseInt($('#age-year').val())==0 || parseInt($('#age-month').val())==0 || parseInt($('#age-day').val())==0){
            $("#age-gate-error").html('Please enter your birthday.').show();
            return;
        }
        age_gate_me(age_gate_id, age_gate_ttl);
    });

}
