jQuery.noConflict();
var selectedBuilingType = '';
var sending=false;
//  ==== READY =================================================================
jQuery(document).ready(function() {
  
  // create slider -------------------------------------------------------------
  setHelp(); 
  createSlider("#slider_living_space", ".slider_living_space_value", 100, 500, 40, "qm", 'normal');
  createSlider("#slider_price", ".slider_price_value", 35, 120, 70, "ct", 'energyprice');
  createSliderSmall("#slider_pipe", 5, 1, 4);
  createSliderSmall("#slider_insulation", 5, 1, 4);
  createSlider("#slider_heaterpump_age", ".slider_heaterpump_age_value", 5, 1, 4, "Jahre", 'special');
  createSlider("#slider_heater_age", ".slider_heater_age_value", 5, 1, 4, "Jahre", 'special');
  
  
  // show arrow calls ----------------------------------------------------------
  
  jQuery(":radio").click(function() {
    showArrow(this);
    sendData();
  });
  
  // send data calls -----------------------------------------------------------
  jQuery("select").change(function () {
    selectedBuilingType = this.value;
    sendData();
  });
   
  jQuery("input[@name='year']").keyup(function() {
    sendData();
  });
  
  //gets fast typers (CSO)
  jQuery("input[@name='year']").blur(function() {
    sendData();
  });
 
  jQuery("input[@type='reset']").click(function() {
    reset();
  });
  
  jQuery("#calculator_content form").submit(function () { 
    return false; 
  });
  
  // init call -----------------------------------------------------------------
  
  reset();//init();

});

// =============================================================================
function setHelp(){
  jQuery(".helpdiv").each(function(){
    prefix=this.id.split('_div');
    jQuery('#'+prefix[0]+"_info").show();
    jQuery('#'+prefix[0]+"_info").mouseover(function(e){(showHelp(e,this))});
    jQuery('#'+prefix[0]+"_info").mouseout(function(){(hideHelp(this))});
  });
}

function showHelp(evt,el){
  extraOffsets=doBrowserSwitch();
  prefix=el.id.split('_info');
  jQuery('#'+prefix[0]+"_div").css('top',jQuery(el)[0].offsetTop);//evt.pageY
  jQuery('#'+prefix[0]+"_div").css('left',jQuery(el)[0].offsetLeft+(jQuery(el)[0].offsetWidth*3));//evt.pageX+20
  jQuery('#'+prefix[0]+"_div").show();
}

function hideHelp(el){
  prefix=el.id.split('_info');
  jQuery('#'+prefix[0]+"_div").hide();
}


function init() {
  jQuery("#slider_price").slider("moveTo", "55");
  jQuery(".info_area").css("visibility", "hidden");
  selectedBuilingType = jQuery("select")[0].value;
  sending=false;
  
  sendData();
}

//returns Top and left position modificators in case of IE
function doBrowserSwitch ()
{
  var browser=navigator.appName;
  var extraOffsetLeft=0;
  var extraOffsetTop=0;
 /* if (browser == 'Microsoft Internet Explorer')
  {
    extraOffsetLeft = 260;
    extraOffsetTop = 120;
  }*/
  offsets = new Array()
  offsets['left']=extraOffsetLeft;
  offsets['top']=extraOffsetTop;
  return offsets;
}

function reset() {
sending=true;
jQuery('input[name=type][value=0]').attr("checked", "checked");
  jQuery("#slider_living_space").slider("moveTo", "120");
  jQuery("#slider_pipe").slider("moveTo", "0");
  jQuery("#slider_insulation").slider("moveTo", "0");
  jQuery("#slider_heaterpump_age").slider("moveTo", "0");
  jQuery("#slider_heater_age").slider("moveTo", "0");
  init();
}

// creates a slider
function createSlider(sliderId, sliderValue, minValue, maxValue, stepValue, ending, mode, isSliderPrice) {
  jQuery(sliderId).slider({
    min:minValue,
    max:maxValue,
    steps:stepValue,
    start:function(e, ui) {
      jQuery(sliderValue).fadeIn('fast');
      switch(mode) {
        case 'special':
          jQuery(sliderValue).text(getUiValue(ui.value)+" "+ending);
          break;
        case 'normal':
           jQuery(sliderValue).text(ui.value+" "+ending);  
           break;
        case 'energyprice':
          priceKW=ui.value/10;
          priceKW=String(priceKW);
          priceKW=priceKW.replace(/\./,',');
          jQuery(sliderValue).html(ui.value+" "+ending+" je l oder m³ <br> "+priceKW+" "+ending+" je kWh");  
          break;
      }
      showArrowForSlider(sliderId);
    },
    slide:function(e,ui) {
      switch(mode) {
        case 'special':
          jQuery(sliderValue).text(getUiValue(ui.value)+" "+ending);
          break;
        case 'normal':
           jQuery(sliderValue).text(ui.value+" "+ending);  
           break;
        case 'energyprice':
          priceKW=ui.value/10;
          priceKW=String(priceKW);
          priceKW=priceKW.replace(/\./,',');
          jQuery(sliderValue).html(ui.value+" "+ending+" je l oder m&sup3; <br> "+priceKW+" "+ending+" je kWh");  
          break;
      }
    },
    stop:function(e,ui) {
      jQuery(sliderValue).fadeOut('fast');
      sendData();
    }
  });
}

// creates a slider 
function createSliderSmall(sliderId, minValue, maxValue, stepValue) {
  jQuery(sliderId).slider({
    min:minValue,
    max:maxValue,
    steps:stepValue,
    start:function(e, ui) {
      showArrowForSlider(sliderId);
    },
    stop:function(e, ui) {
      sendData();
    }
  });
}

function showArrowForSlider(ids) {
  extraOffset= doBrowserSwitch();
  if (ids != "#slider_living_space" && ids != "#slider_price") {
    //jQuery(".info_area").css("visibility", "hidden");
    jQuery("#info_area").css("visibility", "visible");  
  jQuery("#info_area").css('top',jQuery(ids)[0].offsetTop-(jQuery("#info_area")[0].offsetHeight/2));
  jQuery("#info_area").css('left',jQuery('.bullet_info')[0].offsetLeft+30);//evt.pageX+20 
   }
  else{
   jQuery(".info_area").css("visibility", "hidden");
  }
}

function showArrow(ids) {
  extraOffset= doBrowserSwitch();
  jQuery("#info_area").css("visibility", "visible");  
  jQuery("#info_area").css('top',jQuery(ids)[0].offsetTop-(jQuery("#info_area")[0].offsetHeight/2));
  jQuery("#info_area").css('left',jQuery('.bullet_info')[0].offsetLeft+30);
}

// retuns the slider value
function getSlidervalue(sliderId) {
  return jQuery(sliderId).slider('value');
}

function getUiValue(val) {
  var value = ''
  switch(val) {
    case 5:
      value = 20;
    break;
    case 4:
      value = 15;
    break;
    case 3:
      value = 10;
    break;
    case 2:
      value = 7.5;
    break;
    case 1:
      value = 5;
    break;
    default:
     value = 5;
  }
  return value;
}

// sends the data to php and receives the json return
  function sendData() {
  if(!sending){
    var data = {
      'livingSpace' : getSlidervalue("#slider_living_space"),
      'buildingType': selectedBuilingType,
      'buildingAge' : jQuery("input[@name='year']")[0].value,
      'energyPrice' : getSlidervalue("#slider_price"),    
      'isolation'   : getSlidervalue("#slider_pipe"),
      'insulation'  : getSlidervalue("#slider_insulation"),
      'userType'    : jQuery("input:checked").val(),
      'heaterPumpAge' : getSlidervalue("#slider_heaterpump_age"),
      'heaterAge'   : getSlidervalue("#slider_heater_age")
    };
    sending=true;
  //index.php?id="+pageId
    jQuery.post("/index.php?eID=calculateSavings", data,
      function(data){
         sending=false;
         jQuery("div.potenzial span").text(data.energySaving);
         jQuery("div.verbrauch span").text(data.consumption);
         jQuery("div.result_total span").text(data.energySaving);
         jQuery("div.kosten span").text(data.cost);
         jQuery("div.info_area p span").text(data.energySaving);
         jQuery("#year_allocation").removeAttr("style", "color:#F06127;");
         if(data.allocation == "nicht möglich.") {
           jQuery("#year_allocation").attr("style", "color:#F06127;");
         }
         jQuery("#year_allocation").text("Zuordnung: " + data.allocation);
         jQuery("span#pipeSaving").text(data.pipeSaving);
         jQuery("span#insulationSaving").text(data.insulationSaving);
         jQuery("span#heaterAgeSaving").text(data.heaterAgeSaving);
         jQuery("span#heaterTypeSaving").text(data.typeSaving);
         
      }, "json");
      }
  }

  function sendPDFData() 
  {
    setPdfFormValue('pdf_consumption_text', jQuery('.verbrauch_text').text());
    setPdfFormValue('pdf_consumption', jQuery('.verbrauch span').text());
    setPdfFormValue('pdf_cost_text', jQuery('.kosten_text').text());
    setPdfFormValue('pdf_cost', jQuery('.kosten span').text());
    setPdfFormValue('pdf_street', getFormValue('strasse_hausnummer'));
    setPdfFormValue('pdf_zipcode', getFormValue('plz'));
    setPdfFormValue('pdf_city', getFormValue('ort'));
    setPdfFormValue('pdf_buildingtype', getFormValue('building_type'));
    setPdfFormValue('pdf_livingspace', getSlidervalue("#slider_living_space"));
    setPdfFormValue('pdf_yearbuilt', jQuery("input[@name='year']")[0].value);
    setPdfFormValue('pdf_yearbuilt_allocation', jQuery("#year_allocation").html());
    setPdfFormValue('pdf_gasprice', getSlidervalue("#slider_price"));
    setPdfFormValue('pdf_isolationcellar', getSlidervalue("#slider_pipe"));
    setPdfFormValue('pdf_isolationroof', getSlidervalue("#slider_insulation"));
    setPdfFormValue('pdf_heatingtype', jQuery("input:checked").val());
    setPdfFormValue('pdf_ageheaterpump', getSlidervalue("#slider_heaterpump_age"));
    setPdfFormValue('pdf_ageheater', getSlidervalue("#slider_heater_age"));
    setPdfFormValue('pdf_result_isolationcellar',  jQuery("#pipeSaving").html());
    setPdfFormValue('pdf_result_isolationroof', jQuery("#insulationSaving").html());
    setPdfFormValue('pdf_result_heatingtype', jQuery("#heaterTypeSaving").html());
    setPdfFormValue('pdf_result_heaterpumpage', jQuery("#heaterAgeSaving").html());
    setPdfFormValue('pdf_result_heaterage', jQuery("#heaterAgeSaving").html());
    setPdfFormValue('pdf_result_total', jQuery("#result_total span:first").html());
    
    var formElem=document.getElementById('calculatorPdfForm');
    formElem.submit();
  }

  function setPdfFormValue(fieldId, fieldValue)
  {
    document.getElementById(fieldId).value=fieldValue;
  }

  function getFormValue(fieldId)
  {
  return document.getElementById(fieldId).value;
  }

