﻿/// <summary>Print the page if the browser knows how to, otherwise return and allow default link action</summary>
function printPage() {
  if (window.print) {
    window.print();
    return false;
  } else {
    return true;
  }
}


$(document).ready(function() {
  //handling pdf and dwg pictures
  $('.productfiles ul li a').each(function(index, element){
    
    var filename = $(this).text();
    var filetype = filename.substring(filename.length - 3, filename.length);
    if(filetype == "DWG" || filetype == "dwg"){
      $(this).css('background', 'url(Files/billeder/DWG_logo_Web.png) no-repeat scroll left top transparent');
    }
  });

  
  // The menu

  $("li#language_selector").mouseenter(function(){
    $("div#language_layer").slideDown(500);
  });

  $("div#language_layer").mouseleave(function(){
    $("div#language_layer").slideUp(500);
  });

  $('#mainnav').superfish({
    animation: {height:'show'},   // slide-down effect without fade-in
    autoArrows: false,
    speed: 'slow'   
  });    
  
  if ($("#mainnav>li").length > 2) {
  $("#mainnav>li:last").find("ul").addClass("endmenu");
  $("#mainnav>li:last").find("ul li ul").addClass("endmenusub");
  }
  // Tabs on products
  $('#tabs>div:not(:first)').hide(); // Hide all divs, except the first
  $('#tabs>ul li:first').addClass('active'); // Set the class of the first link to active
  $('#tabs>ul li a').click(function() { 
    $('#tabs>ul li').removeClass('active'); // Remove active class from all links
    $(this).parent().addClass('active'); //Set clicked link class to active
    var currentTab = $(this).attr('tab'); // Set variable currentTab to value of href attribute of clicked link
    $('#tabs>div').hide(); // Hide all divs      
    $("." + currentTab).show(); // Show div with class equal to variable currentTab
    return false;
  });
  
  // Imagegallery, bind any click on thumbnails, so they show image as large
  $("#imagegallery li a").click(function() {    
    return setSelectedImage(this);
  });

  // Validate "Book a meeting" form
  var submitIdentifier = "#bookmeeting input[type=submit]";
  $(submitIdentifier).click(function () {
    return ValidateInput("#personalinformations", 'input[type=text]');
  });
  
  // Validate newsletter and pressrelease-forms.
  var subscribeKey = 1;
  var unSubscribeKey = 2;
  ValidateOnSubmit(document.subscribe, subscribeKey);
  ValidateOnSubmit(document.unsubscribe, unSubscribeKey);
  });

// Regex which validate e-mail addresses
var emailRegex = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

function ValidateOnSubmit(form, subscriptionkey) {
  // If form is found, we will hook up our validation.
  if (form) {    
    // Newsletter-module will POST to a page which lacks templates and therefore show a pretty empty page (just saying "Thank you for your subscription").
    // If we redirect to the original page, we maintain our templates. We have to tell if we a subscriping (1) or unsubscriping (2).
    form.action = location.href + "?ParagraphID=839&PID=839&mode=" + subscriptionkey;
    
    form.onsubmit = function() {
      
      // In newsletters from DW, the e-mail element is always called "NewsletterRecipientEmail"
      var emailElm = form.NewsletterRecipientEmail;  
      
       if (form.NewsletterRecipientName && form.NewsletterRecipientName.value == '') {
         $(form.NewsletterRecipientName).addClass("warning").bind("focus", function(){$(this).removeClass("warning");});
         return false;
       } else if (emailElm.value == '') {
         $(emailElm).addClass("warning").bind("focus", function(){$(this).removeClass("warning");});
         return false;
       } else if (emailRegex.test(emailElm.value) == false) {
        $(emailElm).addClass("warning").bind("focus", function(){$(this).removeClass("warning");});
        return false;
       }       
         
       // Everything's gooood, lets proceed
       return true;
    }
   }
}

// Image-gallery (Nilan_Product.xslt)
var _lastSrc;
function setSelectedImage(anchorElm) {      
  var listItem = $(anchorElm).parent();
  // We have saved previous thumb-image so we can reset selected-border on it
  if (_lastSrc)
    $(_lastSrc).removeClass("selected");
  _lastSrc = listItem;

  // Show the clicked image in a large format
  // Fade out main img, set selected border on miniature img, change main img to new img, fade in again (show new main img)
  // - edited 20/09, png-fading in IE didn't play nice so fading is now disabled (by using fadeIn instead of fadeOut/fadeTo).
  $("#mainimage").fadeIn("slow", function () { 
        $(listItem).addClass("selected"); 
        $(this).css('background', 'url("' + $(anchorElm).attr("href") + '") no-repeat center center transparent'); })
      .fadeIn("slow");
  
  return false;
}
// $(this).attr("src", $(anchorElm).attr("href")) })

// Make sure user has filled necessary fields
// Currently targets "Book a meeting" form
function ValidateInput(id, type) {
  var identifier = id + " " + type;
  var blnContinue = true;
  $(identifier).each(function() {
    // If field is empty. Unfortunately trimming is not native in JS :??(
    if (this.value == "") {
      // The label element holds information about our control
      var labelelement = $(this).parent().parent().find("label");
      var inputIsRequired = "True"; // Input checking is done per default. If a variable "isrequired" has been set, use this (whether it's true/false)
      if (labelelement) {
        inputIsRequired = labelelement.attr("required");
      }
      // If field is flagged as "required" in database, check it for empty values
      if (inputIsRequired == "True") {
        alert("Udfyld venligst feltet '" + labelelement.attr("for") + "'");
        this.focus();
        // Halt iteration and let user correct this field before user once again can try to submit and have the form re-validated.
        return blnContinue = false;
      }
      else {
        // If field is not flagged as required, continue to next field.
        return false;
      }
    }
  });
  
  if (blnContinue) {
    
    if (emailRegex.test($("#ScheduleMeeting_Email").val()) == false) {
      alert('Ugyldig e-mail adresse. Kontroller venligst din indtastning');
      $("#ScheduleMeeting_Email").focus();
      blnContinue = false;
    }
  }
  
  return blnContinue;
}

// Fix for not having access to a given product's GroupID...
function addGroupID(link) {
  var groupID = $('#grouplist').attr('data-group');
  link.href += ('&GroupID=' + groupID);
}

// Google maps (used for dealership location)
    
var geocoder;
var map;
    
function initialize(mapcontainer) {
  
  var latlng = new google.maps.LatLng(9.501785, 56.26392); // Default to Denmark
  var myOptions = {
    zoom: 12,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById(mapcontainer), myOptions);    
}

function codeAddress(address) {
  geocoder = new google.maps.Geocoder();  
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map, 
          position: results[0].geometry.location
      });
    } else {
      //alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

function SetDealerAddress(strAddress, mapcontainer)
{
  initialize(mapcontainer);
  codeAddress(strAddress);
}
    
    
 
