var Esof = {};

/* Very simple jQuery extension that put the content of a title attribute
   inside an input tag and remove it on focus */

(function($) {
    $.fn.gazHint = function(lclass) {
        return this.each(function() {
            var label = $(this);
            var forid = label.attr('for');
            if (forid) {
                var input = $('#'+forid);
                
                this.hide = function() {
                    label.addClass("hidden");
                }
                this.show = function() {
                    if (input.val() == "") label.removeClass("hidden");
                }

                input.focus(this.hide);
                input.blur(this.show);                
                label.click(function() { input.focus(); });

                if (input.val() == "") this.show();
            }
        });
    };
})(jQuery);

/* Survey switches */

Esof.checkSwitchSetup = function()
{
    var clicked = $(this).find(".switch")[0];
    var target  = $(this).find("input.switchTarget")[0];
    
    if (!clicked || !target) return;
    
    if ($(clicked).attr('checked'))
        $(target).removeAttr("disabled");

    $(this).one('click', Esof.checkSwitch);
}

Esof.checkSwitch = function(evt)
{
    function sw(target, activate) {
        if (activate) {
            $(target).removeAttr("disabled");
        }
        else {
            $(target).val("");
            $(target).attr("disabled", "on");        
        }
    }
    
    var target = $(evt.target).siblings("input.switchTarget")[0] || evt.data;
    var clicked = $(evt.target);
    
    if (target && clicked.is("input")) {
        if (clicked.hasClass("switch")) {
            sw(target, clicked.attr('checked'));
        }
        
        // If the clicked element is not a switch we disable the target only
        // if the clicked element is a radio button else (check button) we
        // leave the target as it.
        
        else if (!clicked.hasClass("switchTarget")) {
            if (clicked.attr("type") == "radio")
                sw(target, false);
        }
    }
    $(this).one('click', target, Esof.checkSwitch);
};

Esof.fixIEButtons = function()
{
    var hidden = $("#iesection");
    if (hidden.length != 1) return;
    
    $("button").click(function(evt) {
        hidden.val($(evt.target).find("span").text());
    });
};

$(function() { Esof.fixIEButtons(); });

/* Survey results layout */

Esof.createFlotArgs = function(data, ncols)
{
    var objs = [];
    var total = 0;
    
    for (var i=0 ; i < data.length ; i++) {
        total += data[i].B;
    }
    
    for (var i=0 ; i < data.length ; i++) {
        var obj = {
            data: [[i, data[i].B*100/total]],
            bars: {show: true},
            label: data[i].A
        }
        objs.push(obj);
    }
    return objs;
};

Esof.setupTimeline = function() {
    var timeline = $('#timeline-box #strip-wrapper');
    var last = timeline.find('.strip-item').length -1;
    var itemsShown = 3;
    var offset = Math.max(0, last - itemsShown + 1);

    var current = $('#timeline-box .scrollto-control .month.current').attr('href');
    if (current)
        offset = indexOf(current);

    timeline.css('overflow', 'hidden');
    timeline.serialScroll({
        items:'.strip-item',
        prev:'#timeline-box a.prev',
        next:'#timeline-box a.next',
        margin: true,
        start: offset,
        exclude: itemsShown - 1,
        duration: 500,
        force:true,
        stop:true,
        lock:false,
        cycle:false //don't pull back once you reach the end
    });

    function indexOf(el) {
        return $(el).prevAll().length;
    }

    $('#timeline-box .scrollto-control a[href]').click(function(evt){
        evt.preventDefault();
        var href = $(this).attr('href');
        timeline.trigger('goto', indexOf(href));
    });
};

Esof.showFriendConnect = function() {
    var skin = {};
    skin['BORDER_COLOR'] = '#cccccc';
    skin['ENDCAP_BG_COLOR'] = '#E7F2EE';
    skin['ENDCAP_TEXT_COLOR'] = '#333333';
    skin['ENDCAP_LINK_COLOR'] = '#0000cc';
    skin['ALTERNATE_BG_COLOR'] = '#ffffff';
    skin['CONTENT_BG_COLOR'] = '#ffffff';
    skin['CONTENT_LINK_COLOR'] = '#0000cc';
    skin['CONTENT_TEXT_COLOR'] = '#333333';
    skin['CONTENT_SECONDARY_LINK_COLOR'] = '#7777cc';
    skin['CONTENT_SECONDARY_TEXT_COLOR'] = '#666666';
    skin['CONTENT_HEADLINE_COLOR'] = '#333333';
    skin['POSITION'] = 'bottom';
    skin['DEFAULT_COMMENT_TEXT'] = '- add your comment here -';
    skin['HEADER_TEXT'] = 'Comments';
    google.friendconnect.container.setParentUrl('/' /* location of rpc_relay.html and canvas.html */);
    google.friendconnect.container.renderSocialBar(
     { id: 'div-5348376723668105223',
       site: '11412222015633853849',
       'view-params':{"scope":"SITE","features":"video,comment","showWall":"true"}
     }, skin);
};

Esof.getLanguage = function() {
    var lang = $('html').attr('lang');
    if (!lang)
        lang = $('html').attr('xml:lang');
    return lang;
}


Esof.setupConditionalQuestions = function(questions) {
    $(questions).find(':input').change(function() {
        Esof.conditionalEnableDisable(questions)
    });
    Esof.conditionalEnableDisable(questions);
};

// get the current value of a question item
Esof.getQuestionValue = function (question) {
    var $question = $(question);
    if ($question.find(':radio').length > 0)
        return $question.find(':radio:checked').val();
    if ($question.find(':checkbox').length > 0)
        return $question.find(':checkbox:checked').val();
    return $question.find(':input').val();
};

// enable/disable conditional questions
Esof.conditionalEnableDisable = function (questions) {
    $(questions).each(function() {
        var $this = $(this);
        var classes = $this.attr('class').split(/\s+/);
        var conditions = jQuery.map(classes, function(item, idx) {
            var condition = item.match(/if-(not-)?([0-9a-zA-Z]+)-(\S+)/);
            if (!condition || condition.length != 4)
                return;
            var ret = { negated: condition[1] == 'not-', question: condition[2], value: condition[3] };
            return ret;
        });

        var satisfied = true;
        jQuery.each(conditions, function(idx, condition) {
            var question = $('#question-'+condition.question);
            var val = Esof.getQuestionValue(question) == condition.value;
            if (condition.negated)
                val = !val;
            satisfied = satisfied && val;
        });

        if (satisfied)
            $this.addClass('enabled').removeClass('disabled');
        else
            $this.addClass('disabled').removeClass('enabled');
    });

    Esof.updateInputEnableDisable(questions);
};

Esof.updateInputEnableDisable = function (questions) {
    $(questions).find(":input").each(function(){
        var $this = $(this);
        if ($this.parents('.disabled').length > 0) {
            $this.attr('disabled', 'true');
            $this.attr('readonly', 'true');
        }
        else {
            $this.removeAttr('disabled');
            $this.removeAttr('readonly');
        }
    });
};

Esof.setupListQuestions = function(questions) {
    $(questions).find(':input').change(function() {
        Esof.listEnableDisable(questions)
    });
    Esof.listEnableDisable(questions);
};

Esof.listEnableDisable = function (questions) {
    $(questions).each(function() {
        var question = $(this);
        question.find('fieldset.list fieldset').each(function() {
            var inputs = $(this).find(':input:gt(0)');
            var selected = $(this).find(':input:first').val();
            if (!selected) {
                inputs.attr('disabled', 'true');
                inputs.attr('readonly', 'true');
            }
            else {
                inputs.removeAttr('disabled', 'true');
                inputs.removeAttr('readonly', 'true');
            }
        });
    });
};

Esof.setupTextareaMaxlength = function (questions) {
    $(questions).each(function() {
        var question = $(this);
        question.find('textarea[maxlength]').keypress(function() {
            var textarea = this;
            // delay the validation after the keypress has generated
            // the character in the textarea
            setTimeout(function() { Esof.updateTextareaMaxlength(question, textarea); }, 0);
        }).keypress();
    });
};

Esof.updateTextareaMaxlength = function (question, textarea) {
    var $question = $(question);
    var $textarea = $(textarea);

    var maxlength = $textarea.attr('maxlength');
    var length = $textarea.val().length;
    var remaining = maxlength - length;

    if (remaining < 0) {
        var scrollTop = $textarea.scrollTop();
        var scrollLeft = $textarea.scrollLeft();
        $textarea.val($textarea.val().substr(0, maxlength));
        $textarea.scrollTop(scrollTop);
        $textarea.scrollLeft(scrollLeft);
    }
    question.find('.textarea-counter').html(""+Math.max(0, remaining));
};
