/* prevent console.* chokes */
if (typeof window.console == "undefined") {
    window.console = {
        log: function () {},
        group: function () {},
        error: function () {},
        warn: function () {},
        groupEnd: function () {}
    };
}

/* constants */
var PROGRESS_MAX = 258,
    hash, xhr_profile;

function isUndefined(object) {
    return typeof object === 'undefined';
}
function log(str) {if (!isUndefined(console)) {console.debug(str);}}

// return true if the current page is contained by a frame in another doc
// NB it would be preferable to use the fb_sig_in_iframe query string parameter
// here, but this is not passed to all requests, just the initial one. We could
// set a cookie, but that would last longer than the session.
function inFrame() {return top !== self;}

function insertParam(path, key, value) {
    key = escape(key); value = escape(value);
    var kvp = path.split('&'),
        i = kvp.length,
        x;
    while(i--){
        x = kvp[i].split('=');
        if (x[0]==key) {
            x[1] = value;
            kvp[i] = x.join('=');
            break;
        }
    }
    if (i<0) {kvp[kvp.length] = [key,value].join('=');}
    return kvp.join('&');
}

function trim(s) {
    return s.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function show_loader() {
    $("div.loading").show();
}

function hide_loader() {
    $("div.loading").hide();
}

function closeJqm() {
    $(this).closest('div.jqmWindow').jqmHide();
    $('body').css({overflow: 'auto'});
    return false;
}

function openDialog() {
    var $dialog = $('#dialog');
    $('body').css({overflow:'hidden'});
    $dialog.find('hr + div').remove();
    $dialog.jqmShow();
    $dialog.find('hr').after('<div id="dialog_body"></div>');
}

function dialogScrollfix(dialogId) {
    var $d, $d_content, dff = 40,
        minHeight = $(window).height() - 38;
    if (isUndefined(dialogId)) {
        dialogId = 'dialog';
        $d_content = $('#dialog_content');
        dff = 18
    }
    $d = $('#' + dialogId);
    if (isUndefined($d_content)) {
        $d_content = $d.children('div.content').first().show();
    }
    $d_content.css('height', 'auto');
    $d.css('height', 'auto');
    window.setTimeout(
        function() {
            if (minHeight < $d.height()) {
                $d.css('height', minHeight + "px");
                $d_content.css({'height': ($d.height() - dff) + "px", 'overflow-y': 'auto'});
                $d.animate({'top': '8px'}, 200);
            }
        }, 1);
}

function resizeDialog(width, animated, dialogId) {
    var style, $dialog, $content, $loader;
    if (isUndefined(animated)) {
        animated = false;
    }
    if (isUndefined(dialogId)) {
        dialogId = 'dialog';
    }
    style = {"margin-left": -1 * ((width + 20) / 2 + 1) + "px", "width": width + "px"};
    $dialog = $('#' + dialogId);
    if (animated) {
        $content = $dialog.find('div.content');
        $content.hide();
        $dialog.append('<div class="resize-overlay content" class="content"><img src="/media/img/ajax-loader.gif" alt="Loading..." title="Loading..." /></div>');
        $dialog.animate(style, 300, function(){
            $loader = $dialog.children('div.resize-overlay');
            $loader.css({'position': 'absolute', 'top': '10px', 'left': '10px',
                'width': $loader.width(), 'height': $loader.height(),
                'border-bottom-width': 0
            });
            $content.slideDown(300, function () {
                if ($dialog.is(':visible')) {
                    dialogScrollfix($dialog.attr('id'));
                }
            });
            setTimeout(function(){
                $loader.remove();
            }, 100);
        });
    } else {
        $dialog.css(style);
    }
}

function updateDialog(content) {
    $("#dialog hr + div").remove();
    $("#dialog hr").after('<div id="dialog_body"></div>');
    $("#dialog_body").html(content);
    dialogScrollfix();
}

function closeDialog() {
    $("#test_progress").remove();
    $("body").css({overflow:'auto'});
    $("#dialog").attr("class", "jqmWindow jqmID1");
    resizeDialog(680);
    $("#dialog").jqmHide();
	$(window).trigger('closed.dialog');
    return false;
}

function actionDialog() {
    var $close_btn = $('#close-dialog-btn');
    $close_btn.attr('src', '/media/img/close_grey.gif');
    $close_btn.bind({
        'mouseenter.actionDialog': function() {
            $close_btn.attr('src', '/media/img/close.gif');
        },
        'mouseleave.actionDialog': function() {
            $close_btn.attr('src', '/media/img/close_grey.gif');
        },
        'click.actionDialog': function() {
            $close_btn.attr('src', '/media/img/close.gif');
            $close_btn.unbind('.actionDialog');
        }
    });
}

function scrollfixJqm() {
    var i, id, $jqm;
    for (i=0; i<=5; i++) {
        id = 'jqmID' + i + ':visible';
        $jqm = $('div.' + id);
        if ($jqm.length === 1) {
            dialogScrollfix($jqm.attr('id'));
        }
    }
}

function closeJqms() {
    var i, id, $jqm;
    for (i=0; i<=5; i++) {
        id = 'jqmID' + i + ':visible';
        $jqm = $('div.' + id);
        if ($jqm.length === 1) {
            $jqm.jqmHide();
        }
    }
}

function handleJSONResponse(data, textStatus, XHR) {
    if (data.type === 'call') {
        var args = eval(data.args);
        window[data.func](args);
    } else if (data.type === 'redirect') {
        window.location.replace(data.url);
    } else if (data.type === 'dialog') {
        resizeDialog(data.size);
        $('#dialog').addClass(data.classes);
        openDialog();
        updateElement(data.html);
        actionDialog();
    } else if (data.type === 'update') {
        updateElement(data.html, data.selector);
    } else if (data.type === 'noop') {
        return;
    } else if (typeof data.html === 'string') {
        _12like.gt.showBubble(data.html);
    } else {
        openDialog();
        updateElement(data);
    }
}

function updateElement(content, target_id) {
    if (isUndefined(target_id)) {
        updateDialog(content);
        dialogScrollfix();
    } else {
        var $target = $(target_id);
        $target.html(content);
        if ($target.parents('#dialog').length > 0) {
            dialogScrollfix();
        }
        // TODO generic dialogScrollfix();
    }
}

function doAjax(url, target_id, data) {
    var type, errormsg;
    if (url.match('^http')) {
        errormsg = gettext('AJAX cannot load external content');
        updateElement(errormsg, target_id);
    } else {
        if (!isUndefined(data)) {
            type = 'POST';
        }
        $.ajax({
            url: url,
            data: data,
            type: type,
            timeout: 10000,
            success: function(data){
                    if (data.redirect) {
                        window.location.href = data.redirect;
                    } else {
                        updateElement(data, target_id);
                    }
            },
            error: function(req,error){
                if (error === 'error') {
                    error = req.statusText;
                }
                errormsg = gettext('There was a communication error: ') + error;
                updateElement(errormsg, target_id);
            },
            beforeSend: function(data){
                updateElement('<p>' + gettext('Loading...') + '</p>', target_id);
            },
            complete: function(){
                hide_loader();
            }
        });
    }
}

function doAjax2(dest) {
    var path, errormsg;
    if (typeof dest === 'object') {
        dest = this.href;
    }
    path = getPath(dest);
    $.ajax({
        url: path,
        timeout: 10000,
        success: handleJSONResponse,
        error: function(req, error){
            if (error === 'error') {
                error = req.statusText;
            }
            errormsg = gettext('There was a communication error: ') + error;
            updateElement(errormsg);
        }
    });
    return false;
}

function embeddedFormSubmit(href, data) {
    var regex  = new RegExp("^.*?:\/\/.*?(\/.*)$"),
        result = regex.exec(href);
    if (result !== null && result[1] !== null) {
        href = result[1];
    }
    doAjax(href, undefined, data);
    return false;
}

function showModal(url, classes, size) {
    if (isUndefined(size)) {
        size = 680;
    }
    resizeDialog(size);
    if (!isUndefined(classes)) {
        $("#dialog").addClass(classes);
    }
    showInLightbox(url);
}

function showSelectLanguage() {
    showModal(this.href, "top10per", 400);
    return false;
}

function showHTTPError(url) {
    showModal(url, "error top10per", 650);
    setTimeout(closeDialog, 10000);
    return false;
}

function showPrivacySettings() {
    showModal(this.href, "privacy_settings_dialog", 650);
    return false;
}

function showAvailChoice() {
    showModal(this.href, "avail_choice_dialog", 700);
    return false;
}

function showDateDialog(date_id) {
    showModal("/date/dialog/" + date_id, 'top10per', 575);
    return false;
}

function showCalendarReminder() {
    showModal("/calendar-reminder", 'top10per calendar_reminder_dialog', 400);
    return false;
}

function showDateIdea(show_calendar) {
    $("#dialog").addClass("date_idea_dialog");
    if (show_calendar === true) {
      $("#dialog").addClass("date_idea_dialog_show_calendar");
    }
    showInLightbox.apply(this, [this]);
    return false;
}

function showActivate() {
    showModal(this.href, 'payment-dialog', 545);
    actionDialog();
    return false;
}

function showVIP() {
    showModal(this.href, 'top10per payment-dialog', 800);
    actionDialog();
    return false;
}

function showRegImg() {
    var regHref = $('a.start-reg').first().attr('href') || '/start_registration/';
    showModal(regHref, 'top15per', 600);
    return false;
}

function showReg() {
    showModal(this.href, 'top15per', 600);
    return false;
}

function scrolltoAnchor(anchorId) {
    var selector = "#" + anchorId;
    if (!inFrame()) {
        $('html,body').animate({scrollTop: $(selector).offset().top}, 'slow');
    } else {
         window.location.href = selector;
    }
}

/* new test */
function startTestClick() {
    showModal(this.href, 'test_dialog', 680);
    return false;
}

function restartTest() {
    var $container = $("#personalitytest"), data, repaint;
    if (typeof without_display === 'boolean' && without_display) {
        data = "action=close";
        repaint = false;
    } else {
        data = "action=restart";
        repaint = true;
    }
    $.ajax({
        type: 'POST',
        url: "/image-personality-test/",
		data: data,
        success: function(data){
            if (repaint) {
                $container.fadeOut(function(){
                    $container.html(data).fadeIn();
                    dialogScrollfix();
                });
            }
        },
        error: function(data){
            if (repaint) {
                $container.html('<p>' + gettext('Error, Please reload') + '</p>');
            }
        }
    });
    return false;
}

function highlightImage($image) {
    var a=200;
    $image.css("border-color","#59a759");
    $image.prev(".highlight").css("background-color","#59a759").animate({top:"0",width:"152px",height:"152px",left:"0"},a);
}

function unhighlightImage($image) {
    var a=200;
    $image.prev(".highlight").animate({top:"5px",width:"140px",height:"140px",left:"5px"},a).css("background-color","#ffffff");
    $image.css("border-color","#d0cdca");
}

function QuestionMatrix(q_id, n_select, type, cur_question, question_count) {
    var question_id = q_id;
    this.n_select = n_select;
    this.type = type;
    this.selectedAnswers = [];
    this.highlightImage = highlightImage;
    this.unhighlightImage = unhighlightImage;
    this.load_next = function(selected) {
        var $container = $("#personalitytest");
        if (selected === undefined) {
            selected = this.selectedAnswers;
        }
        $.ajax({
            type: 'POST',
            url: "/image-personality-test/",
            data: "action=save_response&id=" + question_id + "&selected=" + selected,
            success: function(data){
                if (data.redirect) {
                    window.location.replace(data.redirect);
                } else {
                    $container.fadeOut(function(){
                        $container.replaceWith(data).fadeIn();
                        dialogScrollfix();
                    });
                }
            },
            error: function(data){
                $container.html('<p>' + gettext('Error, Please reload') + '</p>');
            }
        });
    };
    this.answerClick = function($image) {
        var a=200;
        var id = $image.attr("id");
        var toPick = this.n_select - this.selectedAnswers.length;
        var text, selected, isComplete;
        var next_question = this.load_next;
        if (this.n_select > this.selectedAnswers.length) {
            this.selectedAnswers.push(id);
            selected = this.selectedAnswers;
            isComplete = this.n_select === this.selectedAnswers.length;
            toPick = this.n_select - this.selectedAnswers.length;
            text = interpolate(gettext('Pick %s more'), [toPick]);
            $image.addClass("clicked").unbind('click').unbind('mouseover').unbind('mouseout');
            $image.prev(".highlight").animate({top:"10px",width:"132px",height:"132px",left:"10px"},a);
            $image.animate({top:"15px",width:"120px",height:"120px",left:"15px"},a,function(){
                if (!isComplete) {
                    if (type == "selection_exact") {
                        $('<div class="overlay"></div>').insertAfter($image).text(text);
                    } else {
                        $(".highlight").show();
                        $image.prev(".highlight").fadeOut(200, function(){$image.css("border-width",0);});
                        var to_next = gettext('To next question');
                        $('<div class="overlay" id="sv_status"></div>').insertAfter($image).html(gettext('Do other images worry you as well?') + '<div>\u2013 ' + gettext('OR') + ' \u2013</div>');
                        $('<div class="overlay" id="sv_next"></div>').insertAfter($image).html("<div id=\"to_next_question\">" + to_next + "</div>").click(function() {next_question(selected);return false;}).hover(function() {$("#sv_next").css('background-position', "0 -60px");}, function() {$("#sv_next").css('background-position', "0 0");});
                    }
                }
            });
            if (isComplete) {
                $(".test-matrix img").unbind('click').unbind('mouseover').unbind('mouseout').css({"cursor": "auto"});
                this.load_next();
            } else if (type == "selection_exact") {
                $("#select-info").text(text);
            } else {
                $("#select-none").unbind('click').unbind('mouseover').unbind('mouseout').css({"cursor": "auto"}).animate({top: "15px", left: "15px", width: "120px", height: "120px", fontSize: "1.5em"});
                $("#select-none").prev(".highlight").css({"background":"#333","opacity":".7","filter":"alpha(opacity=70)","z-index":"3"});
            }
            $(".overlay").remove();
        }
    };
    this.cur_question   = cur_question;
    this.question_count = question_count;
    this.update_progress_bar = function() {
        if (!$('#test_progress_bar').length) {
            $("a.close").after('<div id="test_progress"><div id="test_progress_bar"></div></div>');
        }
        $('#test_progress_bar').width(250 * this.cur_question / this.question_count);
    };
}

var sizes = [40, 53, 76, 98, 110, 120, 130, 140, 150];
function scalePics(val) {
    var first_dimension  = sizes[8-val],
        second_dimension = sizes[val];
    $("#first img").css({"width": first_dimension, "height": first_dimension});
    $("#first li").css({"width": first_dimension + 2, "height": first_dimension + 2});
    $("#second img").css({"width": second_dimension, "height": second_dimension});
    $("#first li").css({"width": first_dimension + 2, "height": first_dimension + 2});
    $("#second").css({"width": 307 + sizes[val] - 110});
    if (val < 4) {
        $("#answer6").css({"left": 185 - (3 - val) * 15});
    } else {
        $("#answer3").css({"left": 15 + (val - 4) * 15});
    }
}
function QuestionSlider(question_id, cur_question, question_count) {
    this.question_id = question_id;
    var _value = 4;
    this.value = function(val) {
        if ((val >= 0) && (val <= 8)) {
            _value = val;
            scalePics(val);
        } else {
            return false;
        }
        if (_value === 0) {
            $("#first img").css({"cursor": "default"});
        } else {
            $("#first img").css({"cursor": "pointer"});
        }
        if (_value == 8) {
            $("#second img").css({"cursor": "default"});
        } else {
            $("#second img").css({"cursor": "pointer"});
        }
        return _value;
    };
    this.value.toString = function() {
        return _value;
    };
    this.value.valueOf = this.value.toString;

    this.incValue = function() {
         return this.value(parseInt(_value) + 1);
    };
    this.decValue = function() {
        return this.value(parseInt(_value) - 1);
    };
    this.load_next = function() {
        var $container = $("#personalitytest"), question_id = this.question_id;
        $.ajax({
            type: 'POST',
            url: "/image-personality-test/",
            data: "action=save_response&id=" + question_id + "&value=" + _value,
            success: function(data){
                if (data.redirect) {
                    window.location.replace(data.redirect);
                } else {
                    $container.fadeOut(function(){
                        $container.replaceWith(data).fadeIn();
                        dialogScrollfix();
                    });
                }
            },
            error: function(data){
                $container.html('<p>' + gettext('Error, Please reload') + '</p>');
            }
        });
    };
    this.cur_question   = cur_question;
    this.question_count = question_count;
    this.update_progress_bar = function() {
        if (!$('#test_progress_bar').length) {
            $("a.close").after('<div id="test_progress"><div id="test_progress_bar"></div></div>');
        }
        $('#test_progress_bar').width(250 * this.cur_question / this.question_count);
    };
}
function resetHover() {
    $('#slide_submit a').each(function() {
        $(this).text("");
        $(this).removeClass('selected');
    });
}
function markButton($btn) {
    resetHover();
    $btn.text(gettext("OK"));
    $btn.addClass('selected');
}
function startSlideranimation(question) {
    function activate() {
        $("#slide_submit a").mouseenter(function() {
            var $this = $(this);
            var val = $this.attr("id").substr(7, 1);
            question.value(val);
            markButton($this);
            scalePics(val);
        });
        $("#slide_submit a").click(function() {
            $("#slide_submit a").unbind('mouseenter mouseleave').css({"cursor": "default"});
            question.load_next();
            return false;
        });
        $("#answers img").click(function() {
            var first = $("#first").has(this).length,
                changed;
            if (first) {
                changed = question.decValue();
            } else {
                changed = question.incValue();
            }
            if (changed !== false) {
                markButton($("#submit_" + changed));
            }
            return false;
        });
    }
    function animateSlide() {
        $("#submit_" + (4-i).toString() + ", #submit_" + (4+i).toString()).removeClass('selected');
        if (i < 5) {
            $("#submit_" + (3-i).toString() + ", #submit_" + (5+i).toString()).addClass('selected');
            i += 1;
            window.setTimeout(animateSlide, 200);
        } else {
            $("#submit_4").addClass('selected');
            activate();
        }
    }
    var i = 0;
    window.setTimeout(animateSlide, 1);
}

function getPath(url) {
    var path = url,
        hasPrefix = url.indexOf('://');
    if (hasPrefix > -1) {
        path = path.substring(hasPrefix+3);
        path = path.substring(path.indexOf('/'));
    }
    return path;
}

function showInLightbox(dest) {
    var path, headerless;
    show_loader();
    if (typeof dest === 'object') {
        dest = this.href;
        headerless = $(this).hasClass('headerless');
    }
    openDialog(headerless);
    path = getPath(dest);
    doAjax(path);
    return false;
}

function showTypology() {
    show_loader();
    openDialog();
    $("#dialog_body").attr("id","architypes_overview");
    $("#architypes_overview").load("/typology.html?" + Math.random()*99999,
        function(responseText, textStatus, xhr) {
            hide_loader();
            architype_index = 0;
            var toggle = function() {
                var old_index = architype_index;
                if ($(this).attr("id")=="arrow-prev" && architype_index>0){
                    architype_index--;
                } else {
                    architype_index++;
                }

                if (architype_index==0) {
                    $("#arrow-prev").hide();
                    $("div.arrow-prev").css("background", "none");
                } else {
                    $("#arrow-prev").show();
                    $("div.arrow-prev").css("background", "url(/media/img/arrow_left.png) no-repeat");
                    }
                if (architype_index==9) {
                    $("#arrow-next").hide();
                    $("div.arrow-next").css("background", "none");
                } else {
                    $("#arrow-next").show();
                    $("div.arrow-next").css("background", "url(/media/img/arrow_red_right) no-repeat");
                }
                $("#architype_"+(old_index)).hide();
                $("#architype_"+architype_index).show();
        };
        $("#arrow-prev").click(toggle);
        $("#arrow-next").click(toggle);
        $("#architype_0").show();
        }
        );
    return false;
}


function shareClick() {
    var personalityType = $("#personality_type").text(),
        personalityTypeDesc = $("#personality_type_desc").text(),
        personalityTypeSlug = $("#personality_type_desc").get(0).className,
        obj = {
            method: 'feed',
            link: "http://apps.facebook.com/onetolike/?ct=12like&ci=SharedTestResult",
            picture: "http://www.one2like.com/media/img/archetypes/" + personalityTypeSlug + "_sq.png",
            name: gettext("I Am ") + personalityType,
            caption: 'One2like',
            description: personalityTypeDesc,
            actions: [{name: gettext("Take the test yourself"), link: "http://apps.facebook.com/onetolike/?ct=12like&ci=SharedTestResult"}]
        };
        FB.ui(obj,
            function(response) {
                if (response && response.post_id) {
                    $.ajax({url: "/tracking/sharetestresult/", timeout: 10000});
                }
            }
        );
    return false;
}

function dateIdeaShareClick(opts) {
  var url = opts.url + "?ct=12like&ci=SharedDateIdea",
      attachment = {
        media: [{
          type: "image",
          src:  opts.img_src,
          href: url
        }],
        name:         opts.title,
        href:         url,
        description:  opts.description
      },
      actionLinks = [{text: gettext("12like.com"), "href": "http://apps.facebook.com/onetolike/?ct=12like&ci=SharedDateIdea"}];
  FB_RequireFeatures(["Connect"], function() {
    FB.Connect.streamPublish("", attachment, actionLinks, null, gettext("Share your results on Facebook"));
  });
  return false;
}

function initMatchFilter() {
    var current;
    $('.dropdown').each(function(index) {
        var $this = $(this), $wrap = $this.parent(),
            dd_w = $this.innerWidth() + 22, dw_w = $wrap.innerWidth(),
            width = (dd_w > dw_w ? dd_w : dw_w);
        $this.width(width);$wrap.width(width);$this.prev().width(width - 24);
    });
    var onclick=function(event){
        if($(event.target).closest('li').find(current).length===0){
            $(current).parent().toggleClass('opened',false);
        }
    };
    $('.dropdown-wrap strong').bind('click',function(){
        var $dd_container=$(this).parent(),
            closed=!$dd_container.hasClass('opened'),
            $dd = $dd_container.find('.dropdown');
        if (closed) {
            current = '#' + $dd.attr('id');
            $('body').bind('click',onclick);
        } else {
            current = false;
            $('body').unbind('click');
        }
        $dd_container.closest('ul').children().removeClass('opened');
        $dd_container.toggleClass('opened',closed);
        return false;
    });
    $('.dropdown-wrap strong').bind('mouseenter mouseleave',function(){
        $(this).toggleClass('entered');
    });
    $('.dropdown li').bind('mouseenter mouseleave',function(){
        $(this).toggleClass('hover');
    });

    /* date-filter spezific things */
    $('#match-filter .dropdown li').bind('click',function(){
        var $this = $(this), text = $this.text();
        $.post('/matches/store_filter/',
            {action: 'store_seeking_perference', 'name': $this.parent().attr('id'), 'value': $this.attr('id')},
            function(data){
                if (data.success) {
                    var $wrap = $this.parent();
                    $wrap.prev().text(text);
                    $wrap.find('.selected').removeClass('selected');
                    $this.addClass('selected');
                    window.location.replace(window.location.pathname);
                } else if (data.type && data.type === 'call') {
                    window[data.func](data.args);
                }
        });
        return false;
    });
    $('#match-filter #seeking_age input').bind('keyup',function(){
        if ($('#update_seeking_age').length === 0) {
            var $this = $(this),
                $wrap = $this.parent();
            $('#invalid_age').remove();
            $('<div class="css-btn orange"><a href="javascript:void(0)" id="update_seeking_age">' + gettext('Update') + '</a></div>').appendTo($wrap).bind('click',function(){
                var age_lower = $('#id_seeking_age_lower').val(), age_upper = $('#id_seeking_age_upper').val();
                $.post('/matches/store_filter/',
                    {action: 'store_seeking_perference', 'name': 'seeking_age', 'value': age_lower + "|" + age_upper},
                    function(data){
                        $("#update_seeking_age").parent().remove();
                        var text = "";
                        if (data.success) {
                            if (!age_lower && !age_upper) {
                                text = gettext('Any Age');
                            } else {
                                var transObj;
                                if (!age_lower) {
                                    transObj = { age: age_upper };
                                    text = interpolate(gettext("Max %(age)s years"), transObj, true);
                                } else if (!age_upper) {
                                    transObj = { age: age_lower };
                                    text = interpolate(gettext("Min %(age)s years"), transObj, true);
                                } else {
                                    transObj = { lower_age: age_lower, upper_age: age_upper };
                                    text = interpolate(gettext("%(lower_age)s to %(upper_age)s years"), transObj, true);
                                }
                            }
                            $this.closest('.dropdown').prev().text(text);
                            window.location.replace(window.location.pathname);
                        } else {
                            if (data.error) {
                                text = data.error;
                            } else {
                                text = gettext('Invalid Age');
                            }
                            $wrap.append('<p class="error" id="invalid_age">' + text + '</p>');
                        }
                });
            });
        }
    });
}

// dropdown_selector: e.g. "#ideas-filter .dropdown-wrap"
// list_selector:     e.g. "#date_ideas_list"
// url: url for loading data
function dropdownFilterInit(dropdown_selector, list_selector, url) {
  $(document).click(function() {
    $(dropdown_selector + ' ul.dropdown').hide().prev().removeClass("entered");
  });
  $(dropdown_selector + " > li").each(function() {
    var el = $(this).children("strong");
    var dd = el.next();
    var sel = dd.children("[class=selected]");
    if (sel.length > 0) {
      el.text(dd.children("[class=selected]").text());
    } else {
      el.text(dd.children(":first").text());
    }
    var width = Math.max(dd.outerWidth(), el.outerWidth()) + 50;
    el.width(width - el.outerWidth() + el.width());
    dd.width(width - dd.outerWidth() + dd.width());
    el.bind("click", function() {
      var closed = false;
      if (!$(this).hasClass('entered')) {
          closed = true;
      }
      $(dropdown_selector + ' ul.dropdown').hide().prev().removeClass("entered");
      if (closed) {
        el.addClass("entered");
        dd.show();
      }
      return false;
    });
    // filter data on click
    dd.children().bind("click", function() {
      var $this = $(this);
      var field = dd.attr("id"), key = $this.attr("id");
      var data = {
        field: field,
        key: key
      };
      $(list_selector).empty().load(url, data);
      $this.parent().prev().text($this.text());
    });
  });
}

function inviterClick() {
    $("#inviter").jqmShow();
    return false;
}

function describe_friend_click() {
    show_loader();
    openDialog();
    var url = $(this).attr("href") + "embedded/";
    $("#dialog_body").load(url + "?" + Math.random()*99999, function(responseText, textStatus, xhr) {
        if (textStatus !== "success") {
            alert(gettext("Sorry, there was an error loading the describe me dialog."));
            closeDialog();
        }
        dialogScrollfix();
        hide_loader();
    });
    return false;
}


function request_sent(elem) {
    $(elem).html(gettext("Request sent"));
}

function lock_overlay() {
    var the_offset = $('table.results_list').offset();
    if ($('#lock-overlay').length === 0) {
        jQuery('<div id="lock-overlay"></div>').appendTo(document.body);
    }
    $('#lock-overlay').css({
             "width": $('table.results_list').width() + "px",
             "height": $('table.results_list').height() + "px",
             "top": the_offset.top + "px",
             "left": the_offset.left + "px"});
}

function showNotification(message) {
    if (!$("#notification").length) {
        var el = $("#profile");
        if (!el.length) {
          el = $("#content");
        }
        el.before('<ul id="notification" class="success">' + message + '</ul>');
    } else {
        $("#notification").html(message).show();
    }
    $("#notification").stop().animate({opacity: 1.0}, 5000,function(){
        $(this).fadeTo(500, 0.1, function() {
            $(this).slideUp(1000);
        });
    });
}

function check_hash() {
    if (window.location.hash !== hash) {
        if (!isUndefined(hash) && (hash.substring(0, 10) === "#/profile/") && (!window.location.hash)) {
            hideProfile();
        }
        hash = window.location.hash;
        if (hash.substring(0, 10) === "#/profile/") {
            showProfile(hash.substring(10, 18));
        }
    }
}

function set_hash(new_hash) {
    if (hash != new_hash) {
        hash = "#" + new_hash;
        window.location.hash = new_hash;
    }
}

/* profile viewing */

function showProfileClick() {
    var regexS = "[\\?&]info_tabs_select=([^&#]*)",
        regex = new RegExp(regexS),
        results = regex.exec(this.href),
        regexB = new RegExp("[ABCDEFGHJKMNPQRSTUVWXYZ]{2}[ABCDEFGHJKMNPQRSTUVWXYZ23456789]{6}"),
        box_number = regexB.exec(this.href);
        if(results === null) {
            showProfile(box_number);
        } else {
            showProfile(box_number, results[1]);
        }
    closeJqms();
    if (!inFrame()) {
        scrollTo(0, 0);
    } else {
        location.href = '#';
    }
    return false;
}

function DPActionLinkClick() {
    var $this = $(this),
        a_href = this.href;
    $.getJSON(a_href + "json/", function(data) {
        if (data && data.message && data.text) {
            if ($this.hasClass("change")) {
                $this.parent().html(data.text);
                if (data.overlay) {
                    var odiv = $("#profile-poloroid div");
                    if (!odiv.length) {
                        $("#profile-poloroid img").after(data.overlay);
                    } else {
                        odiv.replaceWith(data.overlay);
                    }
                }
                $('a.dp-action').unbind('click').click(DPActionLinkClick);
            } else {
                if ($this.hasClass("photo-release")) {
                    $(".photo-release").replaceWith(data.text);
                } else {
                    $this.replaceWith(data.text);
                }
            }
            showNotification(data.message);
        }
    });
    return false;
}

function confirmClick() {
    var target = this,
        $target = $(target),
        $wrap = $target.parent(),
        confirm = gettext("Are you sure?") + ' <a href="' + target.href + '" class="yes">' +gettext("Yes") + '</a> ',
        $no = $('<a href="#" class="no">' + gettext("No") + '</a>').unbind('click').click(function() {
            $wrap.html("").append($target);
            return false;
        });
    $target.detach();
    $wrap.html(confirm).append($no);
    return false;
}

function hideProfile() {
    $("#profile").hide();
    $('#inside-container').show();
    set_hash("");
    return false;
}

function noteKeyup() {
    $("#noteform p").replaceWith('<a href="#" class="minor" title="{% trans \'Save note\' %}>' + gettext("Save note") + '</a>');
    if (!$("#noteform a").length) {
        $("#noteform").append('<a href="#" class="minor" title="{% trans \'Save note\' %}">' + gettext("Save note") + '</a>');
    }
    $("#noteform a").click(updateNote);
}

var actions_binded = false;
function bindProfileActions() {
    if (actions_binded) {
       return;
    } else {
        actions_binded = true;
    }
    $('a.dp-action').live('click', DPActionLinkClick);
    $("a.confirm").live('click', confirmClick);
    $("a.submit-arrow").live('click', function() {
        $(this).closest("form").submit();
        return false;
    });
    $('.more_expand').live('click', function() {
        var $this = $(this);
        $this.hide();
        $this.next('.more_text').slideDown();
    });
    $("#add-note").live('click', function() {
        $("#noteform").slideDown();
        $(this).remove();
        return false;
    });
    $("a#ask_me_out, a.avail_display").live('click', function() {
      $("#info-tabs").tabs("select", "#calendar");
    });

    $("#profile-back").live('click', hideProfile);

    // notes update
    $("form#noteform").live('submit', updateNote);
    $("textarea#note").live('blur', updateNote);
    $("textarea#note").live('change', scheduleUpdateNote);
    $("#note").live('keyup', noteKeyup);
}

function showProfile(boxNumber, tab_number) {
    var $content = $('#inside-container'),
        $profile = $("#profile"),
        get_params, url;
    if (isUndefined(tab_number)) {
        get_params = '';
    } else {
        get_params = '?info_tabs_select=' + tab_number;
    }
    url = "/" + boxNumber + "/" + get_params;
    if (!$profile.length) {
        $content.after('<div id="profile"><div id="loader-wrap"><div id="loader">' + gettext("Loading profile") + '</div></div></div>');
        $profile = $("#profile");
    } else {
        $profile.html('<div id="loader-wrap"><div id="loader">' + gettext("Loading profile") + "</div></div>");
    }
    if (url.match('^http')) {
        var errormsg = gettext('AJAX cannot load external content');
        $profile.html(errormsg);
    } else {
        if (!isUndefined(xhr_profile) && xhr_profile !== null) {
            xhr_profile.abort();
        }
        $content.hide();
        $profile.show();
        xhr_profile = $.ajax({
            url: url,
            timeout: 10000,
            success: function(data){
                if (data.redirect) {
                    window.location.href = data.redirect;
                } else {
                    $profile.html(data);
                    if (!$content.children().length) {
                        $("#profile-back").hide();
                    }
                    set_hash("/profile/" + boxNumber);
                }
            },
            error: function(req,error){
                if(error === 'error'){
                    error = req.statusText;
                }
                var errormsg = gettext('There was a communication error: ')+error;
                $("#profile").html(errormsg);
            },
            completed: function() {
                xhr_profile = null;
            }
        });
    }
}

var newWindow = '';
function popupWindow(params) {
    width  = params.width || 562;
    height = params.height || 562;
    if (params.url) {
        if (!newWindow.closed && newWindow.location) {
            newWindow.location.href = params.url;
        } else {
            newWindow = window.open(params.url,'', "scrollbars=yes, resizable=yes, toolbar=no, menubar=no, width=" + width + ", height=" + height);
            if (!newWindow.opener) {
                newWindow.opener = self;
            }
        }
        if (window.focus) {
            newWindow.focus();
        }
    }
}

function describeMeClick() {
    var elem = $("#id_facebook_id option:selected");
    var vars = {
            facebook_id:          elem.val(),
            recipient:            elem.text(),
            recipient_first_name: elem.text().split(" ")[0],
            sender:               sender,
            describe_url:         "http://www.12like.com/description/"
        };
    $.ajax({
        url:     "/profile/descriptions/create/",
        timeout: 10000,
        type:    'POST',
        data:    ({'facebook_id': vars['facebook_id'], 'first_name': vars['recipient_first_name'], 'last_name': vars['recipient'].substring(vars['recipient_first_name'].length + 1, vars['recipient'].length)}),
        success: function(data){
            if (data.success) {
                var subject = gettext("Describe me!"),
                    message = gettext("Dear %(recipient_first_name)s,\n\ncan you describe me? Click the link below:\n\n%(describe_url)s\n\nThanks,\n%(sender)s");
                vars['describe_url'] = vars['describe_url'].concat(data.slug);
                message = encodeURI(interpolate(message, vars, true));
                popupWindow({
                    "url": 'http://www.facebook.com/inbox/?compose&id='+vars['facebook_id']+'&subject='+subject+'&message='+message
                });
            }
        },
        error: function(req,error){
        }
    });

    return false;
}


function helpOverlay(event) {
    var $cur = $(this),
        $help_overlay = $cur.parent().next('div.help-overlay'),
        $win = $(window),
        $parent = $cur.parents('div.jqmWindow').first(),
        showTip, tip, hideTip;
    if ($parent.length === 0) {
        $parent = $('#container');
    }
    tip = {
        offset: 4,
        delay: 0,
        position: function(event) {
            var marginLeft = parseInt($parent.css('marginLeft').replace("px", "")),
                positions = {x: event.pageX, y: event.pageY},
                dimensions = {
                x: [$parent.offset().left + $parent.width() + marginLeft, $help_overlay.outerWidth()],
                y: [$win.scrollTop() + $win.height(), $help_overlay.outerHeight()]
            };
            if (dimensions.x[0] < positions.x + dimensions.x[1] + this.offset) {
                positions.x = dimensions.x[0] - dimensions.x[1] - this.offset - 10;
            } else {
                positions.x += this.offset;
            }
            if (dimensions.y[0] < dimensions.y[1] + positions.y + this.offset) {
                positions.y -= dimensions.y[1] + this.offset * 2;
            } else {
                positions.y += this.offset;
            }
            $help_overlay.css({
                top: positions.y,
                left: positions.x
            });
        }
    };
    hideTip = function() {
        if ($cur.data('tipActive')) {
            $cur.removeData('tipActive');
            $help_overlay.hide();
            $('body').unbind('click.hideTip');
        } else {
            clearTimeout(showTip);
        }
        return false;
    };
    if (event.type == 'mouseover') {
        showTip = setTimeout(function() {
            $cur.data('tipActive', true);
            tip.position(event);
            $('body').bind('click.hideTip', hideTip);
            $help_overlay.fadeOut(0).fadeIn(200);
        }, tip.delay);
    } else if (event.type == 'mouseout') {
        hideTip();
    } else if (event.type == 'mousemove' && $cur.data('tipActive')) {
        tip.position(event);
    }
}

/* profile notes */

// save a note on a profile via ajax post
function updateNote() {
    var text = $("textarea#note").val();
    if (text != "") {
        $("#noteform a").replaceWith('<p class="minor">' + gettext("Updating...") + '</p>');
        var url = $("form#noteform").get(0).action;
        $.post(url, {"text": text}, function(data, textStatus) {
            if (textStatus !== "success" || "error" in data) {
                alert(gettext("Sorry, there was an error occured while saving."));
            }
            else {
                // stop browser from showing "you've edited fields" warning
                $("textarea#note").replaceWith("<textarea id=\"note\">" + text + "</textarea>");
                $("#note").blur(updateNote);
                $("#note").change(scheduleUpdateNote);
                $("#note").keyup(noteKeyup);
                $("#noteform p").html(gettext("Saved"));
            }
        }, "json");
    }
    return false;
}

// global timer for note updates
var updateNoteTimer = null;

function scheduleUpdateNote() {
    clearTimeout(updateNoteTimer);
    updateNoteTimer = setTimeout(updateNote, 5000);
}

/* profile editing */

function selectFriend(_event, data, formatted) {
    $("input#id_recipient_id").val(data.id);
}

function setupFriendAutocomplete(data, textStatus) {
    if (textStatus !== "success") {
        alert(gettext("Sorry, there was an error occured while saving."));
    }
    else if (data.length > 0){

        var acOpts = {
            mustMatch:  true,
            formatItem: function(row, i, max) {return row.name;},
            autoFill:   true
        };
        $("input#id_recipient").autocomplete(data, acOpts).result(selectFriend);
        $("input#id_recipient").get(0).focus();
    }
}

function updateMetric(id) {
    var feet = parseInt($("input#" + id + "_feet").val(), 10) || 0,
        inches = parseInt($("input#" + id + "_in").val(), 10) || 0,
        cm = Math.round(((feet * 12) + inches) * 2.54);
    $("input#" + id).val(cm);
}

function unitSelectClick() {
    var inputBlock = $(this).parent(),
        newUnits = this.value;

    $("input.height_feetin", inputBlock).remove();

    // replace multiple height inputs within each field block
    $("input.height", inputBlock).each(function() {
        var newInput,
            cm = parseInt($(this).val(), 10) || "";

        if (newUnits === "imperial") {
            if (cm !== "") {
                feet = Math.floor(cm / (2.54 * 12));
                inches = Math.round((cm / 2.54) % 12);
            }
            else {
                feet = "";
                inches = "";
            }
            newInput = $("<input name=\"" + this.name + "_feet\" class=\"height_feetin\" type=\"text\" id=\"" + this.id + "_feet\" size=\"3\" value=\"" + feet + "\" onchange=\"updateMetric('" + this.id + "')\" /> <input name=\"" + this.name + "_in\" class=\"height_feetin\" type=\"text\" id=\"" + this.id + "_in\" size=\"3\" value=\"" + inches + "\" onchange=\"updateMetric('" + this.id + "')\" /> <input name=\"" + this.name + "\" value=\"" + cm + "\" class=\"height\" type=\"hidden\" id=\"" + this.id + "\" size=\"3\" />");
        }
        else {
            newInput = $("<input name=\"" + this.name + "\" value=\"" + cm + "\" class=\"height\" type=\"text\" id=\"" + this.id + "\" size=\"3\" />");
        }
        $(this).replaceWith(newInput);
    });
}

function addUnitSelect() {
    var input = $(this),inputBlock = input.parent();

    // only attach one unit select to each input line
    if ($("select.units", inputBlock).length === 0) {
		var unitSelect = $("<select class=\"units\"><option value=\"metric\">"+gettext("CM")+"</option><option value=\"imperial\">"+gettext("Feet/in")+"</option></select>");
        unitSelect.attr("name", this.name + "_units");
        unitSelect.attr("id", this.id + "_units");
        unitSelect.change(unitSelectClick);
        inputBlock.append(unitSelect);
    }

	// set the error list tag AFTER the select unit tag
    if ($("ul.errorlist", inputBlock).length != 0) {

		var i=0;
		while ( i < inputBlock[0].childNodes.length) {
			if(inputBlock[0].childNodes[i].nodeName === "UL") {
				var ulNode = $("ul.errorlist", inputBlock);
				inputBlock[0].removeChild(inputBlock[0].childNodes[i]);
				inputBlock.append(ulNode);
			}
			i++;
		}
    }
}

function loadjscssfile(filename, filetype){
    var tag_name, fileref;
    if (filetype=='js'){
        tag_name = 'script';
    } else if (filetype=='css'){
        tag_name = 'link';
    }
    var _elems = document.getElementsByTagName(tag_name);
    for (i = 0; _elems.length > i; i++) {
        if (_elems[i].href == filename) {
            return;
        }
    }
    fileref = document.createElement(tag_name);
    if (filetype=='js'){
        fileref.setAttribute('type', 'text/javascript');
        fileref.setAttribute('src', filename);
    } else if (filetype=='css'){
        fileref.setAttribute('rel', 'stylesheet');
        fileref.setAttribute('type', 'text/css');
        fileref.setAttribute('href', filename);
    }
    if (typeof fileref!='undefined') {
        document.getElementsByTagName('head')[0].appendChild(fileref);
    }
}

/* login fields */
function labeledInput(id, v){
    var $id = $(id);
    $id.addClass('labeled-input').attr({value: v}).focus(function(){
        var $this = $(this);
        if($this.val() === v){
            $this.removeClass('labeled-input').val("");
        }
        }).blur(function(){
            var $this = $(this);
            if($this.val() === ""){
                $this.addClass('labeled-input').val(v);
            }
	});
    $('label[for='+$id.attr('id')+']').remove();
}

;(function($){
    var mode = document.documentMode || 0,
        isIE6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent) && !mode;

    $.fn.blockOverlay = function(show){
        var fn = show ? $.blockElement : $.unblockElement;
        $(this).each(function(){
            fn($(this));
        });
    };

    $.fn.hasBlockOverlay = function(){
        return this.hasClass("blocked");
    };

    $.blockElement = function(element){
        if (element.hasBlockOverlay()) {
            return
        }
        if (element.css("position") == "static") {
            element.addClass("blocked-relative");
        }
        element.addClass("blocked");
        if (isIE6) {
            element.find("select").addClass("blocked-hidden");
        }

        element.append($('<div class="block-overlay"></div>'));
    };

    $.unblockElement = function(element){
        if (!element.hasBlockOverlay()) {
            return
        }
        element.find("div.block-overlay").remove();
        element.removeClass("blocked blocked-relative");
        element.find("select").removeClass("blocked-hidden");
    };
})(jQuery);


$(document).ready(function() {
    $("a.start_test").live('click', startTestClick);
    $('a.start-reg').live('click', showReg);
    $('#o2l-collage-photo, .index-box').live('click', showRegImg);
    $('.index-box .overtext').live('click', function() {return false;});
    $('.index-box .login a').live('click', function() {window.location.href = $(this).attr("href");return false;});

    $('a.js').live('click', doAjax2);

    // dialog close
    $("a.close").click(closeDialog);
    $('a.close-jqm').live('click', closeJqm);

    // profile dialog for match and message pages
    //$("a.show_profile").live('click', showProfileClick);

    $('#qo2l-login-open').click(function(e){
        $(this).parent().hide();
        $('#o2l-login').show();
        return false;
    });

    // extend height inputs to allow feet/inches
    $("input.height").each(addUnitSelect);

    // sort order
    $("#id_order").change(function() {$("#filter-form").submit();});

    // filter for vistors
    $("#id_role").change(function() {$("#filter-form").submit();});

    // date ideas share button
    $(".date_idea_box a.fb_share").live("click", function() {
      var $a = $(this);
      var $box = $a.closest('.date_idea_box');
      dateIdeaShareClick({
        title: gettext("[Date idea FB] Die 12like Date-Idee: ") + $box.find('.title').text(),
        description: $box.find('.content').text(),
        url: 'http://www.12like.com' + $a.attr('href'),
        img_src: 'http://www.12like.com' + $box.find('img.pic').attr('src')
      });
      return false;
    });

    // date ideas "add to cal" link
    $(".add-to-cal").live("click", function() {
      // show date idea in lightbox
      if (!$("#dialog").is(":visible")) {
        showDateIdea.apply(this, [true]);
      } else {
        // or show calendar if we are already in lightbox
        $(this).fadeOut();
        $(".add_calendar").slideDown(dialogScrollfix);
      }
      return false;
    });

    // date ideas list, lightbox links
    $("#date_ideas_list a.idea-link").live("click", showDateIdea);

    // results page links
    $("#share").click(shareClick);
    $("a.invite").live('click', inviterClick);
    $("#select-language").click(showSelectLanguage);
    $("a.lightbox").live('click', showInLightbox);
    $("a.activate").live('click', showActivate);
    $("a.vip").live('click', showVIP);
    $("#typology").click(showTypology);

    // control bar links
    $("#link-privacy-settings").click(showPrivacySettings);

    // calendar availability button (in control bar and elsewhere)
    $(".link-avail-choice").live("click", showAvailChoice);

    /* other initialisation */

    // activate JQM plug-in for modal dialogs
    $("#inviter").jqm();
    $("#dialog").jqm({
        modal: true,
        onHide: function(hash) {
            hash.w.hide();
            hash.o.remove();
        }
    });

    $('#o2l-setlang a.o2l-setlang').click(function(){
        var lang = $(this).text(),
          form = $('#o2l-setlang'),
          formLang = $('#o2l-setlang-lang');
        $(formLang).val(lang);
        $(form).submit();
        return false;
    });

    // load friend data for message compose name autocomplete
    if ($("input#id_recipient").length > 0) {
        $.getJSON("/friends/json/", setupFriendAutocomplete);
    }

    $('body').delegate('span.hint-icon', 'mouseover mouseout mousemove', helpOverlay);

    $('#submit-btn, div.submit-btn').live('click', function() {
        var $this = $(this);
        if (!$this.hasClass('active')) {
            $this.closest('form').submit();
            if (!$this.hasClass('completed')) {
                $this.addClass('active');
            }
        }
        return false;
    });
    /*{% comment %}adding request header to make jQuery Form Plugin compatible with django's request.is_ajax(){% endcomment %}*/
    jQuery.ajaxSetup({
        'beforeSend': function(xhr) {xhr.setRequestHeader('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');}
    });

    labeledInput($("#username"), gettext("Email or Box No."));
    labeledInput($("#password"), gettext("Password"));
    $("ul#notification").animate({opacity: 1.0}, 5000,function(){
        $(this).fadeTo(500, 0.1, function() {
            $(this).slideUp(1000);
        });
    });

    var hashCheck = setInterval(check_hash, 100);
});

var sf_to = false;
$(window).resize(function(){
    if(sf_to !== false) {
        clearTimeout(sf_to);
    }
    sf_to = setTimeout(scrollfixJqm, 50);
});

function strip(str) {
  return (str.replace(/^\W+/,'')).replace(/\W+$/,'');
}

