function debug(msg) { if ($('#debug').length == 0) $('body').prepend('<div id="debug"></div>'); $('#debug').append("<br />" + msg); }
debug($('#dyn_div_1').width());
/**
 * Calculates after the change of an answer if the okay backgroud-image is displayed or not.
 * @return nothing
 */
function calculate_okay_background_images(question_id,answer_id,obj) {  
  var what_to_do = "nothing";
  if(obj.nodeName.toLowerCase() == "input") {// radio....
    switch (obj.type.toLowerCase()) {
    case "radio": // just set the class question_answered
      what_to_do = "add_class";
      break;
    case "text": // text-field is empty -> remove question_answered class, else add the class
      text = obj.value.replace(/\s+/,"");
      if(text == "")
        what_to_do = "remove_class";
      else
        what_to_do = "add_class";
      break;
    case "checkbox":      
      // if a least one checkbox of the checkboxgroup is active add the class question_answered, else remove it
      // search for checked checkbox inputs within the element with the id question_<question_id>
      if(jQuery('input:checked',$('#question_'+question_id)).size() > 0)
        what_to_do = "add_class";        
      else 
        what_to_do = "remove_class";
      break;      
    default:
      alert("Fehler: Unbekannter Fragetyp (input type="+obj.type.toLowerCase()+")?");
      break;
    }
  } else { // combo box
    // if answer_id is numeric -> show the question_answered class (otherwise it is "Bitte auswählen...")
    if(answer_id.match(/[0-9]+/))
      what_to_do = "add_class";
    else
      what_to_do = "remove_class";      
  } 
  // what_to_do -> now do it!
  if(what_to_do == "add_class") {
    if(!$('#question_'+question_id).hasClass("question_answered")) {
      //alert("add_class!");
      $('#question_'+question_id).addClass("question_answered");
    }
  } else if(what_to_do == "remove_class") {
    if($('#question_'+question_id).hasClass("question_answered")) {
      //alert("remove_class!");
      $('#question_'+question_id).removeClass("question_answered");          
    }
  }
}

/**
 * Called if another answer is selected. (Called once for select and once for deselect)
 * @param question_id 
 * @param answer_id
 * @param obj the DOM element
 * @param lid
 * @param sid
 * @return
 */
function lq_change_answer(question_id,answer_id,obj,lid,sid){
  // show products-sidebar on step 2
  if((sid == lid*1000+2 || sid == 2) && obj.checked == true && !changed_on_step_2_to_products) {    
    if(!sidebar_opened)
      show_sidebar();
    if(!sidebar_products_opened)
      change_to_sidebar_products();
    changed_on_step_2_to_products = true;    
  }
  // show answer/question tip
  if(!isNaN(parseInt(answer_id)) && AnswerTips[answer_id][1] && ((obj.type == "checkbox" && obj.checked == true) || (obj.type == "radio" && obj.checked == true) || obj.type == "select-one")) {
    show_answer_tip(question_id, answer_id);
  }
  /*else{ //what should that do? (without that code it works as planned - problem with DD?) 
    if($('#'+"questionTipText"+question_id).html() != QuestionTips[question_id]){
      $('#'+"questionTipShort"+question_id).fadeOut(0, function() {
        $(this).html(QuestionTipsShort[question_id]).fadeIn(0);
        $('#'+"questionTipHeading"+question_id).html(QuestionTipsHeading[question_id]);
        $('#'+"questionTipText"+question_id).html(QuestionTips[question_id]);
        $('#'+"questionTipLink"+question_id).html(QuestionTipsLink[question_id]);
      });
    }
  }*/
  if((obj.type == "radio" && obj.checked == true) || obj.type != "radio") {
    lq_ajax_update(question_id,answer_id,obj,lid,sid);  
  }
}

function show_answer_tip(question_id, answer_id) {
//  $('#qae_question_tip_'+question_id).css({'display' : 'block' , 'visibility' : 'visible' });
  $('#qae_question_tip_'+question_id).removeClass("hide");
  $('#'+"questionTipShort"+question_id).fadeOut(0, function() {
    $(this).html(AnswerTipsShort[answer_id][1]).fadeIn(500);
    $('#'+"questionTipHeading"+question_id).html(AnswerTipsHeading[answer_id][1]);
    $('#'+"questionTipText"+question_id).html(AnswerTips[answer_id][1]);
    $('#'+"questionTipLink"+question_id).html(AnswerTipsLink[answer_id][1]);
  });
  
}

function show_question_tip(question_id) {
  $('#'+"questionTipShort"+question_id).fadeOut(0, function() {
    $(this).html(QuestionTipsShort[question_id]);
    $(this).fadeIn(500);
    $('#'+"questionTipHeading"+question_id).html(QuestionTipsHeading[question_id]);
    $('#'+"questionTipText"+question_id).html(QuestionTips[question_id]);
    $('#'+"questionTipLink"+question_id).html(QuestionTipsLink[question_id]);
  });  
}

function lq_init_combo_answer(question_id){
  answer_id = $("#g_lup_qd"+question_id).val();
  if(!isNaN(parseInt(answer_id)) && AnswerTips[answer_id][1]) {
    $('#'+"questionTipShort"+question_id).html(AnswerTipsShort[answer_id][1]);
    $('#'+"questionTipInner"+question_id).html(AnswerTips[answer_id][1]);
  }
}



/**
 * Called when a re-calculation of the shown products is needed (after answer selection)
 * @param question_id
 * @param answer_id
 * @param obj
 * @param lid
 * @param sid
 * @return
 */
function lq_ajax_update(question_id,answer_id,obj,lid,sid) {
  //show/hide okay background-image
  calculate_okay_background_images(question_id,answer_id,obj);
  var tips_query = get_current_shown_tips_query(question_id,answer_id);
  var answer_value = 0;
  if(obj.type == "checkbox" || obj.type == "radio"){
    if(obj.checked == true) answer_value = 1;
  }
  else if(obj.type == "select-one")
    answer_value = 1;
  else
    answer_value = obj.value;
  // debug how often requests are sent
  //alert("Send Ajax Request!");
  jQuery.get("index.php?action=ajax&lid=" + lid + "&step=" + sid + "&qid=" + question_id + "&aid=" + answer_id + "&type=" + obj.type + "&value=" + answer_value + "&"+tips_query, lq_update_products, "html");
}

function get_current_shown_tips_query(qid, answer_id) {
  var tips_request_url = "";  
/*  $(".qae_question_tip_info>span").each(function(index) {
    // structure: <div id="qae_question_tip_info><span id="questionTipShort{questionId}">Tip-Text</span></div>
    tips_request_url += this.id.replace(/questionTipShort/,"") + "=" + this.innerHTML  + "&"; //+ encodeURIComponent(this.innerHTML) + "&";
  });*/
  // remove last character (must be a "&")
  
  //$(".qae_question_tip_info>span").each(function(index) {
    // structure: <div id="qae_question_tip_info><span id="questionTipShort{questionId}">Tip-Text</span></div>
   // var id = this.id.replace(/questionTipShort/,"");
    if(AnswerTipsShort[answer_id].length != 0) {
      tips_request_url += qid + "_tip_short=" + encodeURIComponent(AnswerTipsShort[answer_id][1]) + "&";
      tips_request_url += qid + "_tip_text=" + encodeURIComponent(AnswerTips[answer_id][1]) + "&";
      tips_request_url += qid + "_tip_heading=" + encodeURIComponent(AnswerTipsHeading[answer_id][1]) + "&";
      tips_request_url += qid + "_tip_link=" + encodeURIComponent(AnswerTipsLink[answer_id][1]) + "&";
    } else if(typeof(QuestionTipsShort) != "undefined" && typeof(QuestionTipsShort[qid]) != "undefined" && 
    		QuestionTipsShort[qid].length != 0) {
      tips_request_url += qid + "_tip_short=" + encodeURIComponent(QuestionTipsShort[qid]) + "&";
      tips_request_url += qid + "_tip_text=" + encodeURIComponent(QuestionTips[qid]) + "&";
      tips_request_url += qid + "_tip_heading=" + encodeURIComponent(QuestionTipsHeading[qid]) + "&";
      tips_request_url += qid + "_tip_link=" + encodeURIComponent(QuestionTipsLink[qid]) + "&";
    }
  //});
  
  
 
//remove last character (must be a "&")
  if(tips_request_url.length > 0)
    tips_request_url = tips_request_url.substr(0,tips_request_url.length-1);
  // debug
  //alert(tips_request_url);
  return tips_request_url;
}

function change_img(event, newImg) {
  $("#fancy_div img:first").attr('src', newImg);
  event.preventDefault();
}

/**
 * This function sets the onclick events of the small images in the product
 * detail view. This is necessary because of FF 3.0 which is not able to 
 * handle duplicate ids. Therefore I have to select different elements instead
 * of selecting elements by ids. 
 * First I select all small images. Then I set the onclick value of each image
 * to the changeImg function. The parameter of this function is the new large
 * image which is set via the value attribute of the <a> tag.
 * 
 */
function set_onclick_event() {  
  var smallImgs = $("#fancy_div a:has(img)");
  for(var i=0; i < smallImgs.size(); i++) {
    var value = smallImgs[i].attributes["value"].value;
    smallImgs[i].attributes["onclick"].value = "change_img(event,'" + value + "')";
  }
  return false;
}

/**
 * Callback function after the re-calculation of products is finished
 * @param data
 * @param status
 * @return
 */
function lq_update_products(data, status) {
    if (status == "success") {
      var question_answers = document.getElementById("container");      
      question_answers.innerHTML = $("#container",data).html();
      reinit_questions_answers(question_answers);
      var current_prods = document.getElementById("current_products");
     /* var tippOverviewContainerEl = document.getElementById("tipp_overview");
      
      if(tippOverviewContainerEl != null || typeof(tippOverviewContainerEl != "undefined")) {
        tippOverviewContainerEl.innerHTML = $("#tipp_overview",data).html();
      }*/
      
      if(current_prods != null) {        
        current_prods.innerHTML = $("#current_products",data).html();
        // re-install fancy box for sidebar-product links
        $("#current_products a").fancybox({
          'padding' : 0
          ,'frameWidth' : 580
          ,'frameHeight' : 550
          ,'hideOnContentClick': false
          ,'callbackOnShow': set_onclick_event
          ,'callbackOnStart': expandLocation
          ,'callbackOnClose': collapseLocation
        });
      }
    /*
	  var question_answers = document.getElementById("container");      
      question_answers.innerHTML = $("#container",data).html();
      reinit_questions_answers(question_answers);
      var current_prods = document.getElementById("current_products");
      var tippOverviewContainerEl = document.getElementById("tipp_overview_container");
      var prefix = "<div id='";
      var index = data.indexOf("tipp_overview");
      index = index - prefix.length;
      
      var dataProducts = data.substring(0, index);
      var dataTipps = data.substring(index, data.length);
      
      if(tippOverviewContainerEl != null || typeof(tippOverviewContainerEl != "undefined")) {
        tippOverviewContainerEl.innerHTML = dataTipps;  
      }
      
      if(current_prods != null) {    
        current_prods.innerHTML = $("#current_products",dataProducts).html();
      
  //      document.getElementById("current_products").innerHTML = data;

        // re-install fancy box for sidebar-product links
        $("#current_products a").fancybox({
          'padding' : 0
          ,'frameWidth' : 580
          ,'frameHeight' : 620
          ,'hideOnContentClick': false
          ,'callbackOnShow': set_onclick_event
        });
      }*/
    } else {
      alert("An error occured!");
    }
}

function reinit_questions_answers(element) {
  $('form.jNice').jNice();
  initCB();
  // re-evaluate all javascript code within element
  $('script',element).each(function(index) {
    eval(this.innerHTML);
  });
  if(sidebar_opened)
    reduce_question_div_width();    
}



// install fancy box for sidebar-product links
$(document).ready(function() { 
  $("#current_products a").fancybox({
    'padding' : 0
    ,'frameWidth' : 580
    ,'frameHeight' : 550
    ,'hideOnContentClick': false
    ,'callbackOnShow': set_onclick_event
    ,'callbackOnStart': expandLocation
    ,'callbackOnClose': collapseLocation
  });
});

// Side Slide / Sidebar

// Flags...
var sidebar_opened = false;
var sidebar_products_opened = false;
var sidebar_tips_opened = false;
var changed_on_step_2_to_products = false;


/**
 * If animated is true the sidbar should be animated using fadeIn. If
 * animated is false the sidebar should be shown without animation
 * 
 * @param animated
 * @return
 */
function show_sidebar(animated) {
  // animate show sideBarContents-div (contains both products & tipps)
  $("#sideBarContents").css({ 'opacity' : '100' , 'visibility' : 'visible' });
  if(animated) {
    $('#sideBarContents').animate({width: 'show', opacity: 'show'}, 'normal');
  }
  else {
    $('#sideBarContents').show();
  }
  reduce_question_div_width();
  sidebar_opened = true;
}

function reduce_question_div_width() {
  // set question- or start-div(s) smaller (if present) - immediately
  if($('#dyn_div_start').length > 0){ 
    $('#dyn_div_start').css({ width: '65%' });
  }
  else{        
    $('#dyn_div_2').css({ width: '65%' });
  }
  $('#dyn_div_1').css({ width: '65%' });
}



function hide_sidebar_animated() {
  // show sideBarContents-div (contains both products & tipps)
  $('#sideBarContents').animate({ width: 'hide', opacity: 'hide'}, 'normal');
  // callback to do some things AFTER the sideBarContents animation has finished
  window.setTimeout(function() {
    // set question- or start-div(s) wider (if present) - immediately
    if($('#dyn_div_start').length > 0){
      $('#dyn_div_start').css({ width: '90%' });
    }
    else{
      $('#dyn_div_2').css({ width: '90%' });
    }
    $('#dyn_div_1').css({ width: '90%' });   
    
    change_sidbar_activation(1,false);
    change_sidbar_activation(2,false);
    
    // set next_link & previous_link's href attribute to sidebar=closed
    set_sidebar_link_url_parameter("closed");
    
    // set flags accordingly        
    sidebar_opened = false;        
  }, 400);
}

function change_to_sidebar_products() {
  // set Tips content to invisible & Products to visible
  $("#sideBarContentsInnerTips").css({ 'visibility' : 'hidden', 'display':'none' });
  $("#sideBarContentsInnerProducts").css({ 'visibility' : 'visible', 'display':'block' });
  // replace backgroud-image according to sidbar active status
  bgImage = $("#sideBar").css('background-image');
  $("#sideBar").css('background-image', bgImage.replace('side_2bg.gif','side_1bg.gif'));
  
  change_sidbar_activation(1,true);
  change_sidbar_activation(2,false);
  
  // set next_link & previous_link's href attribute to sidebar=products
  set_sidebar_link_url_parameter("products");

  // set flags accordingly        
  sidebar_products_opened = true;      
  sidebar_tips_opened = false;
}

function change_to_sidebar_tips() {
  // set Products content to invisible & Tips to visible
  $("#sideBarContentsInnerProducts").css({ 'visibility' : 'hidden', 'display':'none' });
  $("#sideBarContentsInnerTips").css({ 'visibility' : 'visible', 'display':'block' });
  // replace backgroud-image according to sidbar active status
  bgImage = $("#sideBar").css('background-image');
  $("#sideBar").css('background-image', bgImage.replace('side_1bg.gif','side_2bg.gif'));
  
  change_sidbar_activation(1,false);
  change_sidbar_activation(2,true);
  
  // set next_link & previous_link's href attribute to sidebar=tips
  set_sidebar_link_url_parameter("tips");
  
  // set flags accordingly
  sidebar_products_opened = false;
  sidebar_tips_opened = true;
}

function change_sidbar_activation(sidebar_number, activate) {
  var png_name = (sidebar_number == 1) ? "product" : "i";
  var sidebar_id_name = "#sideBarTab"+sidebar_number+"_img";  
  sideBarTab_img_src = $(sidebar_id_name).attr('src');
  if(sideBarTab_img_src != null) {
    if(activate)
      $(sidebar_id_name).attr('src', sideBarTab_img_src.replace(png_name+'.gif',png_name+'-active.gif'));
    else
      $(sidebar_id_name).attr('src', sideBarTab_img_src.replace(png_name+'-active.gif',png_name+'.gif'));
  }
}

// onclick handler for products
$(document).ready(function() {
  $("a#ToggleSideBarContents1").click(click_handler_products);
});

/**
 * If showAnimated is true the sidbar should be animated using fadeIn. If
 * showAnimated is false the sidebar should be shown without animation
 * 
 * @param event
 * @param showAnimated if the sidebar should be animated or not
 * @return
 */
function click_handler_products(event, showAnimated) {
  if($('#sideBarContents').is(':hidden')){ // show
    animate = (typeof(showAnimated) == "undefined") ? true : showAnimated;
    
    show_sidebar(animate);
    change_to_sidebar_products();
  }
  else if(sidebar_products_opened){ // hide
    hide_sidebar_animated();
  }
  if(sidebar_tips_opened){ // change highlight to sidebar1
    change_to_sidebar_products();
  } 
  return false;
}

// onclick handler for tips
$(document).ready(function() {
  $("a#ToggleSideBarContents2").click(click_handler_tips);
});

function click_handler_tips(event, showAnimated) {
  if($('#sideBarContents').is(':hidden')){ // show
    animate = (typeof(showAnimated) == "undefined") ? true : showAnimated;
      
    show_sidebar(animate);
    change_to_sidebar_tips();
  }
  else if(sidebar_tips_opened){ // hide
    hide_sidebar_animated();
  }
  if(sidebar_products_opened){ // change highlight to sidebar2
    change_to_sidebar_tips();
  } 
  return false;
}

/**
 * Sets the sidebar url parameter in next_link and previous_link url to a new value
 * @param new_value the new value to set
 * @return nothing
 */
function set_sidebar_link_url_parameter(new_value) {
  next_link_href = $('#next_link').attr('href');
  previous_link_href = $('#previous_link').attr('href');
  if(next_link_href)
    $('#next_link').attr('href',set_or_replace_url_parameter(next_link_href,"sidebar",new_value));
  if(previous_link_href)
    $('#previous_link').attr('href',set_or_replace_url_parameter(previous_link_href,"sidebar",new_value));
}


/**
 * Sets or replaces an url_param in an url with a new value
 * @param url the url to search the url_param
 * @param url_param the url_param to set or replace
 * @param new_parm_value the new value for url_param
 * @return the modified url
 */
function set_or_replace_url_parameter(url,url_param,new_parm_value) {  
  if (url.search(url_param) != -1) {
    // urlparameter is present! -> remove it!
    url = url.replace(new RegExp("&"+url_param+"=[^&]*"),"");
  } 
  // urlparameter is not there -> just attach it
  url += "&" + url_param + "=" + new_parm_value;
 
  return url;
}

//Tooltip
$(function() {

  $('#lq_tooltip').tooltip({
    track: true,
    delay: 0,
    showURL: false,
    showBody: " - ",
    extraClass: "pretty",
    fixPNG: true,
    opacity: 0.5,
    left: -120
  });

  $('#lq_tooltip1').tooltip({
    track: true,
    delay: 0,
    showURL: false,
    showBody: " - ",
    extraClass: "pretty",
    fixPNG: true,
    opacity: 0.5,
    left: -120
  });

  $('#lq_tooltip2').tooltip({
    track: true,
    delay: 0,
    showURL: false,
    showBody: " - ",
    extraClass: "pretty",
    fixPNG: true,
    opacity: 0.5,
    left: -120
  });

  $('#lq_tooltip3').tooltip({
    track: true,
    delay: 0,
    showURL: false,
    showBody: " - ",
    extraClass: "pretty",
    fixPNG: true,
    opacity: 0.5,
    left: -120
  });

});


/**
 * Change the content in the Tipp Overview view
 * Is implemented as tabs
 * 
 * @param event
 * @param num
 * @return
 */
function changeTab(event, num) {
  var fragId = "tippfragment-" + num;
  
  //hideAnswerTipps();
  activateTab(num);
  
  var fragments = $("#fancy_div div[id^='tippfragment']");
  for(var i=1; i<=fragments.size(); i++) {
    
    if(i==num) {
      fragments[i-1].className = "";
    }
    else {
      fragments[i-1].className = 'hide';
    }
  }
  return false;
}

/**
 * Style the activated tab in the tipp overview
 * @param num
 * @return
 */
function activateTab(num) {
  if(typeof(num) == "undefined") num = 1;
  var steps = $("#fancy_div li div div");
  var text = $("#fancy_div li span");
  for(var i=0; i<steps.size(); i++) {
    var classNameParent = steps[i].parentNode.parentNode.className;
    var classNameSibling = text[i].className;
   
    
    if(parseInt(steps[i].innerHTML) == num) {
      //if this match is not equal null then the step is already active
      if(classNameParent.match("nav_divactive") == null) {
        classNameParent = classNameParent.replace("nav_div", "nav_divactive");
        classNameSibling = classNameSibling.replace("hide", "hideactive");
      }
    }
    else {
      classNameParent = classNameParent.replace("nav_divactive", "nav_div");
      classNameSibling = classNameSibling.replace("hideactive", "hide");
    }
    
    steps[i].parentNode.parentNode.className = classNameParent;
    text[i].className = classNameSibling;
  }
}

/**
 * This is neede for the eyetracking study. 
 * The link must change when a fancybox opens because otherwise
 * the eyetracking software does not recognize a change
 */
function expandLocation() {
  window.location.hash = "lookup";
}

/**
 * This is neede for the eyetracking study. 
 * The link must change when a fancybox opens because otherwise
 * the eyetracking software does not recognize a change
 */
function collapseLocation() {
  window.location.hash = " ";
}

function mask() {
  $('#background').mask("Ergebnisse werden geladen...");
}


//Tab browsing
$(document).ready(function() {  
    var $tabs = $('#rotate > ul').tabs();   
    $tabs.tabs({ fx: { opacity: 'toggle' } }); // ad function after last ) e.g:.tabs('rotate', 2000)    
    $tabs.tabs('select',1);
    // a little bit dirty, but works
    function switch_to_mylookup() { // bind click event to link
      $tabs.tabs('select', 2); // switch to third tab
      return false;
    }  
    $('#link_to_mylookup_frag1_left').click(switch_to_mylookup);
    $('#link_to_mylookup_frag1_right').click(switch_to_mylookup);    
    $('#link_to_mylookup_frag2_left').click(switch_to_mylookup);
    $('#link_to_mylookup_frag2_right').click(switch_to_mylookup);
	
	$('#background').unmask();
});

