var config = {"base_path":""}
var currentPanel = 0;
var currentTimer;
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 popup_invite_guests = false;

jQuery.preloadImages = function(a){
  for(var i = 0; i<a.length; i++)
    jQuery("<img>").attr("src", a[i]);
}
var preload = new Array();
preload.push(s3_path+"/sec/images/headers/nav-bkgd.png");
preload.push(s3_path+"/sec/images/ico/icon_comp.png");

//$.preloadImages(preload);


//Global Functions

function validateEmail(e){
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(e);
}
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+100);
    else popup.css("top",window.pageYOffset+100);

    $(".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_data;
var g_logoutfirst;

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

function loadLoginPopup(callback, data, logoutfirst){
    //loadFBScript(function(){
        g_callback = callback;
        g_data = data;
        g_logoutfirst = logoutfirst;

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

        //if(!popup.hasClass("login")){
                $(".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).html("Log In &raquo;").unbind("click").click(function(){
                        submitPopup("login", callback, data, logoutfirst);
                        return false;
                });
                */
                //$(".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 (callback == "sendcard_anonymous_login")
                    qs.push("show_anonsend_message=1");
                if(Boolean(typeof data!='undefined' && data) &&
                   Boolean(typeof data.email!='undefined' && data.email) ){
                    qs.push("defemail="+data.email);
                }
                $(".content",popup).load("/static/popup-login.php?"+qs.join("&"), null, function(){
                    FBC.initFB();
                    $("#popup-login-submit-button .button",popup).html("Log In &raquo;").unbind("click").click(function(){
                            submitPopup("login", callback, data, logoutfirst);
                            return false;
                    });
                    $("#popup .fields .secloginfields input").keydown(function(e){
                        if(e.keyCode == 13) $("#popup-login-submit-button .button",popup).click();
                    });

                });
        //}

        var default_username = '';
        $.ajax({
            'url': config.base_path + '/user/remembername',
                'async': false,
                'dataType': 'text',
                'success': function(data) {
                if(data) {
                    default_username = data;
                }
            }
        });
        $("#popup-login-email").val(default_username);
        $(".close",popup).click(function(){ $("#popup").jqmHide(); });

        popup.jqmShow();
        return false;
    //});
}

function loginInvitesCallback(callback, data, cb_data){
    if(!callback) callback = '';
    callback = callback.toLowerCase();
    switch(callback){
        case "invite_attachcard":
        case "invite_inviteothers":
        case "invite_checkemail":
        case "invite_orgview":
            var curEm = $.trim((data.email).toLowerCase());
            var invEm = $.trim((cb_data["email"]).toLowerCase());
            if(curEm==invEm) reloadPage();
            else openLogoutPopup(invEm, curEm);
            break;
        case "invite_globalnav":
        case "invite_savenew":
            reloadPage();
            break;
        case "openinvitationsendpopup":
            updateGlobalNav(data.username);
            openInvitationSendPopup();
            break;
        case "sendcard_anonymous_login":
            submitSendAfterLogin();
            break;
        default:
            reloadPage();
            break;
        
    }

}

function loadFBTermsPopup(callback, cb_data){
    $.get(config.base_path + "/user/fbislinked", null, function(linkeddata, textstatus){
        if(linkeddata.status=="OK"){
            pageTracker._trackEvent('Login', 'FBConnect - Linked');
            switch(callback){
                case "quicksend":
                   updateGlobalNav(linkeddata.username);
                   $(".login-wrp").hide();
                   $("#qs-wrp .send-data").show();
                   $("#popup").jqmHide();
                    break;
                case 'sendcard_fbshare':
                    var h = location.hash;
                    if(h.indexOf("fbshare")>-1){
                        location.reload(true);
                        return false;
                    }
                    else{
                        var u = location.href;
                        u = u.substring(0, u.indexOf("#"));
                        u += "#fbshare";
                        location.href = u;
                        location.reload(true);
                        return false;
                    }
                    break;
                case "static_login":
                    location.href = cb_data.backurl;
                default:
                    loginInvitesCallback(callback, linkeddata, cb_data);
                    //reloadPage();
                    break;
            }
        }
        else if(linkeddata.status=="FAILED" && linkeddata.email=="proxy"){
            
            var popup = $("#popup");
            popup.css("position","absolute");
            if($.browser.msie) popup.css("top",document.documentElement.scrollTop+100);
            else popup.css("top",window.pageYOffset+100);

            $(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>")
            popup.removeClass().addClass("fbnoproxy");
            $("h3",popup).html('A Valid Email Address Is Required');
            $(".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();
                    FBC.logout();
                    $(this).attr("onclick", "location.href=this.href; return false;");
                    return false;
            }).show();

            $(".content",popup).load("/user/fbnoproxy", {}, function(){
                 $(".link-button .button",popup).html("Retry &raquo;").unbind("click").click(function(){
                    $("#popup").jqmHide();
                    $("div.link-button a.unsubscribe",popup).attr("onclick", "location.href=this.href; return false;");
                    FBC.login(function(){
                        loadFBTermsPopup(callback, cb_data);
                    });
                    return false;
                });
            });
            $(".close",popup).click(function(){ 
                $("#popup").jqmHide();
                    FBC.logout();
                $("div.link-button a.unsubscribe",popup).attr("onclick", "location.href=this.href; return false;");
            });
            popup.jqmShow();
            return false;
            
        }
        else {

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

            $(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>")
            popup.removeClass().addClass("fbtermsonly");
            $("h3",popup).html('Accept Terms <span class="onetime">(You only need to do this once)</span>');
            $("div.link-button a.unsubscribe",popup).hide();
            $(".link-button .need-account",popup).hide();

            $(".content",popup).load("/static/popup-login-fbagree.php", {}, function(){
                $(".link-button .button",popup).html("Finish &raquo;").unbind("click").click(function(){
                    if($(this).hasClass("disabled")) return false;
                    $(this).addClass("disabled");
                    if($("#popup .content #fbc_terms:checked").length<=0){
                        $(".fbc_termsonly_error", popup).html("You must agree to the Terms of Service.").show();
                        $(this).removeClass("disabled");
                        return false;
                    }
                    $(".link-button .button",popup).html("Finish &raquo;").unbind("click");
                    $(".fbc_termsonly_error", popup).hide();
                    $("#popup .link-button .ajax").show();
                    var news = ($("#popup .content #fbc_newsletter:checked").length>0);
                    $.post(config.base_path + "/user/fbajaxlogin", {newsletter:news}, function(data){
                        $("#popup .link-button .ajax").hide();
                        if(data.status=="OK") {
                            pageTracker._trackEvent('Login', 'FBConnect - Terms Popup');
                            switch(callback){
                                case "quicksend":
                                   updateGlobalNav(data.username);
                                   $(".login-wrp").hide();
                                   $("#qs-wrp .send-data").show();
                                   $("#popup").jqmHide();
                                    break;
                                default:
                                    //reloadPage();
                                    loginInvitesCallback(callback, data, cb_data);
                                    break;
                            }
                        }
                        else {
                            $("#popup").jqmHide();
                            showMessage(data.error, "Alert");
                            return;
                        }
                    }, "json");
                    return false;
                });
            });
            $(".close",popup).click(function(){ $("#popup").jqmHide(); });
            popup.jqmShow();
            return false;

        }
    }, 'json');

}

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(){
            if($("body").hasClass("invites") || $.find("#invites_div").length>0){
                if(Boolean(typeof guest_email!='undefined' && guest_email)){
                    loadLoginPopup("invite_orgview", {email:guest_email}, true);
                }
                else loadLoginPopup("invite_globalnav");
            }
            else loadLoginPopup();
        });
        $("#global-nav .global-logout").click(function(){
            $.get(config.base_path + "/user/ajlogout",null,function(data){
                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"){
                    loadFBScript(function(){
                        FBC.initFB();
                        FB.ensureInit(function() {
                            FBC.logout(function(){
                                if(is_profilepage){ location.href='/'; return false; }
                                else reloadPage();
                            });
                        });
                    });
                }
                else {
                    if(is_profilepage){ location.href='/'; return false; }
                    else reloadPage();
                }
            },"json");
        });

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

		$(".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();
		return false;
	});
	$("#global-nav .popup-register").click(function(){
		var popup = $("#popup");
		if($.browser.msie){
			popup.css("top",100);
		} else {
			popup.css("top",100);
		}
		
		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(){			
				submitPopup("register");
				return false;
			});
                        $(".link-button .button",popup).show();
			$(".content",popup).load("/static/popup-register.php",function(){
                                FBC.initFB();
				$("#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();
		return false;
	});
	$("#global-nav .popup-forgot").click(function(){
		var popup = $("#popup");
		if($.browser.msie){
			popup.css("top",document.documentElement.scrollTop+100);
		} else {
			popup.css("top",window.pageYOffset+100);
		}
		
		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();
		return false;
	});
	
}
function navOver(id){
    clearTimeout(navigationOutTimer);
    navigationTimer = setTimeout("$('.nav-dropdown').hide();showNav('"+id+"');overnavdelay=0;",overnavdelay);
}
function navOut(){
    navigationOutTimer = setTimeout("overnavdelay=250",500);
    clearTimeout(navigationTimer);
}
function initNav(){
	//Navigation Scripts
        $("#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();
	$(".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 updateGlobalNav(username){
	$("#global-nav div ul li:eq(0)").hide().next().hide().next().next().show().prev().show().find("a.name").html(username);
}
function submitPopup(type, callback, cb_data, 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 (rVal.status == "IMPORT REQUIRED") {
                                                    pageTracker._trackEvent('Login', 'Import Required');
                                                    $("h3", popup).html("Please wait while we build your inbox. This will only happen the first time you log in");
                                                    $(".content",popup).html("<span class='loading'><img src='/sec/images/ajax-loader.gif' /></span>");
                                                    $.ajax({
                                                        'url': config.base_path + '/user/importaccount',
                                                        'async': false,
                                                        'dataType': 'json',
                                                        'success': function(data) {
                                                            $(".content",popup).html("Import finished, thanks !");
                                                        }});
                                                }
                                                pageTracker._trackEvent('Login', 'Regular');
                                                if(loginVote){
                                                        $("body > .jqmOverlay").remove();
                                                        cardVote(loginVote);
                                                }
                                                else if(Boolean(typeof callback!='undefined' && callback)){
                                                    callback = callback.toLowerCase();
                                                    loginInvitesCallback(callback, rVal, cb_data);

                                                }
                                                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+100);
	} else {
		popup.css("top",window.pageYOffset+100);
	}
	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,
                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);
                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 {
                fbimg = thumb_data.img;
                imghtml = '<a href="'+thumb_data.href+'"><img src="'+thumb_data.img+'" alt="'+thumb_data.title+'" /></a>';
            }

            // 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);
            cardOverlayShow(thumb_id);
        },
        function(){
            cardThumbHit = false;
            cardOverlayHide();
        }
    );
}

function cardOverlayShow(thumb_id){
    if($("#cardthumb_overlay").is(":hidden")){
        if(overlay_tracking){
            var cid = $('#'+thumb_id).attr("id").substring(12),
                 card_type = 0;
            if($("body#someusercards").length>0) card_type = 1;
            else if($("body.invites").length>0) card_type = 2;
            $.get(config.base_path + "/card/track_overlay", { cid:cid, ctype:card_type });
        }
        clearTimeout(cardOverlayOutTimer);
        cardOverlayTimer = setTimeout("$('#cardthumb_overlay').show();cardOverlayDelay=0;",cardOverlayDelay);
    }
}
function cardOverlayPosition(thumb_id){
    var thumb = $('#'+thumb_id),
         pos = thumb.parent().position(),
         offset = thumb.offset(),
         leftOffset = pos.left,
         topOffset = offset.top-330;

    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 - 280;
    }

    $("#cardthumb_overlay").removeClass('video');
    if(thumb.hasClass("is_video")){
        $("#cardthumb_overlay").addClass('video');
        topOffset -= 40;
    }

    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);
        })
        .unbind("mouseleave").bind("mouseleave", function(){
            cardOverlayHit = false;
            cardOverlayHide();
        });

}
function cardOverlayHide(){
    clearTimeout(cardOverlayTimer);
    setTimeout('cardOverlayHide_timeout()', 10);
    $("#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");
    }
}


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

        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;
         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(),
                    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(!loggedin && 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;
        }
        else {
            params['card_id'] = card_id;
            params['card_type'] = card_type;
        }

        $.post(config.base_path+'/card/ajcomments', params, function(data){
            if(data.status=="OK"){
                toggleCommentsError(false);
                $("#comments_div ul li.be_first_comment").hide();
                $("#comments_div ul").append(data.comment_html).children(':last').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(!loggedin && 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();

    }
}



$(document).ready(function(){

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

    $("#senders-name").origText();
    $("#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();
            }
    });

    //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);
    });

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

            $(".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 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");
		var nextPanel=0;
		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);
				//$("#breaking-cards .controls a.pause").click();
				break;
			case "next":
				movePanel(1, true);
				//$("#breaking-cards .controls a.pause").click();
				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); movePanel( ($(this).html()-currentPanel-1), false);
                //pageTracker._trackEvent('Breaking Cards', 'Navigate', 'Clicked Panel: '+(currentPanel+1));
            });

        $("#breaking-cards .breakingcard_img").click(function(){
            var cl = $(this).attr("href");
            pageTracker._trackEvent('Breaking Cards', 'Click card', cl);
        });
	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));
                pageTracker._trackEvent('Card Detail Tab Click', $(this).html(), curLoc);

                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;
	});
}

function switchPanel_autoHash(){
    var curLoc = location.href;
    var locSplit = curLoc.split("#");
    var curTab = "email";
    if(locSplit.length > 1 && locSplit[1]!=""){
        curTab = locSplit[1].toLowerCase();
        //$("#mc .send-workflow .send-data-wrp .send-cat ul li").removeClass("active").removeClass("ieactive");
    }
    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";

    if (type.indexOf('comments') > -1) {
        //$("#login_tab").insertAfter("#commentstab_loginholder").show();
        $("#send-card-view div.send-data-wrp #comments_div").show();
        //$("#logintab_action").html("comment");
        tabId = "#send-card-view div.send-data-wrp #comments_tab";
    } else if (type.indexOf('email') > -1) {
        $("#login_tab").insertAfter("#emailtab_loginholder").show();
        $("#logintab_action").html("email cards");
        $("#send-card-view div.send-data-wrp div.send-data").show();
        tabId = "#send-card-view div.send-data-wrp #email_tab";
    } else if (type.indexOf('social') > -1) {
        $("#send-card-view div.send-data-wrp div.social-web").show();
    } else if (type.indexOf('link') > -1) {
        $("#send-card-view div.send-data-wrp div.embedperma").show();
        tabId = "#send-card-view div.send-data-wrp #linkembed_tab";
    } else if (type.indexOf('instant') > -1) {
        $("#send-card-view div.send-data-wrp div.im").show();
    } else if (type.indexOf('submit') > -1) {
        $("#send-card-view div.send-data-wrp div.submitcard").show();
        tabId = "#send-card-view div.send-data-wrp #submitcard_tab";
    } else if (type.indexOf('invite') > -1) {
        $("#send-card-view div.send-data-wrp #invites_div").show();
        tabId = "#send-card-view div.send-data-wrp #invites_tab";
    }

    $(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(){
		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){
					data = eval('('+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;
	});	
	
}

// Set the cookie
function setCookie(name, value, days, domain) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = ";expires="+date.toGMTString();
	} else {
		expires = "";
	}
	if(domain) var dom = ";domain="+domain;
	else dom="";
	document.cookie = name+"="+value+expires+dom+";path=/;";
}

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();
		data = eval('('+data+')');
		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");	
}

// Read the cookie
function readCookie(name) {
	var needle = name + "=";
	var cookieArray = document.cookie.split(';');
	for(var i=0;i < cookieArray.length;i++) {
		var pair = cookieArray[i];
		while (pair.charAt(0)==' ') {
			pair = pair.substring(1, pair.length);
		}
		if (pair.indexOf(needle) == 0) {
			return pair.substring(needle.length, pair.length);
		}
	}
	return null;
}

//.toggleText
jQuery.fn.origText = function(a) {
	return this.each(function() {
		var t = this.value;
		$(this).bind("blur",function(){ if(this.value=="") this.value=t; });
		$(this).bind("focus",function(){ if(this.value==t) this.value=""; });
	});
};

jQuery.extend( {
    equilize: function(a, b, min) {
		var hParam = (!min || ($.browser.msie && $.browser.version <= 7)) ? "height" : "min-height";
		var aH = ($(a).length==0) ? false : $(a).height();
		var bH = ($(b).length==0) ? false : $(b).height();
		if(!aH && !bH) return false;

		if(aH > bH){
			var div = $(b).children().filter(":last");
			if(div[0].tagName=="SCRIPT") div = div.prev();
                        div.css(hParam,div.height() + (aH-bH));
		} else {
			var div = $(a).children().filter(":last");
			if(div[0].tagName=="SCRIPT") div = div.prev();
                        div.css(hParam,div.height() + (bH-aH));		
		}
        return true;
    }
});

function ie_apply_zindex(element_id, zindex, context_id) {
   // default values
   if (undefined == zindex) { zindex = 1; }
   var context = (undefined == context_id) ? $(context_id) : $("body");
   var element = $(element_id);

   // find relative-positioned ancestors of element within context
   return element.parents().each(
      function(ancestor) {
         if ('relative' == $(this).css('position')) {
            // apply z-index to ancestor
            $(this).css({'z-index': zindex});
         }
         if ($(this) == context) { throw $break; }
      }
   );
}

function loadScript(sScriptSrc, callbackfunction){
    var oHead = document.getElementsByTagName('head')[0];
    if(oHead){
        var oScript = document.createElement('script');
        oScript.async = true;
        oScript.setAttribute('src',sScriptSrc);
        oScript.setAttribute('type','text/javascript');
        var loadFunction = function(){
            if (this.readyState == 'complete' || this.readyState == 'loaded')
                callbackfunction();
        };
        oScript.onreadystatechange = loadFunction;
        oScript.onload = callbackfunction;
        oHead.appendChild(oScript);
    }
}

function loadFBScript(callbackfunction){
  loadScript('http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US', callbackfunction);
}

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

function cleanObject(obj, key, defaultValue, smallerSize) {
    var flag = key + "_cleaned";
    var result = eval("typeof(" + flag + ") == 'undefined' ? 0 : 1");
    if (result == 0) {
        if (obj.value == defaultValue) {
            if (smallerSize)
                $(obj).css('font-size', '12px');
            obj.value = "";
        } else
            eval(flag + " = 1;");
    }
}

function unCleanObject(obj, key, defaultValue, smallerSize) {
    if (obj.value == '') {
        if (smallerSize)
            $(obj).css('font-size', '18px');
        obj.value = defaultValue;
    }
}




/**** 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?term=" + encodeURI(term);
        return false;
    }

    var category_id = $("select#search_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);

    if ($("#posts-checkbox").attr('checked')) {
        var term = $("#search").val();
        var sb_tags = (search_in_tags)?'&search_in_tags=1':'';
        var sb_txt = (search_in_text)?'&search_in_text=1':'';
        var inc_cat = (category_id!='')?'&search_category_id='+category_id:'';
        location.href= config.base_path + "/post/search?term=" + encodeURI(term) + inc_cat + sb_tags + sb_txt;
        return false;
    }
    else if ($("#search_invites").attr('checked')) {
       var action = '/invitations' + $("form#search_form").attr('action');
       category_id = $("select#search_invite_category_list option:selected").val();
       $("form#search_form").attr('action', action);
    }
    else if($("#more-search .options input#store").attr("checked")){
       term = term.replace(" ", "-");
       location.href= "http://www.cafepress.com/someecards/s_" + escape(kw);
       return false;
    }
    $("input:hidden#search_form_category_id").val(category_id);

    //$("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();
}
