/* This is the core Javascript file for all pages. */

var PJS = PJS || {};

(function() {

    function getBody() {
        return document.getElementsByTagName("body")[0];
    }

    function setOverlayMask(visible) {
        if (visible) {
            $("#overlay-mask").show();
        } else {
            $("#overlay-mask").hide();
        }
    }

    function isOverlayVisible(name) {
        return $("#" + name).is(':visible');
    }

    function beginsWith(string, text) {
        var pos = string.indexOf(text);
        if (pos === 0) {
            return true;
        } else {
            return false;
        }
    }

    var activeOverlay_ = null;

    function setActiveOverlay(overlay) {
        if (activeOverlay_) {
            hide(activeOverlay_);
        }
        show(overlay);
        activeOverlay_ = overlay;
    }

    function show_popup(popup_id, check_login, default_width) {
        popup_id = "#" + popup_id;
        
        if($(popup_id).is(":visible")) {
            return;
        }
        if (check_login === true || check_login === undefined) {
            ensure_logged_in();
        }
		if (!default_width || default_width === undefined ) {
			default_width = "720px"
		}
		
		$(popup_id).css("width", default_width);
        clearPopupError(popup_id);
        
        // offset = $(window).scrollTop();
        // $(popup_id).css('margin-top', 70 + offset);
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
        // Set height and width to mask to fill up the whole screen
        $('#popup-overlay-mask').css({
            'width': maskWidth,
            'height': maskHeight
        });
        $('#popup-overlay-mask').fadeTo('fast', 0.8);
        
        var winH = $(window).height();
        var winW = $(window).width();
        offset = $(window).scrollTop();
        // $(popup_id).css('top', winH/2-$(popup_id).height()/2);
        // $(popup_id).css('left', winW/2-$(popup_id).width()/2);
        $(popup_id).css('top', offset + 30);
		
        $(popup_id).css('left', winW / 2 - $(popup_id).width() / 2);

        //$(popup_id).fadeTo('fast', 1);
        $(popup_id).show();
        //centerPopup(popup_id);
		window.setTimeout(function() {
				if($(popup_id + " .first-focus")) {
					$(popup_id + " .first-focus").first().focus();
				}
			},
			300);

        $(document).bind("keydown.popup", function(e){
            if (e.keyCode == 27) {
                close_popup();
            }
        });
        
        return false;
    }

    function close_popup() {
        $(document).unbind("keydown.popup");
        $('#popup-overlay-mask').fadeOut('fast');
        $(".overlay").hide();
        hideLoadingPopup();
        return false;
    }


    function _closeOverlay() {
        setOverlayMask(false);
        $("body").removeClass("show-overlay");
        // removeclass(getBody(), "show-overlay");
        close_popup();
        return false;
    }

    function closeOverlay(delay) {
        if (delay) {
            window.setTimeout(function() {
                _closeOverlay();
            }, delay);
        } else {
            _closeOverlay();
        }
        return false;
    }

    function setCookie(c_name, value, expiredays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie = c_name + "=" + escape(value) + ((expiredays === null) ? "" : ";expires=" + exdate.toGMTString());
    }

    function getCookie(c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end === -1) {
                    c_end = document.cookie.length;
                }
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "0";
    }

    function isPopupVisible() {
        return $('#popup-overlay-mask').is(":visible");
    }

    function _show_flash_message(msg, msg_class, msg_timeout) {
        if ($(window).scrollTop() > 114) {
            $("#flash-message-box").css('position', 'fixed');
            $("#flash-message-box").css('top', "0");
        }

        if (!msg_class) {
            msg_class = "success-message";
        }
        $("#flash-message-box").show("fast");

        if (msg_class == "success-message") {
            $("#flash-message").removeAttr("error-message");
        } else {
            $("#flash-message").removeAttr("success-message");
        }
        $("#flash-message").attr('class', msg_class);
        $("#flash-message").prop('innerHTML', msg);

        if (msg_timeout != undefined && msg_timeout > 0) {
            window.setTimeout(function() {
                $("#flash-message-box").hide("fast");
            }, msg_timeout);
        }
        return false;
    }

    function flash_success_message(msg) {
        _show_flash_message(msg, 'flash-message-contents', 3500);

    }

    function flash_error_message(msg) {
        _show_flash_message(msg, 'flash-error-contents', 10000);
    }


    function showPopupSuccess(message, form_id) {
        if (isPopupVisible()) {
            var filter = "#dynamic-popup-container .flash-messages";
            if ($(filter).length > 0) {
                $(filter).prop('innerHTML', message);
                $(filter).removeClass('error-message');
                $(filter).addClass('success-message');
                $(filter).show();
            } else {
                flash_success_message(message);
            }
        } else {
            flash_success_message(message);
        }
    }

    function clearPopupError(form_id) {
        if (typeof(form_id) != "string") {
            return false;
        }
        var filter = form_id + " .error-messages";

        if ($(filter).prop('innerHTML')) {
            $(filter).prop('innerHTML', '');
            $(filter).hide();
        }

        filter = form_id + " .flash-messages";
        if ($(filter).prop('innerHTML')) {
            $(filter).prop('innerHTML', '');
            $(filter).hide();
        }

        filter = form_id + " .error-message";
        if ($(filter).prop('innerHTML')) {
            $(filter).prop('innerHTML', '');
            $(filter).hide();
        }
        
        $('.dynamic-popup-container').find(".error-messages").prop("innerHTML", '');
        
        return false;
    }

    function showPopupError(message, form_id) {
        if (isPopupVisible()) {
            var filter = "#dynamic-popup-container .error-messages, #popup-overlay-mask .flash-messages,  .overlay .error-messages";
            if ($(filter).length > 0) {
                $(filter).prop('innerHTML', message);
                $(filter).removeClass('success-message');
                $(filter).addClass('error-message');
                $(filter).show();
            } else {
                alert(message);
            }
        } else if (form_id) {
            
            var fe;
            if (typeof form_id == "string") {
                fe = $("#" + form_id);
                fe = "#" + form_id + "_div .error-messages";
                if ($(fe).length) {
                    $(fe).prop("innerHTML", message);
                    $(fe).show();
                } else {
                    flash_error_message(message);           
                }
            } else {
                flash_error_message(message);
            }
        } else {
            flash_error_message(message);
            // alert(message);
        }
        return false;
    }

    function centerPopup(popup_id) {
        popup_id = '#' + popup_id;
        // request data for centering
        var windowWidth = document.documentElement.clientWidth;
        var windowHeight = document.documentElement.clientHeight;
        var popupHeight = $(popup_id).height();
        var popupWidth = $(popup_id).width();
        plog('height ' + popupHeight);

        if (popupHeight < 10 || popupWidth < 10) {
            return;
        }
        if (popupHeight < 400) {
            popupHeight = 400;
        }

        var top = windowHeight / 2 - popupHeight / 2;
        if (top + popupHeight > windowHeight) {
            plog("window " + windowHeight + " too small.." + (top + popupHeight));
            top = windowHeight - popupHeight;
        }
        if (top < 0) {
            top = 10;
        }
        plog("top: " + top);
        // centering
        $(popup_id).css({
            "position": "absolute",
            "top": top,
            "left": windowWidth / 2 - popupWidth / 2
        });
        // only need force for IE6
        $("#popup-overlay-mask").css({
            "height": windowHeight
        });

    }

    function login_redirect(url) {
        ensure_logged_in();
        window.location = url;
    }

    function ensure_logged_in() {
        if (is_logged_in !== true) {
            url = "/signin?next=" + window.location
            window.location = url;
            throw "Login Required";
        }
    }


    function removeSomeContent(eid, type, deldiv) {
        ensure_logged_in();
        registerAJAXLoadingPopup();

		var trackstr;

		if(type == "comment") {
			url = "/comments/delete"
			trackstr = "comment_remove"
		} else {
	        url = '/challenge_question/delete_answer';			
			trackstr = "challenge_answer_remove"
		}
		data = 'eid=' + eid;
        
        $.ajax({
            url: url,
            type: "POST",
            dataType: 'json',
            error: ajaxError,
            data: data,
            success: function() {
                var mec = deldiv.closest(".main-entry-container");
                if (mec.length>0) {
                    deldiv.closest(".main-entry-container").fadeOut();
                } else {
                    var e = jQuery.Event("keydown");
                    e.keyCode=39; // right arrow
                    $(document).trigger(e);
                }
                $(document).trigger('moment_deleted', {eid: eid})
				track(trackstr);
            }
        });
        return false;
    }

    function loadChallengeMissionAnswer(question_eid, answer_eid) {
        var url = "/challenge_question/answer_details?question_eid=" + question_eid + "&answer_eid=" + answer_eid;
        load_with_indicator("#mission-answers", url);
        return false;
    }

    function getChallengeAnswerForm(eid) {
        ensure_logged_in();

        load_with_indicator('#challenge-question-form',
                            '/challenge_question/answer_form?question_eid=' + eid, function() {
            initChallengeAnswerForm();
        });
        return false;
    }

    function initChallengeAnswerForm(file_required) {
        
        //PJX.registerPJXForm()
        $("#message-body").maxChar(500, {indicator: "maxchar-remaining", label:""});

        return false;

        // TODO: Convert this to a generic image form uploader and
        // integrate with submitAJAXForm

        if (file_required == undefined) {
            file_required = true;
        } 
        
        // If there is no image file in the form (challenge question),
        // just  bind it to regular AJAXForm
        var formobj = $('form#challenge_answer_form');      
        if(formobj.find("input[type=file]").length == 0) {
            formobj.bind("submit", function() {
                submitAJAXForm(formobj);
                return false;
            });
            return false;
        }
        
		// Else...do file handler stuff
        if(qq.UploadHandlerXhr.isSupported()){           
            handlerClass = 'UploadHandlerXhr';                        
        } else {
            handlerClass = 'UploadHandlerForm';
        }
        
        // Create a file handler for image uploads
        var handler = new qq[handlerClass]({
            action: formobj.attr('action'),
            onProgress: function(id, fileName, loaded, total){
                
            },
            onComplete: function(id, fileName, response){
                $("#mission_preview").attr("src", "/img2/mission_image_placeholder.png");
                $("#form-spinner").hide();
                enableFormID("challenge_answer_form");
                
                if(response && !$.isEmptyObject(response) && !response.isError){
                    if(response.errorMessage) {
                        showPopupError(response.errorMessage);
						trackFormSubmit(formobj, "with image / error");
                    } else {
                        loadLatestFeedEntry()
                        //ajaxSuccess(response, "success", "#answer_form_div");
						trackFormSubmit(formobj, "with image / success");
                    }
                } else {
                    ajaxError(response.xhr);
					trackFormSubmit(formobj, "with image / error");
                    //showPopupError("An error occured :(")
                }
            }
        })
        
        // Bind with ajax image upload stuff
        $('form#challenge_answer_form').bind("submit", function(eventObject) {
            var formobj = $("form#challenge_answer_form");
            
            var imgfile = formobj.find("input[type=file]")[0];
            imgfile = imgfile.files[0];
            
            var formvars = formobj.serializeObjectSimple()
            
            disableFormID("challenge_answer_form");

            if (imgfile != undefined) {
                //$("#mission_preview").attr("src", "/img2/loading_small.gif");
                $("#form-spinner").show();
                var idx = handler.add(imgfile);
                handler.upload(idx, formvars);
            } else {
                if(file_required) {
                    alert("Please select a file to upload")
                } else {
                    submitAJAXForm("challenge_answer_form", null, loadLatestFeedEntry);
                }
            }
            return false;           
        })
        
        return false;
    }
    
    function initTodaysMoment() {
        var momentref = $("#todaymoment");
        momentref.click(function() {
            var txt = momentref.prop("innerHTML");
            var inputfield = $("#todaymoment-form").find('input[name=answer]');
			
            $("#todaymoment-form").show()
            inputfield.show();
            inputfield.prev(".ezpz-hint").hide();
            inputfield.attr('value', txt);
            
            $("#todaymoment-form").find('input[name=question_eid]').attr('value', momentref.attr("eid"))
            inputfield.focus();
            return false;
        });
    }


    function submitChallengeAnswerForm(form_id) {
        ensure_logged_in();
        $(form_id).find("input[type=submit]").attr("disabled", "disabled");
        return true;
    }

    function registerStatsLink() {
        $('.update-stats-href').live("click", function() {
                $("#dynamic-popup-container").css("width", "950px");
                var page=$(this).attr("page");
                fetchAJAXPopup('/checkin/stats_popup?page=' + page, function() {
                        initSelectToSlider();
                    })
                return false;
            });
    }
    
    function submitCheckinForm(form) {
        ensure_logged_in();
        registerAJAXLoadingPopup();

        submitAJAXForm(form, '', function(data, textStatus) {
            //$("#checkin-form-content").hide('fast');
            //ajaxSuccess(data, textStatus);
            //$("#checkin-grid-content").prop("innerHTML", data.html);
            _show_flash_message(data.html);
            PCHART.initChart(logged_in_euid);
            $("#checkin-grid-content").load('/checkin/checkin_grid');
            return false;
        });
        return false;
    }


    function submitComment() {
        registerAJAXLoadingPopup();

        try {
            ensure_logged_in();
            submitAJAXForm('comments_form', '', submitCommentSuccess);
            return false;
        } catch (ex) {
            return false;
        }
    }

    function removeCommentItem(eid, comment_this) {
        // Used for profile favorite comments
        registerAJAXLoadingPopup();
        ensure_logged_in();

        url = '/comments/do_delete';
        data = 'eid=' + eid;
        $.ajax({
            url: url,
            type: "POST",
            dataType: 'json',
            error: ajaxError,
            data: data,
            success: function(data, textStatus) {
                $(comment_this).closest(".comment-entry").hide('fast');
            }
        });
        return false;
    }


    function showEUIDPopup(popup_id, euid, max_popup_count) {
        max_popup_count = max_popup_count || 0;
        if (max_popup_count > 0) {

            popup_count = getCookie(popup_id);
            if (popup_count !== '' && popup_count > max_popup_count) {
                show_popup(popup_id);
                $('#' + popup_id + ' :form .user-euid').attr('value', euid);
                $('#' + popup_id + ' :form').submit();
            } else {
                if (popup_count == '') {
                    popup_count = 0;
                } else {
                    popup_count++;
                }
                setCookie(popup_id, popup_count);
            }
        }
        show_popup(popup_id);
        $('#' + popup_id + ' :form .user-euid').attr('value', euid);
    }

    function disableFormID(form_id) {
        if ($(form_id).is('button')) {
            $(form_id).attr('disabled', 'disabled');

        } else {
            var formobj;
            if (typeof(form_id) == "string") {
                formobj = $("#" + form_id);
            } else {
                formobj = $(form_id);
            }
            formobj.find('input:button, input:submit').attr('disabled', 'disabled');
        }
    }

    function enableFormID(form_id) {

        if ($(form_id).is('button')) {
            $(form_id).removeAttr('disabled');
        } else {
            var formobj;
            if (typeof(form_id) == "string") {
                formobj = $("#" + form_id);
            } else {
                formobj = $(form_id);
            }
            formobj.children().removeAttr('disabled');
            formobj.find('input:button, input:submit').removeAttr('disabled');

        }
    }

    function ajaxError(XMLHttpRequest, textStatus, errorThrown, form_id) {
        //alert('error: ' + XMLHttpRequest.status + ": " +
        //XMLHttpRequest.getResponseHeader("Content-Type"));
        //alert(XMLHttpRequest.responseText);
        //alert(XMLHttpRequest.getResponseHeader("Content-Type"));
        hideLoadingPopup();

        if (XMLHttpRequest.status == 500) {
            showPopupError("A server error occured. Please refresh the page and try again.");
        }
        if (XMLHttpRequest.getResponseHeader("Content-Type").indexOf('text/html') >= 0) {
            $("#" + form_id + "_div").prop('innerHTML', XMLHttpRequest.responseText);
        } else if (XMLHttpRequest.getResponseHeader("Content-Type").indexOf("application/json") >= 0) {
            try {
                var jr = eval("(" + XMLHttpRequest.responseText + ")");
                if (jr.errorMessage !== undefined) {
                    showPopupError(jr.errorMessage, form_id);
                } else {
                    showPopupError("An error occured while processing your request", form_id);
                }

            } catch (err) {
                alert("Invalid response received from server.");
                plog(XMLHttpRequest.responseText);
            }
        } else {
            showPopupError(XMLHttpRequest.responseText, form_id);
        }
        enableFormID(form_id);
    }

    function ajaxSuccess(data, textStatus, form_id) {
        //alert("success: " + data);
        hideLoadingPopup();
        var autoHidePopup = true;
        
        
        if (typeof data === "string" && data != '') {
            showPopupSuccess(data, form_id);
        } else if (typeof data === "object") {
            if (data.result) {
                data = data.result;
            }
            if (data.popupHtml !== undefined) {
                autoHidePopup = false;
                $("#dynamic-popup-container").prop("innerHTML", data.popupHtml);
                show_popup('dynamic-popup-container', false, data.popupWidth);
            } else if (data.successMessage !== undefined) {
                showPopupSuccess(data.successMessage, form_id);
            } else if (data.errorMessage !== undefined) {
                alert('Error: ' + data.errorMessage);
            } else if (data.newcomponent !== undefined) {
				$("#" + data.newcomponent_id).before(data.newcomponent)
				$(form_id)[0].reset();
                $('.containsRemoveX').showXOnHover();

				//$(".hoverX").removeWithConfirmationHover(removeSomeContent);
			}
            
            if(data.formContent) {
                $(form_id).prop("innerHTML", data.formContent);                 
            }

            if (data.redirect) {
                window.location = data.redirect;
            } else if (data.reload) {
                window.location.reload();
            }
        }

        if (autoHidePopup && isPopupVisible()) {
            closeOverlay(1500);
        }
        // enableFormID(form_id);
    }

    function ajaxCallback(responseText, textStatus, XMLHttpRequest) {
        if (textStatus != 'success') {
            alert("Error: " + responseText);
        }
    }



    function fetchAJAXFormResponse(data, textStatus, onLoad) {
        if (data.html) {
            show_popup('dynamic-popup-container', false, data.popupWidth);
            $("#dynamic-popup-container").prop('innerHTML', data.html);
            $(".hinted").ezpz_hint();
            //$('.textbox-hint').tbHinter({class_name: 'greyed'});
			
            if (onLoad) {
                onLoad();
            }
            $("#dynamic-popup-container .first-focus").focus();
	    if(data.pickvcallback) {
		eval(data.pickvcallback);
	    }
	    try{
	        FB.XFBML.parse(); 
	    }catch(ex){}
    
        }
    }

    function showLoadingPopup() {
        $('#loading-popup-overlay-mask').show();
        $('#loading-popup').show();
    }

    function hideLoadingPopup() {
        $('#loading-popup-overlay-mask').hide();
        $("#loading-popup").hide();
    }

    function registerAJAXLoadingPopup() {
        $("#loading-popup").ajaxStart(function() {
            // showLoadingPopup();
            centerPopup("loading-popup");
            $("#loading-popup").show();
        });
        $("#loading-popup").ajaxStop(function() {
            // hideLoadingPopup();
            $("#loading-popup").hide();
            $("#loading-popup").unbind("ajaxStart");
        });
    }
    function load_dynamic_popup(url, data) {
		$("#dynamic-popup-container").css("width", "600px");
        $("#dynamic-popup-container").load(url, data);
        show_popup('dynamic-popup-container', check_login = false);
        return false;
    }
	
    function fetchAJAXPopup(url, onLoad) {
        ensure_logged_in();
        //registerAJAXLoadingPopup();
        // plog(url);
        $.ajax({
            url: url,
            type: "GET",
            dataType: 'json',
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if(XMLHttpRequest.status==404) {
                    alert("Not found!");
                } else {
                    alert("An error occured while performing this action. Please try again later.");
                    closeOverlay();
                }
            },
            success: function(data, textStatus) {
                fetchAJAXFormResponse(data, textStatus, onLoad);
                //registerDynamicTooltip();
				if(url) {
					var surl=url;
					if(url.indexOf("?") > 0) {
						surl = url.substring(0, url.indexOf("?"));
					}
					track("fetchPopup" + surl, "click");
				}
            }
        });

        return false;
    }

    function loadNewWish() {
        var current = $(this);
        var newWishDiv = $("#wishes-container");
        //newWishDiv.find(".loading").show();
        var listname = $("#list_eid").val();
        $.ajax({
            url: "/wishlist/load_new_wish",
            type: "GET",
            data: "list_eid="+listname,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                //ajaxError(XMLHttpRequest, textStatus, errorThrown, id);
                alert("Error adding wish image. Please refresh page.");
            },
            success: function(data, textStatus) {
                newWishDiv.html(data.html);
            }
        });
    }

    function getFacebookInstr(url) {
        $('#discount-form').hide();
        $('#facebook-instr').find(".readonly-url-box").attr('value',url);
        $('#facebook-instr').show();
    }

    function loadLatestFeedEntry() {
        var feedcomponent = $("#feed_div_content");
        feedcomponent.find(".loading").show();
        $.ajax({
            url: "/feed/load_feed?page=1&limit=1",
            type: "GET",
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                ajaxError(XMLHttpRequest, textStatus, errorThrown, id);
            },
            success: function(data, textStatus) {
				$("#empty-feed-div").hide();
                feedcomponent.find(".loading").hide();
                feedcomponent.prepend(data.html);
                //registerFeedEvents();
				postFeedLoad();
            }
        });
    }
    function loadFeedPage(isPublic, isAutoLoad) {
        var page = $("#feed_div").attr("page");
        var feedUrl = "";
        if (isPublic && !isAutoLoad)
            feedUrl = "/feed/public_feed?limit=4&page=";
        else if (isPublic && isAutoLoad)
            feedUrl = "/feed/public_feed?limit=16&page=";
        else
            feedUrl = "/feed/load_feed?page=";
        
        $.ajax({
            url: feedUrl+page,
            type: "GET",
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                ajaxError(XMLHttpRequest, textStatus, errorThrown);
            },
            success: function(data, textStatus) {               
                $("#feed_div").show();
                $("#feed_div_content").append(data.html);
                $("#feed_div_content").find(".loading").hide();
                if(data.next_page && data.next_page>0) {
                    $("#feed_div").attr("page", data.next_page);
                } else {
                    $("#feed_div").hide();
                }
                // if the request is not from logged out feed
                if ((isPublic && isAutoLoad) || !isPublic)
                    registerFeedEvents();               

                // rebind handler for autoloading pub stream
                if (isPublic && isAutoLoad && data.next_page > 2)
                    $(window).bind('scroll', scrollHandler);
                    
            }
        });
    }
    
	function postFeedLoad() {
        //$(".hoverX").removeWithConfirmationHover(removeSomeContent);
        $('.containsRemoveX').showXOnHover();
		$(".removeX").removeWithConfirmation(removeSomeContent);
		$(".feed-dropdown").optioneMenu();
		$(".likeable_entity").likeUnlike();
		resetForm("#challenge_answer_form");
		
	}

	
    function registerFeedEvents() {
		postFeedLoad();
        //initPrettyPhoto();
		
		$("textarea").autogrow().live("focus", function () {
				$(this).siblings('input[type=submit], .explain').show();	
			});
		
        if($("body").data('registeredFeedEvents') != "1") {
    		$("body").data('registeredFeedEvents', "1");
            /*
            $('.ajax-form').live("submit", function() {
                    return submitAJAXForm(this)
                });
            */
            $(".commentable_entity").live("click", function() {
                    ensure_logged_in()
                    var entity_id = $(this).attr("entity_id");
                    var formdiv = $("#formdiv-" + entity_id);
                    formdiv.show().find("textarea").focus();
                    return false;
                });
        }
        
		
	}
    function resetForm(form_selector) {
		if($(form_selector).length == 0) {
			return false;
		}
    
        $(form_selector)[0].reset();
        $(form_selector).find(".hidden-when-inactive").hide();
        
        // ezpz-hint gets cleared when the form is reset.. set the values again
        $(form_selector).find(".hinted[name!='ezpz_hint_dummy_input']").each(function() {
            var txt = $(this).attr('title');
            $(this).prev('.ezpz-hint').val(txt);
        });
        
        return false;
    
        $(':input',form_selector)
            .not(':button, :submit, :reset, :hidden, .ezpz-hint')
            .val('')
            .removeAttr('checked')
            .removeAttr('selected');
        
    }
    
    function load_with_indicator(id, url, onload) {
        $(id).show();
        registerAJAXLoadingPopup();
        $.ajax({
            url: url,
            type: "POST",
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                ajaxError(XMLHttpRequest, textStatus, errorThrown, id);
            },
            success: function(data, textStatus) {
                if (typeof data === "string" && data != '') {
                    $(id).prop("innerHTML", data);
                } else {
                    $(id).prop("innerHTML", data.html);
                }
                $(".hinted").ezpz_hint();
                if (onload) {
                    onload();
                }
                return false;
            }
        });
        //$(id).load(url);
        return false;
    }

    function submitAJAXForm(form_id, url, onSuccess, postSuccess) {
        var sform;
        if (typeof form_id == "string") {
            sform = $("#" + form_id);
        } else {
            sform = $(form_id);
        }
        registerAJAXLoadingPopup();
        clearPopupError(form_id);
        disableFormID(form_id);

        if (url == "" || url == undefined || url == null) {
            url = sform.attr("action");
            plog("submit log: " + url + " for sform: " + sform);
        }
        
        $.ajax({
            url: url,
            type: "POST",
            dataType: 'json',
            data: sform.serialize(),
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                enableFormID(form_id);
				trackFormSubmit(sform, "error");
                ajaxError(XMLHttpRequest, textStatus, errorThrown, form_id);

            },
            success: function(data, textStatus) {
                enableFormID(form_id);
				
				trackFormSubmit(sform, "success")
				
                if(typeof data === "object" && data.is_error) {
                    showPopupError(data.errorMessage, form_id);
                    return false;
                }
                
                if (onSuccess) {
                    onSuccess(data, textStatus, form_id);
                } else {
                    ajaxSuccess(data, textStatus, form_id);
                    if (postSuccess) {
                        postSuccess();
                    }
                }
            }
        });
        return false;
    }

    function initWebcam() {
        // alert('initWebcam');
        webcam.set_api_url('/change_thumbnail/do_webcam');
        webcam.set_quality(90); // JPEG quality (1 - 100)
        webcam.set_shutter_sound(true, "/swf/shutter.mp3"); // play shutter
        // click sound
        webcam.set_swf_url('/swf/webcam.swf');
        webcam.set_hook('onError', 'webcamError');
        webcam.set_hook('onLoad', 'webcamLoaded');
        webcam.set_hook('onComplete', 'uploadWebcamComplete');
    }

    function loadWebcam() {
        // alert("webcam loading");
        $("#webcam_component").prop('innerHTML', webcam.get_html(320, 240));
    }

    function uploadWebcam() {
        // upload to server
        $('#webcam_status').prop('innerHTML', '<h2><img src="/img/loading.gif" style="height: 25px; vertical-align: middle;" />&nbsp;Uploading...</h2>');
        webcam.upload();
    }

    function uploadWebcamComplete(msg) {
        document.location = "/profile";
    }

    function webcamError(msg) {
        alert("Error: " + msg);
    }

    function webcamLoaded(msg) {
        $("#capturebtn").removeAttr('disabled');
    }

    /* PHOTO VIEWER START */

    function showPhotoOverlay(img_this, image_id) {
        pic = $(img_this);

        // Get the image src
        if (!pic.is("img")) {
            pic = pic.find("img");
        }

        // Replace thumbnail url with regular (medium) url
        src = pic.attr("src");
        src = src.replace("t_", "m_");
        src = src.replace("t.jpg", "m.jpg");

        pic_container = pic.parents('.photo-popup-container');
        euid = pic_container.attr('euid');
        username = pic_container.attr('username');

        show_popup("photo-overlay", false);

        $("#photo-overlay-username").prop('innerHTML', username);
        $("#photo-overlay-image").attr("src", src);
        $("#photo-overlay-flag-info").hide();

        var data_map = {
            'euid': euid,
            'current_image_id': image_id
        };
        $("#photo-overlay-nav").load("/photos/overlay_nav", jQuery.param(data_map), ajaxCallback);

        return false;
    }

    function showPhoto(index) {
        image_index = index;
        image_url = getPhotoURL(photo_ids[index]);
        $("#photo-overlay-image").attr("src", image_url);
        printPhotoInfo(image_index, euid, photo_ids);
    }

    function printPhotoInfo() {
        $("#photo-nav-info-box").text('(' + (image_index + 1) + " of " + photo_ids.length + ')');
        curr_photo = photo_ids[image_index];

        if (is_logged_in && logged_in_euid == euid) {
            if (image_index > 0) {
                $("#manage_photo_form_iid").attr("value", curr_photo);

                $("#flag_user_form_div").hide();
                $("#manage_photo_form").show();
                $("#photo_is_thumbnail").hide();
            } else {
                $("#flag_user_form_div").hide();
                $("#manage_photo_form").hide();
                $("#photo_is_thumbnail").show();
            }
        } else {
            $("#manage_photo_form").hide();
            $("#flag_user_form_div").show();
            $("#photo_is_thumbnail").hide();

            $("#flag_photo_form_euid").attr("value", euid);
            $("#flag_photo_form_iid").attr("value", curr_photo);

        }
    }

    function peekIndex(incr_val) {
        var ii = image_index + incr_val;
        if (ii >= photo_ids.length) {
            ii = 0;
        }
        if (ii < 0) {
            ii = photo_ids.length - 1;
        }
        return ii;
    }

    function preLoadPhoto(index) {
        $.get(getPhotoURL(photo_ids[index]));
    }

    function getPhotoURL(photo_id) {
        var id_str = "";
        if (photo_id === 0 || photo_id === "0") {
            id_str = "";
        } else {
            id_str = "_" + photo_id;
        }

        var image_url = img_base + "/" + euid + "/m" + id_str + ".jpg";
        return image_url;
    }

    function showNextPhoto() {
        $("#photo-overlay-image").attr("src", "/img/loading.gif");

        showPhoto(peekIndex(1));
        preLoadPhoto(peekIndex(1));
    }

    function showPrevPhoto() {
        showPhoto(peekIndex(-1));
        preLoadPhoto(peekIndex(-1));
    }

    /* PHOTO VIEWER END */

    function keyHandler(e) {
        if (e.keyCode == 37) {
            // left
            if (isOverlayVisible('photo-overlay')) {
                showPrevPhoto();
            }
            if ($("#prev_answer").length > 0) {
                $("#prev_answer").trigger("click");
            }
        } else if (e.keyCode == 39) {
            // right
            if (isOverlayVisible('photo-overlay')) {
                showNextPhoto();
            }
            if ($("#next_answer").length > 0) {
                $("#next_answer").trigger("click");
            }

        } else if (e.keyCode == 27) {
            closeOverlay();
        }
    }


    function confirmedAction(deldiv, delfunction) {
        ds = $(deldiv).closest(".confirm-action-span");
        ds_html = ds.prop('innerHTML');
        plog(ds_html);
        ds.prop('innerHTML', "Are you sure? <a href='#' id='action_yes'>Yes</a> / <a href='#' id='action_no'>No</a>");
        ds.find('#action_yes').click(function() {
            delfunction();
        });
        ds.find('#action_no').click(function() {
            ds.prop('innerHTML', ds_html);
        });
        return false;
    }


    function plog(sval) {
        //console.log(sval);
    }


    window['ellipsizeToggle'] = function ellipsizeToggle(comp) {
        more_div = $(comp).siblings('.more_content');
        if (more_div.is(':visible')) {
            more_div.hide();
            comp.prop('innerHTML', '...more');
        } else {
            more_div.show();
            comp.prop('innerHTML', '...less');
        }
        return false;
    }

    function initSelectToSlider(auto_submit) {
        
		$.each($('.jq_slider'), function() {
			var sname = $(this).attr("sname");
			var smin = parseInt($(this).attr("min"));
			var smax = parseInt($(this).attr("max"));
			var sval = parseInt($(this).attr("val"));
			
			auto_submit = false;
			
			$(this).slider({
				value:sval,
				min: 0, 
				max: smax,
				slide: function( event, ui ) {
					$( "#sliderval_" + sname ).val(ui.value);
                    $(this).parents('form').removeAttr("unchanged");
                    
                    if(auto_submit) {
                        $(this).parents('form').submit();
                    }
				}
			});
		})
		
		return false;
    }
    window["initSelectToSlider"] = initSelectToSlider

    window["initSlider"] = function(slider_id) {
        if (!slider_id) slider_id = "#slider"
        $(document).ready(function() {
            $(slider_id).easySlider({
                auto: true,
                continuous: true,
                pause: 10000
            });
        });
    };


    function highlightAndFade() {
        $(".highlight-and-fade").animate({
            backgroundColor: "#387db9",
            color: "white"
        }, "slow");
        $(".highlight-and-fade").animate({
            backgroundColor: "white",
            color: "black"
        }, "slow");
    }


    function openPopup(url, title, width, height) {
        var left = (screen.width - width) / 2;
        var top = (screen.height - height) / 2;
        var params = 'width=' + width + ', height=' + height;
        params += ', top=' + top + ', left=' + left;
        params += ', directories=no';
        params += ', location=no';
        params += ', menubar=no';
        params += ', resizable=no';
        params += ', scrollbars=no';
        params += ', status=no';
        params += ', toolbar=no';
        newwin = window.open(url, title, params);

        if (window.focus) {
            newwin.focus()
        }
        return false;
    }
    
	function trackFormSubmit(form_selector, type) {
		var form_name;
		if(form_selector) {
			form_name = form_selector.attr("atag");
			if(!form_name) {
				form_name = form_selector.attr("id");
			}
			if(!form_name) {
				form_name = form_selector.attr("action");
			}
		}
		form_name = form_name + "/" + type;
		track(form_name, "click");
	}
	function registerTrackedLinks() {
		$("a.tracked").click(function() {
			var atag = $(this).attr("atag");
			track(atag, "click");
		});
	}
	
    function track(event_name, event_type) {
        if(window._kmq) {
			//console.log("KM event " + event_name)
            _kmq.push(['record', event_name]);
        }

        if(window.mpmetrics) {
            if (is_logged_in && logged_in_euid) {
                mpmetrics.identify(logged_in_euid);
            }
            
            if(event_type) {
                mpmetrics.track(event_name, {'type': event_type});
                //console.log("Track:" + event_name + ", type: " + event_type);
            } else {
                mpmetrics.track(event_name);
                //console.log("Track:" + event_name);
            }
        }
        
		
        if(window._gaq) {
            _gaq.push(['_trackEvent', event_name, event_type]);
        } 
        
        if(window.clicky) {
            if(event_type) {
                clicky.log("#"+ event_name);
            } else {
                clicky.log("#"+ event_name, event_name, event_type);
            }
			//clicky.pause();
        }
    }
    
	function initQuizForm() {
		$('#quiz-form').formToWizard({
				submitButton: 'quiz-submit',
				textNext: 'Next >',
				textPrev: '< Back',
				showNext: false,
				radioIsNext: true
			})		
	}
    
    function initPrettyPhoto() {
            $("a[rel^='prettyPhoto']").prettyPhoto({
                slideshow: 5000,
                autoplay_slideshow:false,
                overlay_gallery: false,
                animation_speed:'fast',
                social_tools: '',
                deeplinking: false,
                markup: '<div class="pp_pic_holder"> \
                        <div class="ppt">&nbsp;</div> \
                        <div class="pp_top"> \
                            <div class="pp_left"></div> \
                            <div class="pp_middle"></div> \
                            <div class="pp_right"></div> \
                        </div> \
                        <div class="pp_content_container"> \
                            <div class="pp_left"> \
                            <div class="pp_right"> \
                                <div class="pp_content"> \
                                    <div class="pp_loaderIcon"></div> \
                                    <div class="pp_fade"> \
                                        <a href="#" class="pp_expand" title="Expand the image">Expand</a> \
                                        <div class="pp_hoverContainer"> \
                                            <a class="pp_next" href="#">next</a> \
                                            <a class="pp_previous" href="#">previous</a> \
                                        </div> \
                                        <div id="pp_full_res"></div> \
                                        <div class="pp_details"> \
                                            <p class="pp_description"></p> \
                                            <a class="pp_close" href="#">Close</a> \
                                        </div> \
                                    </div> \
                                </div> \
                            </div> \
                            </div> \
                        </div> \
                        <div class="pp_bottom"> \
                            <div class="pp_left"></div> \
                            <div class="pp_middle"></div> \
                            <div class="pp_right"></div> \
                        </div> \
                    </div> \
                    <div class="pp_overlay"></div>',
                
            });
    }
    
	function reload() {
		window.location.reload();
	}
    window["loadFeedPage"] = loadFeedPage;
    window["initPrettyPhoto"] = initPrettyPhoto;
    window["track"] = track;
	window["registerTrackedLinks"] = registerTrackedLinks;
    window["openPopup"] = openPopup;


    window["highlightAndFade"] = highlightAndFade;


    window["printPhotoInfo"] = printPhotoInfo;
    window["showNextPhoto"] = showNextPhoto;
    window["showPrevPhoto"] = showPrevPhoto;
    window["showPhotoOverlay"] = showPhotoOverlay;

    window["closeOverlay"] = closeOverlay;
    window["fetchAJAXPopup"] = fetchAJAXPopup;
    window["submitAJAXForm"] = submitAJAXForm;
    window["showPopupError"] = showPopupError;
    window["load_dynamic_popup"] = load_dynamic_popup;
    window["show_popup"] = show_popup;
    window["close_popup"] = close_popup;
    //window["toggleTab"] = toggleTab;

    window["removeSomeContent"] = removeSomeContent;
    window["loadChallengeMissionAnswer"] = loadChallengeMissionAnswer;
    window["getChallengeAnswerForm"] = getChallengeAnswerForm;
    window["submitChallengeAnswerForm"] = submitChallengeAnswerForm;

    window["submitCheckinForm"] = submitCheckinForm;
    //window["removeCheckin"] = removeCheckin;
    

    window["submitComment"] = submitComment;
    //window["submitCommentSuccess"] = submitCommentSuccess;
    window["removeCommentItem"] = removeCommentItem;

    window["initWebcam"] = initWebcam;
    window["uploadWebcamComplete"] = uploadWebcamComplete;
    window["loadWebcam"] = loadWebcam;
    window["uploadWebcam"] = uploadWebcam;
    window["webcamLoaded"] = webcamLoaded;
    window["webcamError"] = webcamError;

    window["confirmedAction"] = confirmedAction;

    window["ensure_logged_in"] = ensure_logged_in;
    window["beginsWith"] = beginsWith;
    window["login_redirect"] = login_redirect;

    window["registerAJAXLoadingPopup"] = registerAJAXLoadingPopup;

    window["showEUIDPopup"] = showEUIDPopup;
    //window["registerDynamicTooltip"] = registerDynamicTooltip;
    window["load_with_indicator"] = load_with_indicator;
    
    window["initChallengeAnswerForm"] = initChallengeAnswerForm;
    window["registerFeedEvents"] = registerFeedEvents;
    window["initTodaysMoment"] = initTodaysMoment;

	PJS.ajaxSuccess = ajaxSuccess;
	PJS.showPopupError = showPopupError;
	PJS.ajaxError= ajaxError;
	PJS.loadLatestFeedEntry = loadLatestFeedEntry;
	PJS.loadNewWish = loadNewWish;
	PJS.getFacebookInstr = getFacebookInstr;
	PJS.postFeedLoad = postFeedLoad;
	PJS.reload = reload;
    
    PJS.registerStatsLink = registerStatsLink;
	PJS.trackFormSubmit = trackFormSubmit;
	PJS.initQuizForm = initQuizForm;

})();

