// process.js
var VImg = [];
var updateHtm = false;
var FLEET_BASE = 'V-Flotte Base';
var FLEET_ADVANCED = 'V-Flotte Avanzato';
var LOCATEME = 'Localizzami';
var LOCATEME_WEB = 'Localizzami WEB';
var Product = '';


function $(id){
  return document.getElementById(id);
}

function preloadImg(ids){
  for(var i = 0; i < ids.length; i++){ 
    VImg[ids[i]] = new Image();
    VImg[ids[i]+'_on'] = new Image();
    VImg[ids[i]].src = 'images/btn_'+ids[i]+'.png';
    VImg[ids[i]+'_on'].src = 'images/btn_'+ids[i]+'_on.png';
  }
}

function getSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [myWidth, myHeight]
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function showFocus(obj){
  if(!document.getElementById) return;
  obj.style.border = "1px solid #FFCC66";
}

function showBlur(obj){
  if(!document.getElementById) return;
  obj.style.border = "1px solid #6699CC";
} 

function addLayer(id,cls,vis,htm){
  var d = document.createElement("DIV");
  d.setAttribute("id",id);
  if(cls){
    d.setAttribute("class",cls );
    d.setAttribute("className",cls);
  }
  d.innerHTML = htm;
  if(vis) d.style.display = vis;
  document.getElementsByTagName('body')[0].appendChild(d);     
}

function showPopWin(){
  var width = document.getElementById('base_div').offsetWidth;
  var height = document.getElementById('wrapper').offsetHeight+16;
  var size = getSize();
  var scroll = getScrollXY();
  var pageY = size[1]; 
  if(pageY > height) height = pageY;
  var scrollY = scroll[1];
  var popDiv = document.getElementById('PopWin');
  var obj = v_getObj('order');
  popDiv.innerHTML = v_getOrderForm(Product, obj.htm);
  document.getElementById('anc_captcha').onclick = function(){v_captcha('img_captcha'); return false;};
  document.getElementById('anc_send').onclick = function(){v_submit(obj.type); return false;};
  popDiv.style.width = 'auto';
  popDiv.style.height = 'auto';
  popDiv.style.top = parseInt((pageY-popDiv.offsetHeight)/2)+scrollY+'px';
  popDiv.style.left = parseInt((width-popDiv.offsetWidth)/2)+'px';
  addShadow('Shadow',width,height);
  document.getElementById('Shadow').style.visibility = 'visible';
  popDiv.style.visibility = 'visible';
}

function hidePopWin(){
  document.getElementById('Shadow').style.visibility = 'hidden';
  document.getElementById('Shadow').style.width = '1px';
  document.getElementById('PopWin').style.visibility = 'hidden';  
}

function addShadow(id,w,h){
  var obj = document.getElementById(id)
  obj.style.top = 0;
  obj.style.left = 0; 
  obj.style.width = w+'px';
  obj.style.height = h+'px';
  obj.style.opacity = .50;
  obj.style.filter = 'alpha(opacity=50)';
}

function v_getProduct(p){
  var prd;
  switch(p){
    case 'flotte_base': 
      prd = FLEET_BASE;
      break;
    case 'flotte_avanzato': 
      prd = FLEET_ADVANCED;
      break;
    case 'localizzami': 
      prd = LOCATEME; 
      break;
    case 'localizzami_web': 
      prd = LOCATEME_WEB; 
      break;
    case 'accessori': 
      prd = FLEET_ADVANCED; 
      break;    
  }
  return prd;
}

function v_check(){
  var page = '';
  if($('product')){
    page = $('product').value;
    Product =  v_getProduct(page);
  }
  if(document.form) document.form.btn.onclick = v_process;
  else if(page == 'flotte_base'){
   $('anc_costs').onclick = function(){v_hide('costs','services','friend'); v_show('costs'); return false;};
   $('anc_services').onclick = function(){v_hide('costs','services','friend'); v_show('services'); return false;};
   $('anc_friend').onclick = function(){v_hide('costs','services','friend'); v_show('friend'); return false;};
   $('anc_order').onclick = function(){showPopWin(); return false;};
   var ids = ['costs','costs_on','services','services_on','order','order_on','friend','friend_on'];
   addLayer('PopWin',null,false,'');
   addLayer('Shadow','shadow',false,'');
   preloadImg(ids);
 }else if(page == 'flotte_avanzato'){
   $('anc_costs').onclick = function(){v_hide('costs','services','friend','accessories'); v_show('costs'); return false;};
   $('anc_services').onclick = function(){v_hide('costs','services','friend','accessories'); v_show('services'); return false;};
   $('anc_accessories').onclick = function(){v_hide('costs','services','friend','accessories'); v_show('accessories'); return false;};
   $('anc_friend').onclick = function(){v_hide('costs','services','friend','accessories'); v_show('friend'); return false;};
   $('anc_order').onclick = function(){showPopWin(); return false;};
   var ids = ['costs','costs_on','services','services_on','order','order_on','friend','friend_on','accessories','accessories_on'];
   addLayer('PopWin',null,false,'');
   addLayer('Shadow','shadow',false,'');
   preloadImg(ids);
 }else if(page == 'localizzami' || page == 'localizzami_web'){
   $('anc_data').onclick = function(){v_hide('data','functions'); v_show('data'); return false;};
   $('anc_functions').onclick = function(){v_hide('data','functions'); v_show('functions'); return false;};
   $('anc_order').onclick = function(){showPopWin(); return false;};
   var ids = ['data','data_on','functions','functions_on','order','order_on'];
   addLayer('PopWin',null,false,'');
   addLayer('Shadow','shadow',false,'');
   preloadImg(ids);
 }else if(page == 'accessori'){
   $('anc_planning').onclick = function(){v_hide1('planning','activity','contacts','privacy','driver'); v_show1('planning'); return false;};
   $('anc_activity').onclick = function(){v_hide1('planning','activity','contacts','privacy','driver'); v_show1('activity'); return false;};
   $('anc_contacts').onclick = function(){v_hide1('planning','activity','contacts','privacy','driver'); v_show1('contacts'); return false;};
   $('anc_privacy').onclick = function(){v_hide1('planning','activity','contacts','privacy','driver'); v_show1('privacy'); return false;};
   $('anc_driver').onclick = function(){v_hide1('planning','activity','contacts','privacy','driver'); v_show1('driver'); return false;};
   $('anc_order').onclick = function(){showPopWin(); return false;};
   var ids = ['details','details_on','order','order_on'];
   addLayer('PopWin',null,false,'');
   addLayer('Shadow','shadow',false,'');
   preloadImg(ids);
 }else if(page){
   updateHtm = true;
   $('anc_info').onclick = function(){v_hide('info','call','demo'); v_show('info'); return false;};
   $('anc_call').onclick = function(){v_hide('info','call','demo'); v_show('call'); return false;};
   $('anc_demo').onclick = function(){v_hide('info','call','demo'); v_show('demo'); return false;};
   var ids = ['info','info_on','call','call_on','demo','demo_on'];
   preloadImg(ids);
 }
}

function v_captcha(id){
  var r = Math.floor(Math.random()*1000);
  $(id).src = 'http://www.illocalizzatore.it/coge/captcha.jpg?rnd='+r;
}

function v_hide(){
  if(arguments){
    for(var i = 0; i < arguments.length; i++){
      if(updateHtm) $('div_'+arguments[i]).innerHTML = '';
      $('div_'+arguments[i]).style.display = 'none';
      $('btn_'+arguments[i]).src = VImg[arguments[i]].src;
    }
  }
}

function v_hide1(){
  if(arguments){
    for(var i = 0; i < arguments.length; i++){
      if(updateHtm) $('div_'+arguments[i]).innerHTML = '';
      $('div_'+arguments[i]).style.display = 'none';
      $('btn_'+arguments[i]).src = VImg['details'].src;
    }
  }
}

function v_show(){
  if(arguments){
    for(var i = 0; i < arguments.length; i++){
      if(updateHtm){
        var obj = v_getObj(arguments[i]);
        $('div_'+arguments[i]).innerHTML = obj.htm;
        $('anc_captcha').onclick = function(){v_captcha('img_captcha'); return false;};
        $('anc_send').onclick = function(){v_submit(obj.type); return false;};
      }
      $('div_'+arguments[i]).style.display = 'block';
      $('btn_'+arguments[i]).src = VImg[arguments[i]+'_on'].src;
    }
  }  
}

function v_show1(){
  if(arguments){
    for(var i = 0; i < arguments.length; i++){
      $('div_'+arguments[i]).style.display = 'block';
      $('btn_'+arguments[i]).src = VImg['details_on'].src;
    }
  }  
}

function v_getObj(arg){
  var obj = {type: null, htm: '<table border="0" cellspacing="5" cellpadding="0" >'};
  obj.htm +=
    '<tr>'+
      '<th align="right" scope="row">Nome Cognome o Ragione sociale</th>'+
      '<td><input id="name" name="name" style="width: 200px; padding-left: 3px;" /></td>'+
    '</tr>'+
    '<tr>'+
      '<th align="right" scope="row">e-mail</th>'+
      '<td><input id="mail" name="mail" style="width: 280px; padding-left: 3px;" /></td>'+
    '</tr>'+
    '<tr>'+
      '<th align="right" scope="row">Telefono</th>'+
      '<td><input id="phone" name="phone" style="width: 120px; padding-left: 3px;" /></td>'+
    '</tr>';    
  switch(arg){
    case 'info':
      obj.type = 1;
      obj.htm += 
          '<tr>'+
            '<th align="right" valign="top" style="padding-top: 3px" scope="row">Messaggio</th>'+
            '<td><textarea id="message" style="width: 320px; height: 100px; padding-left: 3px; padding-right:3px;"></textarea></td>'+
          '</tr>';
      break;
    case 'call': 
      obj.type = 2;
      obj.htm += 
          '<tr>'+
            '<th align="right" scope="row">Appuntamento</th>'+
            '<td><input id="date" name="date" style="width: 120px; text-align:center" /> (gg/mm/aaaa hh.mm)</td>'+
          '</tr>'+
          '<tr>'+
            '<th align="right" valign="top" style="padding-top: 3px" scope="row">Messaggio</th>'+
            '<td><textarea id="message" style="width: 320px; height: 100px; padding-left: 3px; padding-right:3px;"></textarea></td>'+
          '</tr>';
      break;
    case 'demo':
      obj.type = 3;
      obj.htm += 
          '<tr>'+
            '<th align="right" scope="row">Appuntamento</th>'+
            '<td><input id="date" name="date" style="width: 120px; text-align:center" /> (gg/mm/aaaa hh.mm)</td>'+
          '</tr>'+
          '<tr>'+
            '<th align="right" valign="top" style="padding-top: 3px" scope="row">Messaggio</th>'+
            '<td><textarea id="message" style="width: 320px; height: 100px; padding-left: 3px; padding-right:3px;"></textarea></td>'+
          '</tr>';
      break;
    case 'order': 
      obj.type = 4;
      obj.htm += 
          '<tr>'+
            '<th align="right" valign="top" style="padding-top: 3px" scope="row">Numero apparati</th>'+
            '<td><input id="deviceNum" name="deviceNum" style="width: 40px; text-align:right; padding-right: 3px;" value="1" /></td>'+
          '</tr>'+
          v_getOrderProduct();
      break;
  }
  obj.htm +=
    '<tr>'+
      '<th align="right" valign="top" style="padding-top: 3px" scope="row">Inserire i caratteri nell\'immagine</th>'+
        '<td width="320">'+
          '<div><input id="captcha" name="capthcha" style="width: 80px; padding-left: 3px;" /></div>'+
          '<div style="margin-top:5px;"><a id="anc_captcha" href="#">Se non vedi i caratteri aggiorna l\'immagine</a></div>'+
          '<img id="img_captcha" src="http://www.illocalizzatore.it/coge/captcha.jpg" border="0" style="margin-top:5px;" alt="captcha"/>'+
        '</td>'+
      '</tr>'+
      '<tr>'+
        '<th> </th>'+
        '<td height="40" align="center" valign="bottom">'+
          '<div style="float: left;">'+
            '<a href="#" id="anc_send"><img border="0" src="images/btn_send.png" /></a>'+
          '</div>'+
          '<div id="div_response" style="padding-top: 4px; margin-left: 140px; font-weight:bold;"></div>'+
        '</td>'+
      '</tr>'+
    '</table>';
  return obj;
}

function v_getOrderProduct(){
  var htm = '';
  switch(Product){
    case FLEET_ADVANCED:
      htm +=
        '<tr>'+
          '<th align="right" style="padding-top: 3px" scope="row">Accessori</th>'+
          '<td></td>'+
        '</tr>'+
        '<tr>'+
          '<td colspan="2">'+v_getAccessories()+'</td>'+
        '</tr>';
      break;
    case LOCATEME:
    case LOCATEME_WEB:
    case FLEET_BASE: 
      htm += '';        
  }
  return htm;
}

function v_getAccessories(){
  var htm =
    '<table border="0" cellspacing="5" cellpadding="0" style="margin-left: 135px; background-color:#eeeeee">'+
      '<tr>'+
        '<th align="right" >V-Pianificazione</th>'+
        '<td><input id="chk_planning" name="chkPlanning" type="checkbox" value="" /></td>'+
      '</tr>'+
      '<tr>'+
        '<th align="right" >V-Attivit&agrave;</th>'+
        '<td><input id="chk_activity" name="chk_activity" type="checkbox" value="" /></td>'+
      '</tr>'+
      '<tr>'+
        '<th align="right" >V-contatti</th>'+
        '<td><input id="chk_contacts" name="chk_contacts" type="checkbox" value="" /></td>'+
      '</tr>'+
      '<tr>'+
        '<th align="right" >Filtro Privacy</th>'+
        '<td><input id="chk_privacy" name="chk_privacy" type="checkbox" value="" /></td>'+
      '</tr>'+
      '<tr>'+
        '<th align="right" valign="top" style="padding-top: 3px" scope="row">Riconoscimento autista</th>'+
        '<td><input id="chk_driver" name="chk_driver" style="width: 40px; text-align:right; padding-right: 3px;" value="0" /></td>'+
      '</tr>'+
   '</table>';
  return htm;
}

function v_getOrderForm(prd,txt){
  var htm =
    '<div style="background-color:#ffffff; padding:15px;">'+
      '<div style="position: absolute; right: -11px; top: -10px;">'+
        '<a href="#" id="anc_close" onclick="hidePopWin();"><img border="0" src="images/closebox.png" alt="closebox"/></a>'+
      '</div>'+
      '<div style="margin-bottom:5px; color:#800000; font-size:14px;"><b>ORDINE: '+prd+'</b></div>'+
      txt+
    '</div>';
  return htm;
}

function v_checkForm(){
  return true;
}

function v_getOrderInfo(){
   var txt = 'Prodotto: '+ Product+'; Numero apparati: '+$('deviceNum').value;
   switch(Product){
     case FLEET_ADVANCED:
       txt += '; Accessori: '+
         ($('chk_planning').checked ? 'Pianificazione; ' : '')+
         ($('chk_activity').checked ? 'Attivitą; ' : '')+
         ($('chk_contacts').checked ? 'Contatti; ' : '')+
         ($('chk_privacy').checked ? 'Filtro privacy; ' : '')+
         ($('chk_driver').value > 0 ? 'Riconoscimento autista'+$('chk_driver').value : '');
       break;
     case LOCATEME:
     case LOCATEME_WEB:
     case FLEET_BASE: 
   }
   return txt;
}
function v_submit(type){
  if(v_checkForm()){
    var info = type == 4 ? v_getOrderInfo() : $('message').value;
    var url = '../../coge/addContact?'+
      'name='+$('name').value+
      '&email='+$('mail').value+
      '&phoneNumber='+$('phone').value+
      '&date='+($('date') ? $('date').value : '')+
      '&note='+info+
      '&captchaText='+$('captcha').value+
      '&typeID='+type+
      '&sendMail=true'+
      '&rnd='+Math.floor(Math.random()*1000);
    $('div_response').innerHTML = 'Invio in corso...';
    ajax.get(url);
  }
}

function v_process(){
  var c1 = 0.05;
  var c2 = 0.12;
  var n = document.form.num.value;
  var c = document.form.cost.value;
  var k = document.form.km.value;
  if(n != '' && c != '' && k != ''){
    c = parseFloat(c.replace(/,/, '.'));
    document.form.res0.value = (n*c*k).toFixed(2);
    document.form.res1.value = (n*c*k*c1).toFixed(2);
    document.form.res2.value = (n*c*k*c2).toFixed(2);
  }
}

var ajax = {
  get: function(url){
    try{    
      var xmlObj = null;
      if(window.XMLHttpRequest) xmlObj = new XMLHttpRequest();
      else if(window.ActiveXObject) xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
      else return;
      xmlObj.onreadystatechange = function(){if(xmlObj.readyState == 4) ajax.parse(xmlObj);};
      xmlObj.open ('GET', url, true);
      xmlObj.send ('');
    }catch(e){
      alert(e.message);
    }       
  },

  parse: function(xmlObj){
    try{
      if(xmlObj.responseXML){
        var element = xmlObj.responseXML.getElementsByTagName('element')[0];
        if(element.getElementsByTagName('error').length > 0){
          var code = element.getElementsByTagName('error')[0].getAttribute('code');
          if(code == '1') $('div_response').innerHTML = 'Caratteri dell\'immagine non corretti!';          
          else $('div_response').innerHTML = 'Invio fallito! Controlla i dati insetiti.';
        }else{
          $('div_response').innerHTML = 'Invio completato! Grazie.';
          v_captcha('img_captcha');
        }
      }else{
        alert(xmlObj.responseText);
      }
    }catch(e){
      alert(e.message);
    }
    
  }
}