//<script language="javascript">
/**********************
 * Some Configuration *
 **********************/
GA_ACCOUNT = "UA-16474776-1";
CSE_ACCOUNT = "015015642813484535839:magrry5x2hg";

MAX_CONTACT_FORM_COMMENT_LENGTH = 500;

PRODUCT_INTRODUCTION_VIDEO_IDS = {
  de: "3RQopZJDvxk",
  en: "lMLzwWva4no"
}

REQUESTED_ACTION_MAP = {
  "lead-form-download-button": "DOWNLOAD",
  "lead-form-contact-data-submit-button": "CONTACT",
  "lead-form-web-presentation-submit-button": "WEBPRESENTATION"
}

FANCYBOX_DEFAULTS = {
  centerOnScroll: true,
  titlePosition: "inside",
  transitionIn: "elastic",
  transitionOut: "elastic",
  enableKeyboardNav: false,
  padding: 0
}

VIDEO_PARAMS = {
  width: 488,
  height: 397,
  containerId: "video-player-container",
  swfContainerId: "video-player-swf-container",
  playerId: "videoPlayer"
}

var _gaq = _gaq || [];
_gaq.push(["_setAccount", GA_ACCOUNT]);
_gaq.push(["_setDomainName", "none"]);
_gaq.push(["_setAllowLinker", true]);

(function() {
  var ga = document.createElement("script");
  ga.type = "text/javascript";
  ga.async = true;
  ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";

  var firstScriptTag = document.getElementsByTagName("script")[0];
  firstScriptTag.parentNode.insertBefore(ga, firstScriptTag);
})();

/*_gaq.push(function() {
  window.pageTracker = _gat._getTrackerByName();
});*/

window.activeForm = "";
window.contactFormSubmitted = false;
window.downloadDone = false;
window.playbackQualitySetTo720p = false;
window.playerInitDone = false;



$(document).ready(function() {
  //hide breadcrumb on super pages and for the docs
  if($(".superpage-content").length > 0 || $("body").is(".path-2-6")) {
    $("#breadcrumb-container").remove();
  }
  else if ($("body").is(".path-3-0") || $("body").is(".path-3-1")) {

  } else {
    $(".content-col").css({paddingTop: "30px"});
    $("#breadcrumb-container").css({
      position: "absolute",
      top: "0px",
      left: "266px"
    });
  }


  //resize featured blocks depending on count
  if($("body").is(".path-0-0")) {
    var leftCol = $(".left-col");
    var featuredBlocks = $(".featured", leftCol);
    var featuredBlocksCount = featuredBlocks.length;

    featuredBlocks.css({
      width: leftCol.innerWidth() / featuredBlocksCount - featuredBlocksCount * 7//218
    });
  }


  //hide the navigation on the registration confirmation page
  $("#path-0-6 .nav-container-left, #path-0-7 .nav-container-left").hide();

  //Set defaults for fancybox.
  $.extend($.fn.fancybox.defaults, FANCYBOX_DEFAULTS);

  //stuff for the navigation
  $(".nav-top-level-item").hover(function() {
    $(".nav-popup", this).show();
  }, function(event) {
    $(".nav-popup", this).hide();
  });



  window.onYouTubePlayerReady = function(playerId) {
    var ytp = document.getElementById(VIDEO_PARAMS.playerId);
    ytp.addEventListener("onStateChange", "onPlayerStateChange");
    ytp.addEventListener("onPlaybackQualityChange", "onPlaybackQualityChange");
  }

  //
  //Video stuff
  //
  $(".video-link").fancybox({
    //href: "http://www.youtube.com/v/" + PRODUCT_INTRODUCTION_VIDEO_IDS[LANG] + "?fs=1&enablejsapi=1&version=3&playerapiid=introPlayer&hd=1&rel=0&hd=1",
    //href: "http://www.youtube.com/apiplayer?enablejsapi=1&version=3&playerapiid=introPlayer",
    href: "#" + VIDEO_PARAMS.containerId,
    autoDimensions: false,
    width: VIDEO_PARAMS.width,
    height: VIDEO_PARAMS.height,
    hideOnContentClick: false,
    onCleanup: function() {
      //fix for IE that keeps playing the video in the background
      //$("#" + VIDEO_PARAMS.swfContainerId + " object").get(0).pauseVideo();
      //$("#" + VIDEO_PARAMS.containerId).empty();
    },
    onComplete: function() {
      if(!$("#" + VIDEO_PARAMS.containerId).data("isPlayerEmbedded")) {
        swfobject.embedSWF(
          "http://www.youtube.com/v/" + PRODUCT_INTRODUCTION_VIDEO_IDS[LANG] + "?fs=1&enablejsapi=1&version=3&playerapiid=introPlayer&hd=1&rel=0&hd=1",
          VIDEO_PARAMS.swfContainerId,
          VIDEO_PARAMS.width,
          VIDEO_PARAMS.height,
          "8",
          null,
          null,
          {allowScriptAccess: "always", allowFullScreen: "true", wmode: "transparent"},
          {id: VIDEO_PARAMS.playerId}
        );
        $("#" + VIDEO_PARAMS.containerId).data("isPlayerEmbedded", true);
      }
    }
  });

  $("#product-introduction-ad").hover(function() {
    $("#pi-play-button").attr("src", "Resources/Images/play-button-hover.png");
  }, function() {
    $("#pi-play-button").attr("src", "Resources/Images/play-button.png");
  });

  $("div.press-picture a").fancybox();

  //Preventing the default behaviour of a link is important here. All a tags with these classes
  //have @href set and therefor would open a fancybox with nonsense in it.
  //However, the @href must be set in order for analytics to properly pick these links up (in-page analytics).
  //@href is overridden by fancybox anyway (see a few lines below).
  $(".download-link, .contact-link, .order-link, .web-presentation-link, .video-link")
    .click(function(event) {
      event.preventDefault();
    })
    .autoTracker();

  $(".download-link, .contact-link, .order-link, .web-presentation-link").click(function() {
    $.fancybox.showActivity();
    $.get(LEAD_FORM_URL)
      .success(function(responseText, statusText, xhr) {
        $("#localized-lead-form").html(responseText);
        resetFormElements();

        var map = {
          "Trial": prepareDownloadForm,
          "Contact Me": prepareContactMeForm,
          "Web Presentation": prepareWebPresentationForm,
          "Order": prepareOrderForm
        };
        map[window.activeForm]();

        $.fancybox.hideActivity();
        $.fancybox({
          href: "#contact-form-container",
          onClosed: function(event) {
            if("Trial" != window.activeForm && false == window.contactFormSubmitted) {
              _gaq.push(["_trackEvent", "Contact Form", window.activeForm, "aborted"]);
            }

            if("Trial" == window.activeForm && false == window.downloadDone) {
              _gaq.push(["_trackEvent", "Contact Form", "Trial", "Download aborted"]);
            } else if("Trial" == window.activeForm && true == window.downloadDone && false == window.contactFormSubmitted) {
              _gaq.push(["_trackEvent", "Contact Form", "Trial", "Registration aborted"]);
            } else if("Trial" == window.activeForm && true == window.downloadDone && true == window.contactFormSubmitted) {
              _gaq.push(["_trackEvent", "Contact Form", "Trial", "Registration submitted"]);
            }

            window.activeForm = "";
          }
        });
      })
      .success(registerContactFormEventHandlers);
  });

  //
  //stuff related to the download/contact form
  //
  $(".web-presentation-link").click(prepareWebPresentationForm);
  $(".download-link, .button-top-1").click(prepareDownloadForm);
  $(".contact-link, .button-top-2").click(prepareContactMeForm);
  $(".order-link").click(prepareOrderForm);

  //
  //support form stuff
  //
  $(".support-link").fancybox({
    onComplete: function() {
      doFormValidation("support-form");
    }
  });

  $("#support-form-submit-button").click(function(event) {
    var fieldsAreValid = true;

    $("#support-form").find("input.required-field, input.optional-field").each(function() {
      fieldsAreValid = validateField($(this));
      return fieldsAreValid;//if fieldsAreValid is false, each() will not iterate through the rest
                            //of the fields, similar to a break in a normal loop
    });

    if(fieldsAreValid) {
      $("#support-form-progress-indicator").show();
      $("#support-form-submit-button").attr("disabled", "disabled");
      $.post(
        SUPPORT_POST_URL,
        $("#support-form").serializeArray(),
        function(data) {
          $("#support-form-data").hide();
          $("#support-form-thank-you").fadeIn("fast");

          $("#support-form-issue-number").text(data.documentElement.firstChild.nodeValue);
        },
        "xml"
      );
    } else {
      if("de" == LANG) {
        alert("Bitte füllen Sie alle rot markierten Felder aus.");
      } else {
        alert("Please enter all fields marked red.");
      }
    }
  });

  $("#close-support-form-link").click(function(event) {
    $.fancybox.close();
  });

  $("#search-form").submit(function(event) {
    event.preventDefault();
    document.location.href = $("#search-form").attr("action") + "?q=" + encodeURIComponent($("#search-string").val());
  });

  $(".frontpage-thumbnail-link, a.content-image").fancybox({
    hideOnContentClick: true,
    cyclic: true
  });

  $(".pdf-link").fancybox({
    type: "iframe",
    width: 1024,
    height: 768,
    padding: 0
  });

  $(".example-file-links a").autoTracker();

  $("#back-button").click(function(event) {
    document.location.href = document.referrer;
  });

  //make entire featured blocks clickable
  $(".featured:has(a)").each(function() {
    var item = $(this);
    item
      .css({cursor: "pointer"})
      .click(function(event) {
        document.location.href = item.find("a").attr("href");
      });
  });



  //
  //MSV stuff
  //
  var msvContainersToHide = [
    "#top-buttons-container",
    "div.tag-cloud",
    "#left-nav-docs-link",
    "#top-nav-item-3",
    "#top-nav-item-15",
    "#top-nav-item-2",
    "#top-nav-item-50",
    "#lang-selection"
  ];

  if($("body").is(".path-7-4")) {
    $(msvContainersToHide.join(",")).remove();

    //change contact links to point to msv contact page
    $("a:contains('Kontakt')").attr("href", "/de/7-4-1/projekte/kommunale-kunden/kontakt");
    $("div.nav-container-left")
      .css({width: "214px"})
      .appendTo("div.left-col");
  }


  //hide sub items of 7-4
  $("li#top-nav-item-7-4 ul").remove();


  //
  //.net version tracking
  //

  //Get .net version and set it to a custom variable in GA.
  //Note that this piece of code only uses the last match that
  //is found in the userAgent string (and therefor the highest
  //version the user has installed).
  var regExp = /\.NET(?:\sCLR\s)?([0-9.]+[a-z]?)/gi;
  var match, matches = [];
  while((match = regExp.exec(navigator.userAgent)) != null)
    matches[matches.length] = match[1];
  _gaq.push(["_setCustomVar", 5, ".NET-Version", matches[matches.length - 1] || "(indeterminable)", 1]);

  _gaq.push(["_trackPageview"]);
});

/***********************************************
 * tiny jquery plugin to track regular a-links *
 ***********************************************/
(function($){
  $.fn.autoTracker = function() {

    this.bind("click.autoTracker", function(event) {
      window.setTimeout(function() {

        var url = event.currentTarget.href;
        if($.support.hrefNormalized)
          url = url.match(/http:\/\/(?:.+?)(\/.+)$/i)[1];

        _gaq.push(["_trackPageview", url]);

      }, 200);
    });

    return this;
  };
})(jQuery);

/************************
 * .net version checker *
 ************************/
function HasRuntimeVersion(v, c) {
  var ConvertVersionStringToArray = function(v) {
    var a = v.match(/([0-9]+)\.([0-9]+)\.([0-9]+)/i);

    if(a == null)
      a = v.match(/([0-9]+)\.([0-9]+)/i);

    return a.slice(1);
  }

  var CompareVersions = function(v1, v2) {
    if(v1.length > v2.length) {
      v2[v2.length] = 0;
    } else if(v1.length < v2.length) {
      v1[v1.length] = 0;
    }

    for (var i = 0; i < v1.length; ++i) {
      var n1 = new Number(v1[i]);
      var n2 = new Number(v2[i]);
      if (n1 < n2)
        return -1;
      if (n1 > n2)
        return 1;
    }

    return 0;
  }

  var va = ConvertVersionStringToArray(v);
  var a = navigator.userAgent.match(/\.NET CLR [0-9.]+/g);

  if(va[0] == 4)
    a = navigator.userAgent.match(/\.NET[0-9.]+E/g);

  if(c) {
    a = navigator.userAgent.match(/\.NET Client [0-9.]+/g);
    if (va[0] == 4)
      a = navigator.userAgent.match(/\.NET[0-9.]+C/g);
  }

  if (a != null)
    for (var i = 0; i < a.length; ++i)
      if (CompareVersions(va, ConvertVersionStringToArray(a[i])) <= 0)
        return true;

  return false;
}


/******************************
 * Code for the various forms *
 ******************************/
function doFormValidation(formId) {
  $("#" + formId).find("input.required-field, input.optional-field").each(function() {
    validateField($(this));
  });
}

function validateField(field) {
  var fieldIsValid = false;

  if(field.hasClass("numbers-only")) {
    fieldIsValid = /^\d+$/.test(field.val());
  } else if (field.hasClass("email-only")) {
    fieldIsValid = /^([\w-+_\.]+)@((?:[\w\.-]+\.)+)([a-zA-Z]{2,6})$/i.test(field.val());
  } else {
    fieldIsValid = field.val() != "";
  }

  //the field is allowed to be empty when its marked as optional.
  //however, when the field is not empty it must be filled correctly
  if(!fieldIsValid && field.hasClass("optional-field") && field.val() == "") {
    fieldIsValid = true;
  }

  if(true == fieldIsValid) {
    field.removeClass("invalid");
  } else {
    field.addClass("invalid");
  }

  return fieldIsValid;
}

function prepareDownloadForm() {
  resetFormElements();

  if(HasRuntimeVersion("4.0.0", false))
    $("#install-location").show();
  else
    $("#install-location").hide();

  $("#lead-form-download-header").show();
  $("#lead-form-download-button").show();

  $("#lead-form-explanation-download").show();

  $("#download-step-overview").show();
  $(".lead-form-download-step").removeClass("active");
  $("#download-step1").addClass("active");
  $("#download-links-container").show();
  $("#lead-form-table").show();

  window.activeForm = "Trial";
}

function prepareContactMeForm() {
  resetFormElements();

  $("#contact-form-data").show();
  $("#lead-form-contact-me-header").show();
  $("#lead-form-explanation-contact-me").show();
  $("#lead-form-contact-data-submit-button").show();

  window.activeForm = "Contact Me";
}

function prepareWebPresentationForm() {
  resetFormElements();

  $("#contact-form-data").show();
  $("#lead-form-web-presentation-header").show();
  $("#lead-form-explanation-web-presentation").show();
  $("#lead-form-web-presentation-submit-button").show();

  $("#desired-date-row").show();

  window.activeForm = "Web Presentation";
}

function prepareOrderForm() {
  resetFormElements();

  if(HasRuntimeVersion("4.0.0", false))
    $("#install-location").show();
  else
    $("#install-location").hide();

  $("#lead-form-download-header").show();
  $("#lead-form-download-button").show();

  $("#lead-form-explanation-download").show();

  $("#download-step-overview").show();
  $(".lead-form-download-step").removeClass("active");
  $("#download-step1").addClass("active");
  $("#download-links-container").show();
  $("#lead-form-table").show();

  $("#download-remark").show();

  window.activeForm = "Order";
}

function registerContactFormEventHandlers() {

  $("#download-location").attr("href", ED_DOWNLOAD_URL);
  $("#install-location").attr("href", ED_INSTALL_URL + "?Cookies=" + escape(document.cookie) + "&amp;Referer=" + escape(document.referrer));

  $("input.required-field, input.optional-field").keyup(function(event) {
    validateField($(this));
  });
  $("select.required-field, select.optional-field").change(function(event) {
    validateField($(this));
  });

  $("#lead-form-description-field").keydown(function(event) {
    var el = $(this);
    var comment = el.val();
    if(comment.length >= MAX_CONTACT_FORM_COMMENT_LENGTH)
    {
      $("#comment-too-long-hint").fadeIn("slow");
      el.val(comment.substring(0, MAX_CONTACT_FORM_COMMENT_LENGTH));//in case a long text was pasted
      event.preventDefault();
    }
  });

  $(".do-download-button")
    .click(function(event) {
      window.downloadDone = true;

      $(".lead-form-download-step").removeClass("active");
      $("#download-step2").addClass("active");

      $("#download-links-container").hide();
      $("#contact-form-data").fadeIn("fast");
    });

  //
  //form submission/validation stuff
  //
  $(".lead-form-submit-button").click(function(event) {
    event.preventDefault();

    var allowSend = true;

    $("#contact-form").find("input.required-field, input.optional-field").each(function() {
      if(!validateField($(this)))
        allowSend = false;
    });

    if (allowSend) {
      _gaq.push(["_trackEvent", "Contact Form", window.activeForm, "submitted"]);
      _gaq.push(["_trackPageview", "/Targets/LeadSubmitted"]);

      window.contactFormSubmitted = true;

      var formValues = $("#contact-form").serializeArray();
      formValues[formValues.length] = {
        name: "RequestedAction",
        value: REQUESTED_ACTION_MAP[event.target.id]
      };

      var queryString = "";
      for (var i in formValues) {
        queryString += formValues[i]["name"] + "=" + escape(formValues[i]["value"]).replace(/\+/g, "%2B");
        //append an ampersand to the end if the current value is not the last one
        if (i < formValues.length - 1)
          queryString += "&";
      }

      $.post(
        CONTACT_POST_URL, queryString, function() {
        $("#lead-form-table").hide();

        switch (REQUESTED_ACTION_MAP[event.target.id]) {
          case "DOWNLOAD":
            $("#thank-you-download-container").fadeIn("fast");
            break;

          case "CONTACT":
            $("#thank-you-contact-me-container").fadeIn("fast");
            break;

          case "WEBPRESENTATION":
            $("#thank-you-web-presentation-container").fadeIn("fast");
            break;
        }
      });
    } else {
      if ("de" == LANG) {
        alert("Bitte füllen Sie alle rot markierten Felder aus.");
      } else {
        alert("Please enter all fields marked red.");
      }
    }
  });

  $("#install-location").click(function() {
    _gaq.push(["_trackPageview", "/Targets/DownloadDone"]);
    _gaq.push(["_trackEvent", "Enterprise Designer", "Trial", "Installed"]);
  });

  $("#download-location").click(function(event) {
    event.preventDefault();

    _gaq.push(["_trackPageview", "/Targets/DownloadDone"]);
    _gaq.push(["_trackEvent", "Enterprise Designer", "Trial", "Downloaded"]);

    //This is actually only a problem in chrome but the browser
    //property does not specifically support chrome
    //so I'll just check for webkit
    if ($.browser.webkit)
      window.setTimeout("document.location.href = '" + event.currentTarget.href + "';", 300);
    else
      document.location.href = event.currentTarget.href;
  });

  _gaq.push(["_trackEvent", "Contact Form", window.activeForm, "opened"]);
}

//hide all elements that are *not* common to all forms
function resetFormElements() {
  $("#thank-you-download-container").hide();
  $("#thank-you-contact-me-container").hide();
  $("#thank-you-web-presentation-container").hide()

  $("#contact-form-data").hide()

  $("#lead-form-contact-me-header").hide();
  $("#lead-form-download-header").hide();
  $("#lead-form-web-presentation-header").hide();

  $("#lead-form-explanation-download").hide();
  $("#lead-form-explanation-contact-me").hide();
  $("#lead-form-explanation-web-presentation").hide();

  $("#lead-form-contact-data-submit-button").hide();
  $("#lead-form-download-button").hide();
  $("#lead-form-web-presentation-submit-button").hide();

  $("#desired-date-row").hide();

  $("#download-remark").hide();

  $("#download-step-overview").hide();
  $("#download-links-container").hide();

  $("#lead-form-table").show();
}

/***************
 * video stuff *
 ***************/
var videoHelpers = {
  setPlaybackQualityTo720p: function() {
    if(false == window.playbackQualitySetTo720p) {
      window.playbackQualitySetTo720p = true;
      document.getElementById(VIDEO_PARAMS.playerId).setPlaybackQuality("hd720");
    }
  },
  onPlayerStateChange: function(newState) {
    if(3 == newState) {//play
      _gaq.push(["_trackPageview", "/Targets/ProductIntroductionViewed"]);
      _gaq.push(["_trackEvent", "Videos", "Play", "Product Introduction"]);
      setPlaybackQualityTo720p();
    } else if(2 == newState) {//pause
      _gaq.push(["_trackEvent", "Videos", "Pause", "Product Introduction"]);
    } else if(0 == newState) {//stop (video ended)
      _gaq.push(["_trackEvent", "Videos", "Finished", "Product Introduction"]);
    }
  },
  onPlaybackQualityChange: function() {
    setPlaybackQualityTo720p();
  }
}
//IE
window.onPlayerStateChange = videoHelpers.onPlayerStateChange;
window.onPlaybackQualityChange = videoHelpers.onPlaybackQualityChange;
