//funzione per riprendere l'oggetto del player youtube
var ytplayer
function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("IdMonitorV4YTPlayer");
  //ytplayer.playVideo();
}


$(document).ready(function()
{  
  
  //screenshots gallery
  
  if($("a.screenshots").length > 0)
    //$("a.screenshots").prettyPhoto();
    $("a[rel^='prettyPhoto']").prettyPhoto({
			animation_speed: 'normal', /* fast/slow/normal */
			slideshow: 5000, /* false OR interval time in ms */
			autoplay_slideshow: false, /* true/false */
			opacity: 0.80, /* Value between 0 and 1 */
			show_title: true, /* true/false */
			allow_resize: true, /* Resize the photos bigger than viewport. true/false */
			default_width: 500,
			default_height: 344,
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'facebook', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
			hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
			wmode: 'opaque', /* Set the flash wmode attribute */
			autoplay: true, /* Automatically start videos: True/False */
			modal: false, /* If set to true, only the close button will close the window */
			overlay_gallery: true, /* If set to true, a gallery will overlay the fullscreen image on mouse over */
			keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */
			changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
			callback: function(){} /* Called when prettyPh*/
    })
  
  //------
	
  $("#ResAreaSubmit").click(function(){
    $("#ResAreaForm").submit();
    return false;
  })
  
  $('div.sliderTop').cycle({ 
    fx:     'fade', 
    timeout: 6000,
    pager:  '#sliderPager',
    pagerAnchorBuilder : function(idx, slide) { 
        if(idx==0) {var str = '<li class="pal"><a href="#" class="pal activeSlide">'+(idx+1)+'</a></li>';} else {var str = '<li class="pal"><a href="#" class="pal">'+(idx+1)+'</a></li>';}
        return str
    },
    before:   onBeforeSlide,
    after: function(){ $("div.sliderTop img").css("background", "none") }

  });
  
  /*  ----  menu ---  */
  
  $('#jsddm > li').bind('mouseover', jsddm_open)
  $('#jsddm > li').bind('mouseout',  jsddm_timer)
  
  
  $("a.mainm").click(function(){
    return false;
  })
  
  
  /*Contact form*/
  $("div.formErr").hide()
  $("input.textIn, textarea.textIn").keypress(function(){ $("#"+$(this).attr("id")+"_err").slideUp("fast") })
  $("input.textIn, textarea.textIn").focus(function(){ $(this).addClass("sel"); $("#"+$(this).attr("id")+"_err").slideUp("fast") })
  $("input.textIn, textarea.textIn").blur(function(){ $(this).removeClass("sel"); })
  
  $("div.scrlWrap").scroll(function(){ return false; })
  
  $("ul.submit a.submit, ul.submit a.next, ul.submit a.skip").click(function(){ $("#contact_form").submit(); return false; })
  $("ul.submit a.prev").click(function(){ 
    if(globalStep==3){
      $("div.stepContainer").animate({left: "-620px"}, 500, "swing")
      $("div.sidecont_rounded").hide()
      $("div[data-step='step2']").fadeIn("fast")
      globalStep=2
    }else if(globalStep==2){
      $("div.stepContainer").animate({left: "0"}, 500, "swing")
      $("div.sidecont_rounded").hide()
      $("div[data-step='step1']").fadeIn("fast")
      globalStep=1
    }
    return false; 
  })
  
  var thing = String($("#what_sel").html())
  var globalThing
  var globalThingSelected = 100
  
  if(thing=="woman"){globalThing = 1}
  if(thing=="monitor"){globalThing = 2}
  if(thing=="man"){globalThing = 3}
  if(thing=="lock"){globalThing = 4}
  if(thing=="house"){globalThing = 5}
  if(thing=="folder"){globalThing = 6}
  
  $("ul.capc a").click(function(){
    $("ul.capc a").removeClass("sel")
    $(this).addClass("sel")
    globalThingSelected = parseInt(String($(this).attr("class")).replace("c","") )
    $("#form_thing_err").slideUp("fast")
    return false;
  })
  
  var globalStep = 1
  
  $("#contact_form").submit(function(){
    var name = Trim(String($("#form_name").val()))
    var organization = Trim(String($("#form_organization").val()))
    var address = Trim(String($("#form_address").val()))
    var city = Trim(String($("#form_city").val()))
    var country = Trim(String($("#form_country").val()))
    var zip = Trim(String($("#form_zip").val()))
    var state = Trim(String($("#form_state").val()))
    var phone = Trim(String($("#form_phone").val()))
    var mphone = Trim(String($("#form_mphone").val()))
    var email = Trim(String($("#form_email").val()))
    var website = Trim(String($("#form_website").val()))
    var learned = Trim(String($("#form_learned").val()))
    var notes = Trim(String($("#form_notes").val()))
    
    if(globalStep == 1){
      var myErr = ""
      var imgMyErr = "<img style='margin:0 10px 0 0;' src='/images/arrUp.jpg' alt='Error in field value' />"
      
      if(name.length<=0){
        myErr = imgMyErr + "Name is obligatory."
        $(document).scrollTo( $(".homeText"), 300, function(){
          $("#form_name_err").html(myErr).slideDown("fast")
        })
        return false
      }
      if(organization.length<=0){
        myErr = imgMyErr + "Organization is obligatory."
        $(document).scrollTo( $(".homeText"), 300, function(){
          $("#form_organization_err").html(myErr).slideDown("fast")
        })
        return false
      }
      if(country.length<=0){
        myErr = imgMyErr + "Country is obligatory."
        $(document).scrollTo( $(".homeText"), 300, function(){
          $("#form_country_err").html(myErr).slideDown("fast")
        })
        return false
      }
      if(phone.length>0 && isNaN(phone.replace(/ /g, ""))){
        myErr = imgMyErr + "Telephone number must be numeric."
        $(document).scrollTo( $(".homeText"), 300, function(){
          $("#form_phone_err").html(myErr).slideDown("fast")
        })
        return false
      }
      if(mphone.length>0 && isNaN(mphone.replace(/ /g, ""))){
        myErr = imgMyErr + "Mobile phone number must be numeric."
        $(document).scrollTo( $(".homeText"), 300, function(){
          $("#form_mphone_err").html(myErr).slideDown("fast")
        })
        return false
      }
      if(email.length<=0){
        myErr = imgMyErr + "E-mail is obligatory."
        $(document).scrollTo( $(".homeText"), 300, function(){
          $("#form_email_err").html(myErr).slideDown("fast")
        })
        return false
      }
      if(!emailCheck(email)){
        myErr = imgMyErr + "Invalid e-mail format."
        $(document).scrollTo( $(".homeText"), 300, function(){
          $("#form_email_err").html(myErr).slideDown("fast")
        })
        return false
      }
      if(website.length<=0){
        myErr = imgMyErr + "Website is obligatory."
        $(document).scrollTo( $(".homeText"), 300, function(){
          $("#form_website_err").html(myErr).slideDown("fast")
        })
        return false
      }
      
      if(globalThingSelected==100){
        myErr = "Please select a thing to be sure you're human."
        $(document).scrollTo( $(".homeText"), 300, function(){
          $("#form_thing_err").html(myErr).fadeIn(100).fadeOut(100).fadeIn(100)
        })
        return false
      }
      if(globalThingSelected!=globalThing){
        myErr = "You clicked a wrong thing, please try again."
        $(document).scrollTo( $(".homeText"), 300, function(){
          $("#form_thing_err").html(myErr).fadeIn(100).fadeOut(100).fadeIn(100)
        })
        return false
      }
      
      //se è il primo step invio la mail
      $("#ajax-loader").show()
      $.get("sendForm.asp?"+$(this).serialize(), function(data){
        if(data=="ok"){
          $("div.stepContainer").css("width","1250px")
          $("#step2").show()
          $("div.stepContainer").animate({left: "-620px"}, 500, "swing")
          $("#topDescContact").html("Thank you for your request we will contact you as soon as possible.")
          $("div.sidecont_rounded").hide()
          $("div[data-step='step2']").fadeIn("fast")
          globalStep = 2
          
          $(document).scrollTo( $(".homeText"), 300)
          
          //qui fa partite il codice si conversione di adword
          
          document.getElementById("conv_iframe").src = 'googleAdConversionCode.html'
          
        }else{
          alert("There was an error on form submit, please try again later")
          $("#ajax-loader").hide()
        }
      })
      return false;
    }else if(globalStep == 2){
      $("#ajax-loader2").show()
      $.get("sendFormStep2.asp?"+$(this).serialize(), function(data){
        if(data=="ok"){
          $("div.stepContainer").css("width","1860px")
          $("div.scrlWrap").css("height","730px")
          $("#step3").show()
          $("div.stepContainer").animate({left: "-1230px"}, 500, "swing")
          $("#topDescContact").html("To better <strong>satisfy our customer’s needs</strong> we kindly ask you to <strong>send us the following information:</strong>")
          $("div.sidecont_rounded").hide()
          $("div[data-step='step3']").fadeIn("fast")
          
          $(document).scrollTo( $(".homeText"), 300)
          globalStep = 3
        }else{
          alert("There was an error on form submit, please try again later")
          $("#ajax-loader2").hide()
        }
      })      
      return false;
    }else if(globalStep == 3){
      
      var cont=0
      $(".quest1").each(function(){
        if(String($(this).attr("checked"))=="true")
          cont++
      })
      if(cont==0){
        alert("Select an option for the first question, please")
        return false;
      }
      
      cont=0
      $(".quest2").each(function(){
        if(String($(this).attr("checked"))=="true")
          cont++
      })
      if(cont==0){
        alert("Select an option for the second question, please")
        return false;
      }
      
      if(String($("input[name='quest2_risp1']").attr("checked"))=="true" && Trim(String($("input[name='quest2_risp3']").val())).length<=0 ){
        alert("Please fill in the software system you are conducting interviews with in the text field.")
        return false;
      }
      
      cont=0
      $(".quest3").each(function(){
        if(String($(this).attr("checked"))=="true")
          cont++
      })
      if(cont==0){
        alert("Select an option for the third question, please")
        return false;
      }
      
      if(Trim(String($("input[name='risposta4']").val()))=="" ){
        alert("Please fill in a number in the text field of the fourth question.")
        return false;
      }
      
      
      $("#ajax-loader3").show()
      $.get("sendFormSurv.asp?"+$(this).serialize(), function(data){
        if(data=="ok"){
          $("#ajax-loader3").hide()
          $("#survey").slideUp(300, function(){
            $("#thanks").fadeIn(300)
            $("div.sidebar").fadeOut("fast", function(){
              $("div.homeText").css("margin-left", "130px")
              $("div.scrlWrap").css("overflow", "hidden")
              $("div.scrlWrap").animate({height: "250px"}, 300)
              
              $("#topDescContact").html("Thank you for your time.")
            })
          })
          
        }
      })
      return false;
    }
      
    
  })
  
  
  $("input[name='quest2_risp3']").change(function(){
    
    $("#risposta2").val("Yes - "+$(this).val())
      
  })
  
  $(".survTable span, .survTable input[type='checkbox'],").click(function(){
    var inpClass = String($(this).attr("class")).replace("sp_","")
    var actvName = String($(this).attr("data-rel"))
    
    if(inpClass!="quest3"){
      $("."+inpClass).attr("checked", false)
      $(this).attr("checked", true)
      $("input[name='"+actvName+"']").attr("checked", true)
    }else{
      if(String($(this).attr("class")).indexOf("sp_")!=-1  ){
        
        if(String($("input[name='"+actvName+"']").attr("checked"))== "true" )
          $("input[name='"+actvName+"']").attr("checked", false)
        else
          $("input[name='"+actvName+"']").attr("checked", true) 
        
      }
      
    }
       
    var myVal
    if(inpClass=="quest1"){
      if(actvName!="undefined"){myVal = $(this).html() }else{ myVal = $("span[data-rel='"+$(this).attr("name")+"']").html()}
      $("#risposta1").val(myVal)
    }else if(inpClass=="quest2"){
      if(actvName!="undefined"){myVal = $(this).html() }else{ myVal = $("span[data-rel='"+$(this).attr("name")+"']").html()}
      if(myVal=="Yes"){
        $("input[name='quest2_risp3']").show()
      }else{
        $("input[name='quest2_risp3']").hide()
        $("input[name='quest2_risp3']").val("")
      }
      
      $("#risposta2").val(myVal+" - "+$("input[name='quest2_risp3']").val())
      
    }else if(inpClass=="quest3"){
      var myStrVal = ""
      $("input.quest3").each(function(){
        if(String($(this).attr("checked"))=="true")
          myStrVal += $("span[data-rel='"+$(this).attr("name")+"']").html()+"-"
      })
      //if(actvName!="undefined"){myVal = $(this).html() }else{ myVal = $("span[data-rel='"+$(this).attr("name")+"']").html()}
      $("#risposta3").val(myStrVal)
      
    }
    
  })
  
  $("span.sp_info").click(function(){
    if( String($("input[name='"+$(this).attr("data-rel")+"']").attr("checked"))=="true" ) 
      $("input[name='"+$(this).attr("data-rel")+"']").attr("checked", false)
    else  
      $("input[name='"+$(this).attr("data-rel")+"']").attr("checked", true)
  })
  
  var selOpened = false
  var initHeight = $("div.textIn").height()
  
  $("div.textIn").hover(
    function(){ if(!selOpened) {$(this).css("background-color", "#D0D0D0").css("border","1px solid #63C8F0")} },
    function(){ if(!selOpened) {$(this).css("background-color", "#E5E5E5").css("border","1px solid #FFF")} }
  )
    
  $(document).click(function(){
    if(selOpened==true){
      $("div.textIn").animate({height: initHeight}, 200)  
      $("div.textIn").css("background-color", "#E5E5E5").css("border","1px solid #FFF")
    }
  })
  
  $("div.textIn").click(function(){ 
    event.stopPropagation();
  })
  
  var initMainSelValue = $("div.textIn a:first").html()
  $("div.textIn a").click(function(){
    
    if(String($("div.textIn").css("background-color"))!="#D0D0D0")
      $("div.textIn").css("background-color", "#D0D0D0").css("border","1px solid #63C8F0")
    
    $("div.textIn a:first").html(initMainSelValue)
    if(selOpened == true){
      $("div.textIn").animate({height: initHeight}, 200)
      $("div.textIn a:first").html($(this).html())
      selOpened=false
    }else{
      $("div.textIn").animate({height: $("div.textIn ul").height()}, 300)
      selOpened=true
    }
    $("#form_learned").val($(this).attr("rel"))
    return false;
  })
  
  /*area video*/
  
  //inizializzo il player

  if($("#YTContainer").length>0){
    var params = { allowScriptAccess: "always" };
    var atts = { id: "IdMonitorV4YTPlayer", hd: "1" , wmode: "opaque"};
    swfobject.embedSWF("http://www.youtube.com/e/l1btAL00wOA?enablejsapi=1&playerapiid=ytplayer", "YTContainer", "870", "519", "8", null, null, params, atts);
  }
  
  /*$("#takeALook li a").click(function(){
    $("#mainVideoContainer").hide()
    $("#mainVideoContainerPlay").slideDown(700)
    if (ytplayer){
      ytplayer.playVideo();
    }
    
    return false;
  })*/
  $("#closeOverview").click(function(){
    $("#mainVideoContainerPlay").slideUp(300, function(){
      $("#mainVideoContainer").fadeIn(300)
    })
    if (ytplayer){
      //ytplayer.seekTo(0)
      ytplayer.stopVideo();
    }
    
    return false;
  })
  
  $(".videoItem, .videoItem *").click(function(){
    $(this).find("a:first").trigger("click")
  })
  
  $(".videoItem a, #takeALook li a").click(function(){
    ytID = String($(this).attr("data-YT"))
    
    $(document).scrollTo(160, 700, function(){
      $("#mainVideoContainer").hide()
      $("#mainVideoContainerPlay").slideDown(700, function(){
        if (ytplayer){
          ytplayer.loadVideoById(ytID)
          ytplayer.playVideo()
        }  
      })
    })
    
    return false;
  })
  
  $(".videoItem").hover(
    function(){
      $(this).addClass("videoItemOver")
    },
    function(){
      $(this).removeClass("videoItemOver")
    }
  )
  
  
  /*acquisto licenze*/
    
  var costoGiornalieroSingolaLicenza = 3;//(in euro)
  var costoAttivazioneLicenza = 20;//(in euro)
    
  $("#licenses_order_form input[name='date_from']").datepicker({ minDate: 0, dateFormat: "dd/mm/yy"});
  $("#licenses_order_form input[name='date_from']").keypress(function(){ return false;});
  
  $("#licenses_order_form input[name='licenses_number'], #licenses_order_form input[name='days']").keypress(function(e) {
    if(e.keyCode < 48 || e.keyCode > 57)
      return false;
  });
  
  $("#licenses_order_form input[name='licenses_number'], #licenses_order_form input[name='days']").keyup(function(e) {
    if(e.keyCode < 48 || e.keyCode > 57)
      return false;
    else{
      var nGG = parseInt($("#licenses_order_form input[name='days']").val());
      var nLc = parseInt($("#licenses_order_form input[name='licenses_number']").val());
      
      if(!isNaN(nGG) && !isNaN(nLc)){
        $("div.riepilogo_licenze span.operator_am").html(costoGiornalieroSingolaLicenza*nGG*nLc)
        $("div.riepilogo_licenze span.administrator_am").html(costoGiornalieroSingolaLicenza*nGG)
        $("div.riepilogo_licenze span.total_am").html((costoGiornalieroSingolaLicenza*nGG*nLc)+(costoGiornalieroSingolaLicenza*nGG)+costoAttivazioneLicenza)
      }      
      
      if(!isNaN(nGG) && !isNaN(nLc) && Trim(String($("#licenses_order_form input[name='date_from']").val())).length>0){
        //calcola data finale
         $("#licenses_order_form td.date_to").html("calcola data");
      }
    }
  });
  
  $("#licenses_order_form input[name='date_from']").change(function(){
    
  })
    
});
 
/*funzione slider*/
function onBeforeSlide(curr, next, opts){
  var index = opts.nextSlide;
  $("#sliderPager a").removeClass("activeSlide")
  $("#sliderPager a:contains('"+(index+1)+"')").addClass("activeSlide")
}

/*  ----  menu ---  */
var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;

function jsddm_open()
{  jsddm_canceltimer();
   jsddm_close();
   ddmenuitem = $(this).find('div').show();}

function jsddm_close()
{  if(ddmenuitem) ddmenuitem.hide();}

function jsddm_timer()
{  closetimer = window.setTimeout(jsddm_close, timeout);}

function jsddm_canceltimer()
{  if(closetimer)
   {  window.clearTimeout(closetimer);
      closetimer = null;}}
      
      
document.onclick = jsddm_close;
      
/*  ----  menu  FINE ---  */

/*funzioni di utilità*/

function emailCheck(mail){
	var espr = /^[_a-z0-9+-]+(\.[_a-z0-9+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$/;
	if (!espr.test(mail))
    return false;
	else
    return true;
}


function Trim(strq)
{
	while(strq.indexOf(" ")==0)
	{
		if(strq.length > 0)
			strq = strq.replace(" ", "");
		else
			break;
	}
	
	while(strq.lastIndexOf(" ")==strq.length-1)
	{
		if(strq.length > 0)
			strq = strq.substring(0, strq.length-1);
		else
			break;
	}
		
	return strq;
}

/*---------------------------------------------------------
  Inizializzo la gestione degli errori
---------------------------------------------------------*/
$.ajaxSetup({"error":function(XMLHttpRequest,textStatus, errorThrown) {   
      alert(textStatus);
      alert(errorThrown);
      alert(XMLHttpRequest.responseText);
  }
});
