function enter_pressed(e) {
  var keycode;
  if (window.event)
    keycode = window.event.keyCode;
  else if (e)
    keycode = e.which;
  else
    return true;

  if (keycode == 13) {
    return true;
  } else
    return false;
}

var open_help_div;

function clearText(thefield){
  if (thefield.defaultValue==thefield.value)
    thefield.value = ""
} 


function show_hints (form) {
  Form.getElements(form).collect(function(elm) {
    if (elm.title) {
        insert_advice(elm);
  }
  }).all();
};


function help_box(name, title) {

  if (open_help_div != null && document.getElementById("help_div_" + open_help_div).className != "help_div_hidden") {
    help_box_close(open_help_div);
    if (open_help_div == name) {
      open_help_div = null;
      return null;
    }
  }
	
  help_div = document.getElementById("help_div_" + name);
	
  if (!help_div) {
    var help_div = document.createElement("span");
    help_div.setAttribute("id", "help_div_" + name);
  }
	
  var img_elm = document.getElementById("advice-" + name);
  var div_elm = document.getElementById("help_box_" + name);
	
  help_div.innerHTML = "<div style='float: left; width: 133px; line-height: 14px;' id='div_message_" + name + "'>" + title + "</div><div id='close_x_" + name + "' onClick='help_box(\"" + name + "\", \"\")'>x</div>";
	
  div_elm.appendChild(help_div);
	
  var close_x_elm = document.getElementById("close_x_" + name);
	
  if (title && img_elm.className == "help_icon") {
    help_div.className = "help_div_visible_yellow";
    close_x_elm.className = "help_div_x_yellow";
    img_elm.className = "help_icon_yellow";
  }
  else if (title && img_elm.className == "help_icon_error") {
    help_div.className = "help_div_visible_error";
    close_x_elm.className = "help_div_x_error";
    img_elm.className = "help_icon_error";
  }

  open_help_div = name;
	
}

function help_box_close(name){

  var help_div = document.getElementById("help_div_" + name);
  var img_elm = document.getElementById("advice-" + name);
  if (help_div && img_elm) {
    if (help_div.className == "help_div_visible_yellow") {
      help_div.className = "help_div_hidden";
      img_elm.className = "help_icon";
    }
    else if (help_div.className == "help_div_visible_error") {
      help_div.className = "help_div_hidden";
      img_elm.className = "help_icon_error";
    }
  }
}

function insert_advice(elm) {

  var advice = '<span id="help_box_' + elm.name + '"><span onClick="help_box(\'' + elm.name + '\', document.getElementById(\'advice-' + elm.name + '\').title)" class="help_icon" id="advice-' + elm.name + '" title="' + elm.title + '"></span></span>';
  switch (elm.type.toLowerCase()) {
    case 'checkbox':
    case 'radio':
      var p = elm.parentNode;
      if(p) {
        new Insertion.Bottom(p, advice);
      } else {
        new Insertion.After(elm, advice);
      }
      break;
    default:
      new Insertion.After(elm, advice);
  }
}

Object.extend(Validation, {
  test : function(name, elm, useTitle) {
    var v = Validation.get(name);
    try {
      help_box_close(open_help_div);
      open_help_div = null;
			
      if(!v.test($F(elm), elm)) {
        if (!$('advice-' + elm.name)) {
          insert_advice(elm);
        }
        var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
        var errorMsgString = error_head + " " + errorMsg + " " + (elm.title ? elm.title : "");

        $('advice-' + elm.name).removeClassName('help_icon');
        $('advice-' + elm.name).addClassName('help_icon_error');
        $('advice-' + elm.name).title = errorMsgString;
			    
        elm.removeClassName('validation-passed');
        elm.addClassName('validation-failed');

        return false;
      } else if ($('advice-' + elm.name)){
        if (!$('advice-' + elm.name).title) {
          $('advice-' + elm.name).remove();
        } else {
          $('advice-' + elm.name).removeClassName('help_icon_error');
          $('advice-' + elm.name).addClassName('help_icon');
          $('advice-' + elm.name).title = elm.title;
        }
        elm.removeClassName('validation-failed');
        elm.addClassName('validation-passed');
        return true;
      } else {
        elm.removeClassName('validation-failed');
        elm.addClassName('validation-passed');
        return true;
      }
    } catch(e) {
      throw(e)
    }
  }
});

function initPage() {
  var map = $('map');
  if(map) {
    var diamond_list = map.getElementsByTagName('AREA');
    for(var i=0; i<diamond_list.length; i++){
      el = diamond_list[i];
      el.style.display = 'none';
      Event.observe(
        el.id,
        'mouseover',
        function() {
          var diamond_id = this.id;
          diamond_id = diamond_id.substring(diamond_id.indexOf('_')+1, diamond_id.length);
          $(diamond_id).style.display = 'inline';
        }
        );
            
      Event.observe(
        el.id,
        'mouseout',
        function() {
          var diamond_id = this.id;
          diamond_id = diamond_id.substring(diamond_id.indexOf('_')+1, diamond_id.length);
          $(diamond_id).style.display = 'none';
        }
        );
            
      Event.observe(
        el.id,
        'click',
        function() {
          var diamond_id = this.id;
          diamond_id = diamond_id.substring(diamond_id.indexOf('_')+1, diamond_id.length);
          window.location = $(diamond_id + '_a').href;
          return false;
        }
        );
    }
  }
}

/**
 * IE7 Fix where BODY element was skipped which produced an error
 * @author Marko.Kruustuk
 * @date 22.04.2009
 */
//-----------------------------------------------------------------------------
Object.extend(Epoch.prototype, {
  getTop : function (element) //PRIVATE: returns the absolute Top value of element, in pixels
  {
    var oNode = element;
    var iTop = 0;
	    
    while(oNode.tagName != 'BODY' && oNode.tagName != 'HTML') {
      iTop += oNode.offsetTop;
      oNode = oNode.offsetParent;
    }
	    
    return iTop;
  }
});
//-----------------------------------------------------------------------------
Object.extend(Epoch.prototype, {
  getLeft : function (element) //PRIVATE: returns the absolute Left value of element, in pixels
  {
    var oNode = element;
    var iLeft = 0;
	    
    while(oNode.tagName != 'BODY' && oNode.tagName != 'HTML') {
      iLeft += oNode.offsetLeft;
      oNode = oNode.offsetParent;
    }
	    
    return iLeft;
  }
});

function show_notice() {
  if ($('hide_notice').style.display == 'none') {
    $('hide_notice').style.display = 'block';
    setTimeout('document.forms["name"].submit();', 1000);
  }
}

function eurCalculatoret() {
  window.open( "http://www.mkindlustus.ee/wp-content/themes/insurance/calculator/et/index.html", "myWindow", "status = 0, height = 220, scrollbars=0, width = 230, resizable = 0" );
}

function eurCalculatorru() {
  window.open( "http://www.mkindlustus.ee/wp-content/themes/insurance/calculator/ru/index.html", "myWindow", "status = 0, height = 220, scrollbars=0, width = 230, resizable = 0" );
}

Object.extend(Epoch.prototype, {
  setLang : function ()
  {
    this.daylist = new Array(ep_Su,ep_Mo,ep_Tu,ep_We,ep_Th,ep_Fr,ep_Sa,ep_Su,ep_Mo,ep_Tu,ep_We,ep_Th,ep_Fr,ep_Sa); /*<lang:en>*/
    this.months_sh = new Array(ep_Jan,ep_Feb,ep_Mar,ep_Apr,ep_May,ep_Jun,ep_Jul,ep_Aug,ep_Sep,ep_Oct,ep_Nov,ep_Dec);
    this.monthup_title = ep_next_month;
    this.monthdn_title = ep_previous_month;
    this.clearbtn_caption = ep_clear;
    this.clearbtn_title = ep_clears;
    this.maxrange_caption = ep_max;
  }
});

Object.extend(Epoch.prototype, {
  calConfig : function ()
  {
    //this.mode = 'flat'; //can be 'flat' or 'popup'
    this.displayYearInitial = this.curDate.getFullYear(); //the initial year to display on load
    this.displayMonthInitial = this.curDate.getMonth(); //the initial month to display on load (0-11)
    this.rangeYearLower = this.curDate.getFullYear();
    this.rangeYearUpper = this.curDate.getFullYear() + 1;
    this.minDate = new Date(2005,0,1);
    this.maxDate = new Date(2037,0,1);
    this.startDay = 1; // the day the week will 'start' on: 0(Sun) to 6(Sat)
    this.showWeeks = false; //whether the week numbers will be shown
    this.selCurMonthOnly = false; //allow user to only select dates in the currently displayed month
    this.clearSelectedOnChange = true; //whether to clear all selected dates when changing months
		
    //flat mode-only settings:
    //this.selectMultiple = true; //whether the user can select multiple dates (flat mode only)
	
    switch(this.mode) //set the variables based on the calendar mode
    {
      case 'popup': //popup options
        this.visible = false;
        break;
      case 'flat':
        this.visible = true;
				
        break;
    }
    this.setLang();
  }
});

Object.extend(Epoch.prototype, {
  getTop : function (element) //PRIVATE: returns the absolute Top value of element, in pixels
  {
    var oNode = element;
    var iTop = 0;

    while(oNode.tagName != 'BODY' && oNode.tagName != 'HTML') {
      iTop += oNode.offsetTop;
      oNode = oNode.offsetParent;
    }

    return iTop;
  }
});
//-----------------------------------------------------------------------------
Object.extend(Epoch.prototype, {
  getLeft : function (element) //PRIVATE: returns the absolute Left value of element, in pixels
  {
    var oNode = element;
    var iLeft = 0;

    while(oNode.tagName != 'BODY' && oNode.tagName != 'HTML') {
      iLeft += oNode.offsetLeft;
      oNode = oNode.offsetParent;
    }

    return iLeft;
  }
});

function loaderOverlay(selector) {
  var p = jQuery(selector).offset();
  var h = jQuery(selector).height();
  var w = jQuery(selector).width();
  jQuery('#loaderOverlay')
  .css({
    top: p.top + 'px',
    left: p.left + 'px',
    width: w + 'px',
    height: h + 'px'
  })
  .show();
  jQuery('#loader').show();
  var lh = jQuery('#loader').height();
  var lw = jQuery('#loader').width();
  jQuery('#loader')
  .css({
    top: (p.top + h/2 - lh/2) + 'px',
    left: (p.left + w/2 - lw/2) +  'px'
  });
  jQuery(window).resize(function() {
    loaderOverlay(selector);
  });
}

jQuery(document).ready(function($) {
  var m = $('#content-box .mainpagebanner');
/*
  $('form')
  .find('input,select,textarea')
  .filter(':visible')
  .filter('[title]')
  .each(function(){
    $(this).after('<div class="info" style="position: absolute; float:none;"><div class="text">'  + $(this).attr('title') + '</div></div>');
  });
  var setInfoOffsets = function() {
    $('div.info').each(function() {
      var ip = $(this).prev();
      var coords = getOffsets(ip.get(0));
      console.log(coords, ip.outerWidth());
      $(this).css({
        "left": (coords.x + ip.outerWidth() + 2) +"px",
        "top": (coords.y - 196) +"px"
      });

    });
  }
  setTimeout(function(){
    setInfoOffsets();
  }, 1);
  
  $(window).resize(function() {
  
    });
*/
  if (m.length) {
    var as = $('#steps a');
    m.bannerslider({
      Autoanimate : true,
      TimeOut : 15000
    }).animated(function(current){
      var ul = $('#steps');
      ul.find('.stepActive').removeClass('stepActive');
      $(ul.children().get(current)).addClass('stepActive');
    });
    as.each(function(i){
      $(this).click(function(e){
        e.preventDefault();
        m.bannerslider().navigate(i);
      });
    });
  }
  
var fix_total_area = function() {
    var m2 = $('#total_area').val().replace(',', '.');
    $('#total_area').val(m2);
  	}
$('#total_area').change(fix_total_area);

function allowNumbersOnly(event){
    // Allow: backspace, delete, tab, escape and dot
    if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 110 || event.keyCode == 188 || event.keyCode == 190 ||
         // Allow: Ctrl+A
        (event.keyCode == 65 && event.ctrlKey === true) || 
         // Allow: home, end, left, right
        (event.keyCode >= 35 && event.keyCode <= 39)) {
             // let it happen, don't do anything
             return;
    }
    else {
        // Ensure that it is a number and stop the keypress
        if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
            event.preventDefault(); 
        }   
    }
}

var set_building_insurance_sum = function(userInput) {
	userInput = (userInput == undefined) ? '0' : userInput;
	
    var type = $('#insurance_object').val();
    var m2 = $('#total_area').val().replace(',', '.');
    var material = $('#building_material').val();
    
    if (type && m2 && material) {
      var sum = 0;
      switch (type){
      case '1': // korteri siseviimistlus
    	  sum = (material == 2) ? 400 : 400;
    	  break;
      case '2': // korteri siseviimistlus koos mõttelise osaga
    	  sum = (material == 2) ? 600 : 600;
    	  break;
      case '3': // mõtteline osa hoonest
    	  sum = (material == 2) ? 840 : 900;
    	  break;
      case '4': // elamu
    	  sum = (material == 2) ? 840 : 900;
    	  break;
      case '5': // paarismaja
    	  sum = (material == 2) ? 840 : 900;
    	  break;
      case '6': // ridaelamuboks
    	  sum = (material == 2) ? 840 : 900;
    	  break;
      case '7': // mõisa eluhoone
    	  sum = (material == 2) ? 840 : 900;
    	  break;
      case '8': // suvila
    	  sum = (material == 2) ? 600 : 670;
    	  break;
      case '9': // saun
    	  sum = (material == 2) ? 600 : 670;
    	  break;
      case '11': // garaas
    	  sum = (material == 2) ? 435 : 500;
    	  break;
      case '12': // laut
    	  sum = (material == 2) ? 435 : 500;
    	  break;
      case '13': // ait
    	  sum = (material == 2) ? 435 : 500;
    	  break;
      case '15': // puukuur
    	  sum = (material == 2) ? 270 : 400;
    	  break;
      case '16': // töökoda
    	  sum = (material == 2) ? 270 : 400;
    	  break;
      case '17': // kõrvalhoone/laohoone
    	  sum = (material == 2) ? 270 : 400;
    	  break;
      case '18': // klaaskasvuhoone
    	  sum = (material == 2) ? 165 : 165;
    	  break;
      case '19': // muinsuskaitse objekt
    	  sum = (material == 2) ? 0 : 0;
    	  break;
      }
      
      var insSum = Math.ceil(sum * m2);
      var calcInput = $('#building_insurance_sum').val().replace(',', '.');
      calcInput = Math.ceil($('#building_insurance_sum').val());
      $('#building_insurance_sum').val(calcInput);
      if(userInput == 1){
    	  if (calcInput < insSum) {
        	  $('#building_insurance_sum').val(insSum);
          }
      } else {
    	  $('#building_insurance_sum').val(insSum);
      }
      
    }
  }
  $('#total_area').blur(set_building_insurance_sum);
  $('#total_area').keydown(function(event){allowNumbersOnly(event);});
  $('#building_insurance_sum').blur(function(){set_building_insurance_sum(1);});
  $('#building_insurance_sum').keydown(function(event){allowNumbersOnly(event);});
  $('#insurance_object').change(set_building_insurance_sum);
  $('#building_material').change(set_building_insurance_sum);
  
  	jQuery('#droppingFrame').slideDown(500);
  	
	if(jQuery.browser.msie) {
  	    /* IE obscures the option text for fixed-width selects if the text 
  	     * is longer than the select. To work around this we make the width 
  	     * auto whenever the drop down is visible.
  	     */
  	    jQuery("select.fixed-width").livequery(function(){
  	        /* Use mousedown rather than focus because the focus event gets 
  	         * interrupted and the dropdown does not appear 
  	         */
  	    	jQuery(this)
  	        .mousedown(function(){
  	            if(jQuery(this).css("width") != "auto") {
  	                var width = jQuery(this).width();
  	                jQuery(this).data("origWidth", jQuery(this).css("width"))
  	                       .css("width", "auto");
  	                /* if the width is now less than before then undo */
  	                if(jQuery(this).width() < width) {
  	                	jQuery(this).css("width", jQuery(this).data("origWidth"));
  	                }
  	            }
  	        })
  	        /* Handle blur if the user does not change the value */
  	        .blur(function(){
  	        	jQuery(this).css("width", jQuery(this).data("origWidth"));

  	        })
  	        /* Handle change of the user does change the value */
  	        .change(function(){
  	        	jQuery(this).css("width", jQuery(this).data("origWidth"));

  	        });
  	    });
  	}
	
	jQuery(function() {
		jQuery('.nyroModal').nyroModal();
	});
});

function getOffsets(el) {
  var o = {
    x : el.offsetLeft,
    y : el.offsetTop
  };
  if (el.offsetParent != null) {
    var po = getOffsets(el.offsetParent);
    o.x += po.x;
    o.y += po.y;
  }
  return o;
}

function hideDroppingFrame(){
	jQuery.ajax({url: "/wp-content/plugins/insurancenew/setDroppingFrameSession.php"});
	jQuery("#droppingFrame").slideUp(500);
}
