/*
 * @input:
 * jsContainer <string> =   the last part of #id of given message group which contains the js-links 
 *                          or just should be hidden
 *
 */


$(document).ready(function() {
  InitHelper();
});



// hides an object (group) with given number (page_number-raunning_number)
// we perform hiding inside of try-catch to ensure no errors will be displayed if 
// id contains unresolvable object i.e. with wrong page_number and/or wrong running_number 
function hideGroupById(id){
    var id;
    try { $('#eq-group-'+id).css('display', 'none'); } catch(err){}
}

function showGroupById(id){
    var id;
    try { $('#eq-group-'+id).css('display', ''); } catch(err){}
}

// hides a table row containing the variable provided as argument
function hideByVariableName(name){
    //$("select[name='"+name+"']:parent").css('visibility', 'hidden');
    $("tr:has(select[name='"+name+"'])").css('display', 'none');
    $("tr:has(input[name='"+name+"'])").css('display', 'none');
}

function showByVariableName(name){
    //$("select[name='"+name+"']:parent").css('visibility', 'hidden');
    $("tr:has(select[name='"+name+"'])").css('display', '');
    $("tr:has(input[name='"+name+"'])").css('display', '');
}


// disables a particular checkbox
function disableCheckbox(id)
{
    try {
        $("input[name='v["+id+"]']").attr("disabled", true);  
    } catch(e) {}
    
}

// hides a particular checkbox     
function hideCheckbox(id)
{
    try {
        $("input[name='v["+id+"]']").css('display', 'none');  
    } catch(e) {}
    
}


// hides the rows of the group which have no entry in the question field
// needed for example in the case of providing no answer for 
// a input line variable and its later use in the questionnaire
// http://forum.equestionnaire.de/viewtopic.php?f=1&t=1212
function hideEmptyRows(id)
{
    try 
    { 
        var i = 0;
        tr =  $('#eq-group-'+id+' tr').each(function(){
            if (i >0)
            {      
                if ($(this).children().html() == "&nbsp;") 
                {                
                    $(this).css('display', 'none');
                }
            }
            i++;
        });

    } catch(err){}
}

function hideEmptyColumns(id)
{
    var id;
    
    try 
    { 
        // get the array of empty columns except the first one
        var eArr = new Array();
        var i = 0;

        try 
        { 
            header =  $('#eq-group-'+id+' tr').eq(0).children('td').each(function(){  
                if (i>0)
                {
                    if ($(this).html() == '&nbsp;') {eArr.push(i);}
                }
                i++;
            });
        } catch (err1){}  
        

        // hide the cells matching the numbers from the array of empty header columns number eArr         
        tr =  $('#eq-group-'+id+' tr').each(function(){
            for (i=0; i< eArr.length; i++)
            {
                $(this).children('td').eq(eArr[i]).css('display', 'none');
            }
        });
    } catch(err){}
}


//
// provided a multiple choice group @id 
// and the item number of the "not aplicable" alternative @naId
// binds the handlers that deselect all the alternatives if the n/a alternative becomes selected
// and deselect the n/a alternative if any of the remainder alternatives becomes selected
function attachMCUnchecker(id, naId)
{
    var id, naId;
    try 
    { 
        // get the array of names of the checkboxes
        var nArr = new Array();
        var i = 0;

        try 
        { 
            $('#eq-group-'+id+' input:checkbox').each(function(){  
                // if it is a n/a alternative 
                // bind a onclick handler, which unchecks the remaining alternatives 
                if ($(this).attr("name")== "v["+naId+"]")
                {                            
                    $(this).bind('click', function(){
                        if($(this).attr('checked')== true)
                        {
                            $('#eq-group-'+id+' input:checkbox').each(function(){
                                if ($(this).attr("name") != "v["+naId+"]") { $(this).attr("checked", false); }
                            });
                        }
                    });
                }
                // if it is not an n/a alternative
                // bind a handler which unchecks the n/a alternative
                else 
                {
                    $(this).bind('click', function(){
                        if($(this).attr('checked')== true)
                        {
                            $('#eq-group-'+id+' input[name="v['+naId+']"]').attr("checked", false); 
                        }
                    });
                }
                i++;
            });
        } catch (err1){}  
        
    } catch(err){}

}


//
// provided a multiple choice group @id 
// and the item number of the "not aplicable" alternative @naId
// binds the handlers that toggles the enabled/disabled state of the alternatives 
// when toggeling the checked state of the n/a alternative 
function attachMCDeaktivator(id, naId)
{
    var id, naId;
    try 
    { 
        // get the array of names of the checkboxes
        var nArr = new Array();
        var i = 0;

        try 
        { 
            $('#eq-group-'+id+' input:checkbox').each(function(){  
                // if it is a n/a alternative 
                // bind a onclick handler, which unchecks and deaktivates the remaining alternatives 
                if ($(this).attr("name")== "v["+naId+"]")
                {                            
                    $(this).bind('click', function(){
                        if($(this).attr('checked')== true)
                        {
                            $('#eq-group-'+id+' input:checkbox').each(function(){
                                if ($(this).attr("name") != "v["+naId+"]") { 
                                    $(this).attr("checked", false); 
                                    $(this).attr("disabled", true); 
                                }
                            });
                        }
                        else
                        {
                             $('#eq-group-'+id+' input:checkbox').each(function(){
                                if ($(this).attr("name") != "v["+naId+"]") { 
                                    $(this).attr("disabled", false); 
                                }
                            });
                        }
                    });
                }

                i++;
            });
        } catch (err1){}  
        
    } catch(err){}

}


// makes "others" input line only avaliable when corresponend checkbox is active
// id = item id
function attachMCTextTrigger(id)
{
    try 
    { 
        var id;
        var bChecked = $("td:has(input[name='v["+id+"]'])").children('input:checkbox').attr('checked');
        $("input[name='v["+id+"_input]']").attr('disabled', !bChecked);
        
        $("td:has(input[name='v["+id+"]'])").children('input:checkbox').bind('click', function(){
            var bChecked = $(this).attr("checked");
            $("input[name='v["+id+"_input]']").attr('disabled', !bChecked);
        });
    } catch(err){}   
}

// validated the input line "others" of multiple choice group
// and alerts an error message if the line is empty
// @id = item id
// @2 = boolean: if attachMCTextTrigger should be activated
// @1 = str: custom error message 
function attachMCTextTriggerWithValidation (id)
{
    var id;
    
    var sErrorMessage = 
            (typeof arguments[1] == 'undefined' || arguments[1] == ''
            ? 'Sie haben leider nicht alle Fragen auf dieser Seite Beantwortet. Bitte ergänzen Sie Ihre Antworten!' 
            : arguments[1]);
    var bDisableTrigger =  
            (typeof arguments[2] == 'undefined' || arguments[2] == '' ? false : arguments[2] );

    
            
    if (bDisableTrigger) { attachMCTextTrigger (id); }
    
    $(document).ready(function() {  
        $('#eq-next-link').click(function(){ 

            var bChecked = $("td:has(input[name='v["+id+"]'])").children('input:checkbox').attr('checked');
            var str = $("input[name='v["+id+"_input]']").val();
            if (bChecked && str == "")
            {
                alert(sErrorMessage);
                try {$("input[name='v["+id+"_input]']").focus(); } catch(e){}
                return false;
            }

        });
    });
}

// emulates skipping of the current page
// by hiding the contents of the body tag 
// and firing of the submit event on the questionnaire's form
function skipPage()
{
    $('body').css('display', 'none');
    $('#wrap').css('visibility', 'hidden');
    $(document).ready(function() {
        document.forms[0].submit();
    });
}

// checks the document's referrer
// and redirects the browser to a website of the choice
// if no match can be found
// @referrer - substring of referrer URL to test
// @redirectTarget - URL to redirect to (this must be a properly formed URL, i.e. must include http:// prefix)
// @straight (boolean) - true to redirect if referrer matches, false to rediret if referrer does not match
function referrerRedirect (referrer, redirectTarget, straight)
{
    var referrer, redirectTarget, straight;
    
    try
    {
        var url = document.referrer;
        alert("DEBUG: Please report the following text line to our Support:\n"+url);
        var match = (url.indexOf(referrer) != -1);  // true if substring found, false otherwise
        if (match == straight) 
        {
            window.location.replace(redirectTarget);
        }
             
    } catch(err){}
    
}

// prepends input line with text
// @id - number of the input line variable to prepend : for v12 write 12
// @text - text to prepend
// 3rd argument can carry style definition
function prependInputLine(id, text)
{
    var id, text;
    if (typeof arguments[2] == 'undefined' || arguments[2] == '') 
    {
         style = "color: black; font-weight: normal; font-size: 12px;";
    } else 
    {
         style =  arguments[2];
    }
    try { 
        $("td:has(input[name='v["+id+"]'])").prepend("<span style='"+style+"'>"+text+"</span>");
    } catch(err){}
}

// appends input line with text
// @id - number of the input line variable to append : for v12 write 12
// @text - text to prepend
// 3rd argument can carry style definition    
function appendInputLine(id, text)
{
    var id, text;
    if (typeof arguments[2] == 'undefined' || arguments[2] == '') 
    {
         style = "color: black; font-weight: normal; font-size: 12px;";
    } else 
    {
         style =  arguments[2];
    }
    try 
    { 
         $("td:has(input[name='v["+id+"]'])").children('br').remove();
         $("td:has(input[name='v["+id+"]'])").append("<span style='"+style+"'>&nbsp;"+text+"</span>");
    } catch(err){}

}

// shows random div from a list of given divs and saves its number in an input line
// @id - id of the input line item to save the coice in
// @arguments - list of the div ids
function randomDivs (id)
{
    var id, i, rnd;
    try 
    { 
        for (i=1; i<arguments.length; i++)
        {
            $("#"+arguments[i]).css('display', 'none');
        }
        
        rnd = getRnd(arguments.length - 2);

        $("#"+arguments[rnd+1]).css('display', '');
        
        $(document).ready(function() {   
            saveValue(id, rnd+1);
            $("tr:has(input[name='v["+id+"]'])").parent().css('display', 'none');
        });    
    } catch(err){}  
} 

// shows a div from a set of divs, whoes numer is detrmined by an input variable
// which is normally set and saved in by the randomdivs function
function divSetShow (v)
{
    var v, i;
    
    v =  isNaN( parseInt(v)) ? 1 : parseInt(v);
    
    try 
    {
        for (i=1; i<arguments.length; i++)
        {
            $("#"+arguments[i]).css('display', 'none');
        }

        $("#"+arguments[v]).css('display', '');
    
    } catch(err){}   
}

// attaches jquery datae picke control to a tata field
// needs to import
//<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
//<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
//<script src="http://templates.equestionnaire.de/javascripts/jquery.ui.datepicker-de.js" type="text/javascript"></script>
// @id - number of variable to attach to
datePickerScriptsLoaded = false;
function attachDatePicker (id)
{
    var id;
    
    try 
    {
        if (!datePickerScriptsLoaded) 
        {
            document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>');
            document.write('<sc'+'ript src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></'+'script>');
            document.write('<sc'+'ript src="http://templates.equestionnaire.de/javascripts/jquery.ui.datepicker-de.js" type="text/javascript"></'+'script>');
            datePickerScriptsLoaded = true;
        }
        $(document).ready(function() {
            $("input[name='v["+id+"]']").datepicker({ 
                changeYear: true, 
                changeMonth: true,
                constrainInput: true
            });
            $("input[name='v["+id+"]']").datepicker($.datepicker.regional['de']);
        });
    } catch(e){}
}

// loads letterPaginator.js 
// and initiates letterPaginator control for a given group
// @id = id of the group to attach LetterPaginator to, e.g. "4-1" 
// 1@max = maximum number of checked options - passthrough
letterPaginatorScriptsLoaded = false;
function attachLetterPaginator(id)
{
    var id;
    var max = (typeof arguments[1] == 'undefined' && typeof arguments[1] =='') ? 0 : arguments[1];

    try
    {
        if (!letterPaginatorScriptsLoaded)
        {
            document.write('<sc'+'ript src="http://templates.equestionnaire.de/javascripts/letterPaginator.js" type="text/javascript"></'+'script>');  
            letterPaginatorScriptsLoaded = true;          
        }
        $(document).ready(function() { 
            initLetterPaginator(id, max);
        });        
    } catch(e) {}
    
}
// initiates Completes Counter
// this script ounts completes of a given questionnaire through an AJAX call
// then compares the number of completes with a provied condition
// and shows one of two divs dependend on comparison results
// @qid = id of the questionnaire
// @completesNumbeer = nuber of completes determining the condition
// @div1 = id of the div to show if number of completes is lower than completesNumber  (coupon)
// @div2 = id of the div to show if number of completes is higher than completesNumber  (nocoupon)    

function completesCounter(quid, completesNumber)
{
    var qid, completesNumber;
    var div1 = arguments[2];
    var div2 = arguments[3];
    var realCompletesNumber = 0; // will be returned by AJAX query
    var divToShow;
    try 
    {
        $("#"+div1).css('display', 'none');  
        $("#"+div2).css('display', 'none');  
        // setup an AJAX call
        $(document).ready(function() {
            
            $.ajaxSetup({cache: false});

            var fill_order = new Array();
            var ajax_loaded = false;

            $.get('completesCounter.php', {qid: quid}, function(data) {
              realCompletesNumber = parseInt(data);
              ajax_loaded = true;

              divToShow = (realCompletesNumber <= completesNumber ? div1 : div2);
              $("#"+divToShow).css('display', ''); 
            });


        });  
    } catch(e){}    
}
//--------------------------------------
//--------------------------------------

function InitHelper(){
    //check if jsContainer id is defined, if so - perform search and hide
    if (typeof jsContainer != 'undefined' && typeof jsContainer == 'string') { 
        hideGroupById(jsContainer);
    }
}



//--------------------------------------
//--------------------------------------

// returns a rounded integer randomized number, given rndBasis = maximum number of wanted interval
// getRnd(10) will provide an integer from intervall [0; 10]
// to get a random number between 1 and 10 call (getRnd(9)+1)
function getRnd(rndBasis){
       return Math.round( Math.random() * rndBasis ); 
}

/*
function replacePipes(){
    var o = document.getElementsByTagName('TD');
    for (i=0; i < o.length; i++){
    //alert(o[i].innerHTML);
        o[i].innerHTML = o[i].innerHTML.replace(/\|\|(.*?)\|\|/ig, 'Klicken Sie <a href="http://www.google.de/search?q=$1" target="_blank">HIER</a>');
    }
}
*/

// searches all elements of questionnaire for @search-string and replaces it with @replacement-string
function replaceString(search, replacement){
    var o = document.getElementsByTagName('TD');
    search = search.replace("$", "\\$");
    var searchString = new RegExp(search, "gi");
    for (i=0; i < o.length; i++){
        o[i].innerHTML = o[i].innerHTML.replace(searchString, replacement);
    }
}

// saves a given @value in the input-line named with given @id
// to save value "5" in v[2] call saveValue(2, "5")
function saveValue(id, val){
    var id, val;
    $("input:[name='v[" + id + "]']").val(val);
}
function setValue(id, val){
      saveValue(id, val);
}
function saveValueIncremental(id, val, separator){
    var id, val, separator;
    if ($("input:[name='v[" + id + "]']").val() == '')
    {
           $("input:[name='v[" + id + "]']").val(val);
    } 
    else
    {
        $("input:[name='v[" + id + "]']").val(
            $("input:[name='v[" + id + "]']").val() + separator + val
        );        
    }
}

// gets a value from the input-line named with given @id
// to get value form v[2] call getValue(2)
function getValue(id){
     return $("input:[name='v[" + id + "]']").val();
}

// analog of php's in_array
function in_array(item, arr) {
    for (p=0; p < arr.length; p++) 
    if (item == arr[p]) {return true;}
    return false;
}

// substitute for parseInt -
// returns 0 if value is NAN or the parsed integer value
// @val = string to be parsed
// the defaut value "0" can be substituted by the second argumen
function eqParseInt (val)
{
    var val;
    var defVal = (typeof arguments[1] == 'undefined' || arguments[1] == '') ? 0 : arguments[1];
                                                                  
    val = isNaN( parseInt(val)) ? defVal : parseInt(val); 
    return val;
}
