// MASTER JS
// SWFobject for IPS by sveinung@idium.no Feb 2010
(function f(b){var d=window.ips=window.ips||{},c=b||{loading:false},e;if(d.queue===undefined)d.queue=[];if(typeof window.swfobject!=="undefined"&&typeof window.swfobject.embedSWF!=="undefined")c.loading=false;else if(d.queue.length>0){if(c.loading===false){b=document.createElement("script");b.type="text/javascript";b.async=true;b.src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js";(document.getElementsByTagName("head")[0]||document.getElementsByTagName("body")[0]).appendChild(b); c.loading=true}e=setTimeout(function(){f(c)},50)}if(c.loading===false&&d.queue.length>0)for(b=0;b<d.queue.length;b++){var a=d.queue[b];if(!a.loaded){a.loaded="true";swfobject.embedSWF(a.url,a.element,a.width,a.height,a.version,a.expressInstall,a.flashvars,a.params,a.attributes)}}if(c.loading===false&&typeof window.jQuery!=="undefined")e=setTimeout(function(){jQuery(document).one("ajaxStart",function(){e=setTimeout(function(){f(c)},100)})},2E3)})();

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


//Force indexOf on strings
if(!Array.indexOf){
  Array.prototype.indexOf = function(obj){
   for(var i=0; i<this.length; i++){
    if(this[i]==obj){
     return i;
    }
   }
   return -1;
  }
}

var loadFolderContents = function(url) {
  if (url == "")
  url = $(".nav_main li:first a").attr("href");
  jQuery(".nav_main li").removeClass("navigated");
  var contentUrl = url+'?get=content';
  jQuery(".teasers").load(contentUrl,function() {
    $(".nav_main li a[href='"+url+"']").parent().addClass("navigated");
    var headerUrl = $(".ajax_content").data("headerimage");
    $(".headerbottom_center").css("backgroundImage","url('"+headerUrl+"')");
  });
};

  //Find maximum legal license quantity
  function findMaxLicenseValue(licenses){
    var temp = 1;
    var maxLicenseValue = 1;
    $.each($(licenses), function(index, value){
      if(value[2] > temp){
        maxLicenseValue = value[2];
      }
    });
    return maxLicenseValue;
  };

//Load licenses
  function loadLicenses() {
    var temp = [];
    $.each($("select#license_type_hidden option"), function(index, option){
      temp.push(option.value.split("|"));
    });
    return temp;
  };

  //Add license options to dropdown based on license quantity
  function licenseOptions(licenses) {
    $("#os").val(-1);
    var number = $("input#quantity").val();
    var temp = [];
    $.each(licenses, function(index, value){
      if(number >= parseInt(value[1]) && number <= parseInt(value[2])){
        temp.push(value);
      }
    });
    var licenseText = (ips.system.lang == "no") ? "Velg lisenstype" : "Choose license type"; 
    $("#license_type").html($("<option value='-1'>" + licenseText + "</option>"));
    $.each($(temp), function(index, value){
      $("#license_type").append($("<option value='" + value + "'>" + value[0] + "</option>"));
    });
  };

function downloadDemoForm(link) {

    $(".demo_info_div").show();
    $(".demo_info").hide();
    //Generate request url based on where link is located
    var url = ($(link).length > 0) ? $(link).attr("href") + '?template=article_webshop_' + ips.system.lang + '&demo=true&lang=' + ips.system.lang : ips.system.request + '&template=article_webshop_' + ips.system.lang + '&demo=true&lang=' + ips.system.lang;
    $.ajax({ 
      url: url,
      cache: false,
      beforeSend: function() {
        $('html,body').animate({ scrollTop: $("#main").offset().top }, { duration: 'slow', easing: 'swing'});
        $("#loading").show();
      },
      success: function(data){
        $("#loading").hide();
        $(".demo_info").html($(data)); 
        var osArray  = [];
        $(".demo_type_hidden option").each(function(index, value) {
          var split1 = $(value).val().indexOf("+")+1;
          var os =  $(value).val().substring(split1);
          var split2 = os.indexOf("|");
          os = os.substring(0,split2);
          if(osArray.indexOf(os) == -1) {
            osArray.push(os);
          }
        });

        //osArray = $.unique(osArray).reverse();
        
        $(osArray).each(function(index, value) {
          var valueOs = (value == "win") ? "Windows" : "OSX";
          $(".demo_os").append("<option value='" + value + "'>" + valueOs + "</option>");
        });
        changeDemoOs(osArray[0]);
        $(".demo_info").show();
      }
    });
};

function changeDemoOs(selectedOs) {
  $(".demo_type option").remove();

  $(".demo_type_hidden option").each(function(index, value) {
    var split1 = $(value).val().indexOf("+")+1;
    var os =  $(value).val().substring(split1);
    var split2 = os.indexOf("|");
    os = os.substring(0,split2);
    if(selectedOs == os) {
      var tempValues = $(value).val().split("||");
      var newValue = tempValues[0] + "||" + ips.system.host + ips.system.base + tempValues[1];
      $(value).val(newValue);
      $(".demo_type").append($(value).clone());
    }
  });
};

//Load shopping basket
function updateUser(){
  $.ajax({ 
    url: ips.system.base + "?template=user&lang=" + ips.system.lang,
    cache: false,
    success: function(data){
      $(".headerbottom_cart").html($(data)); 
    }  
  });
};


//master.js
jQuery(document).ready(function($) {

  // DISPLAY USER INFO WHEN LOGGED IN
  $.ajax({
    url: ips.system.base + "?template=userLoggedIn&lang=" + ips.system.lang + "&redirectTo=" + ips.system.request + "&topFolderID=" + ips.system.topFolderID,
    cache: false,
    success: function(data) {
      jQuery(".nav_support li:last").before(data); // APPEND RESULT TO HEADER
    }
  });

  $(".nonelink").each(function(index) {
    $(this).attr("href", '#');
  });


   //TEXTSIZE
   var getTextSize = function() {
     var textsize = $.cookie('textsize');
     $("body")
.removeClass("default")
.removeClass("small")
.removeClass("medium")
.removeClass("large").addClass(textsize);
   };
   getTextSize();
   $("#sizeSelector").click(function(event){
       $target = $(event.target);
       if ($target.is("span")) {
         $.cookie('textsize', $target.attr("class"), { expires: 300, path: '/'});
       }
       getTextSize();
       return false;
   });

  var base = ips.system.base; //cache as local variable
  var topFolderID = ips.system.topFolderID; //cache as local variable
  /* orders /ordrehistorikk */
  if ($("table.orders").length == 1) {
    var customerid = $("table.orders").data().userid;
    var scriptsURL = ips.system.base+'scripts/keygen/';
    var url =  scriptsURL+'orders.groovy?secret=71055ce6-4138-4a6e-adb5-ab9cd68b536e&customerid='+customerid;
    $.getJSON(url,function(data) {
      var monthsStrings = ['januar','februar','mars','april','mai','juni','juli','august','september','oktober','november','desember'];
      var orders = data.orders;
      var ordersHTML = "";
      ordersHTML += '<tr>';
      ordersHTML += '<th>';
      ordersHTML += 'Ordboktype';
      ordersHTML += '</th>';
      ordersHTML += '<th>';
      ordersHTML += 'Programn\u00F8kkel';
      ordersHTML += '</th>';
      ordersHTML += '<th>';
      ordersHTML += 'Utl\u00F8psdato';
      ordersHTML += '</th>';
      ordersHTML += '<th>';
      ordersHTML += 'Antall lisenser';
      ordersHTML += '</th>';
      ordersHTML += '<th>';
      ordersHTML += 'Dato kj\u00F8pt';
      ordersHTML += '</th>';
      ordersHTML += '<th>';
      ordersHTML += 'Detaljer';
      ordersHTML += '</th>';
      ordersHTML += '</tr>';
      for (var x=0; x<orders.length;x++) {
        var order = orders[x];
        ordersHTML += '<tr data-id="'+order.id+'">'; // HTML5 data attribute
        ordersHTML += '<td class="dic_type">';
        ordersHTML += order.dictionary_type;
        ordersHTML += '</td>';
        ordersHTML += '<td>';
        ordersHTML += order.program_key;
        ordersHTML += '</td>';
        ordersHTML += '<td>';
        ordersHTML += monthsStrings[-1+order.exp_month]+' '+order.exp_year;
        ordersHTML += '</td>';
        ordersHTML += '<td>';
        ordersHTML += order.licenses;
        ordersHTML += '</td>';
        ordersHTML += '<td>';
        ordersHTML += order.create_date;
        ordersHTML += '</td>';
        ordersHTML += '<td class="details">';
        ordersHTML += '<span class="viewDetailsButton">Se detaljer</span>';
        ordersHTML += '</td>';
        ordersHTML += '</tr>';
      }
      $("table.orders").append(ordersHTML);
      var getDicTypesURL = scriptsURL+'dictionary_types.groovy';
      $.getJSON(getDicTypesURL,function(data) {
        var dicTypeString = "";
        $(".dic_type:not(.hasDicTypeLoaded)").each(function() {
          var dicCode = $(this).text();
          dicTypeString = "";
          for (x=0;x<data.types.length;x++) {
            if(data.types[x].id == dicCode) {
              dicTypeString = data.types[x].type;
            }
          }
          $(this).html(dicTypeString).addClass("hasDicTypeLoaded");
        });
      });
      $("table.orders tr").unbind().bind("click",function() { // click on order
        var $this = $(this);
        if($this.hasClass("detailsLoaded")) {
          if ($this.find("table").is(":visible")) {
            $this.find(".viewDetailsButton").show();
          }
          else {
            $this.find(".viewDetailsButton").hide();
          }
          $this.find("table").fadeToggle();
        }
        else {
          var orderID = $this.data().id;
          var getOrderURL = scriptsURL+'order_details.groovy?secret=71055ce6-4138-4a6e-adb5-ab9cd68b536e&orderid='+orderID;
          $.getJSON(getOrderURL,function(data) {
            var orderHTML = "";
            orderHTML += '<table style="display:none">';
            if(data.order_details.length == 0) {
              orderHTML += '<tr><td>Ingen ordb\u00F8ker funnet</td></tr>';
            }
            else {
              orderHTML += '<tr>';
              orderHTML += '<th>';
              orderHTML += 'Spr\u00E5k: ';
              orderHTML += '</th>';
              orderHTML += '<th>';
              orderHTML += 'N\u00F8kkel:';
              orderHTML += '</th>';
              orderHTML += '<th class="close">';
              orderHTML += '\u02DF';
              orderHTML += '</th>';
              orderHTML += '</tr>';
              for (var x=0;x<data.order_details.length;x++) {
                var detail = data.order_details[x];
                orderHTML += '<tr>';
                orderHTML += '<td class="dic_lang">';
                orderHTML += detail.dict_lang;
                orderHTML += '</td>';
                orderHTML += '<td>';
                orderHTML += detail.dict_key;
                orderHTML += '</td>';
                orderHTML += '</tr>';
              }
            }  
            orderHTML += '</table>';
            $this.addClass("detailsLoaded");
            $this.find(".viewDetailsButton").hide();
            $this.find(".details").append(orderHTML);
            var getlangsURL = scriptsURL+'dictionary_languages.groovy';
            $.getJSON(getlangsURL,function(data) {
              var dicString = "";
              $(".dic_lang:not(.hasLangLoaded)").each(function() {
                var dicCode = $(this).text();
                dicString = "";
                for (x=0;x<data.languages.length;x++) {
                  if(data.languages[x].id == dicCode && data.languages[x].language != 'ALL') {
                    dicString = data.languages[x].language;
                    dicString = dicString.substr(2)+'<span class="doubleArrows"> \u2194 </span>'+dicString.substr(0,2);
                  }
                  else if (data.languages[x].id == dicCode && data.languages[x].language == 'ALL')
                    dicString = 'Alle spr\u00E5k';
                }
                $(this).html(dicString).addClass("hasLangLoaded");
              });
            });
            $this.find("table").fadeIn();
          }); // EOF get single order details JSON
        } // EOF order not loaded, load it and show it  
      }); // EOF function which is run on click on one order
    }); //EOF get orders JSON
  } // eof if orders table is present in the markup.
  /* eof orders */
  if(jQuery("body.frontpage").length == 1) {
    jQuery(".nav_main a").bind("click",function(e) {
      e.preventDefault();
      var url = $(this).attr("href");
      jQuery.history.load(url);
    });
    $.history.init(
      function(hash){
        loadFolderContents(hash); 
      },
      { unescape: ",/" }
    );
  }
  else { // not on a page which handles hash tag, send to frontpage with correct hash
    jQuery(".nav_main a").bind("click",function(e) {
      e.preventDefault();
      var langBase = ips.system.topFolderID == "51" ? ips.system.base+'en/' : ips.system.base;
      window.location = 
        langBase +
        "#" + 
        $(this).attr("href");
    });
  }

  // *** Check input in demo form
  $(".demo_form input").live("keydown change", function() {
    checkInput($(this));
  });

  function checkInput(element) {
    element.css("backgroundColor", "#FFF");
    if(element.val().length != 0){
      element.next("span").hide();
    } else {
      element.next("span").show();
    }
  };


    //Forgotten password
    $("#forgottenPassword input.submit").die().live("click", function(event) {
      event.preventDefault();
      $("span.feedback").remove();
      var email = $("#forgottenPassword input").val();
      $.ajax( {
        type: "POST",
        url: ips.system.base + "scripts/webshopHandler.groovy?action=resetPassword&amp;email=" + email + '&amp;language=' + ips.system.lang,
        dataType: "text",
        cache: false,
        success: function( response ) {
          if(response == "true") {
            var responseText = (ips.system.lang == "no") ? "Ditt nye passord har blitt sendt til din e-postadresse" : "Your new password has been sent to your e-mail address" ;
            $("li.email").append('<span class="feedback error">' + responseText + '</span>');
          } else {
            var responseText = (ips.system.lang == "no") ? "E-post adressen er ikke funnet i v&#229;rt system" : "E-mail address not found in our system" ;
            $("li.email").append('<span class="feedback error">' + responseText + '</span>');
          }
        }
      });
    });

  //Document load check input
  $(".demo_form input").each(function(){
    checkInput($(this));
  });

  //Check username on input with regex
  $("#_AID221_userName").die().live("change", function() {
    var errorMsg = (ips.system.lang == "no") ? "Kun bokstaver, tall og '_', '.' er lov (f\u00F8rste tegn m\u00E5 v\u00E6re bokstav). Norske tegn som \u00E6,\u00F8,\u00E5 er ikke lov." : "Only letters, numbers and '_', '.' is allowed (the first character has to be a letter). Norwegian characters are not allowed.";
    $(this).siblings("span").remove();
    $(this).parent().removeClass("error");
    $("#edit_user_form input.submit").removeAttr("disabled");
    var string = $(this).val();
    var myRegEx = new RegExp(/[a-zA-Z]{1}[a-zA-Z0-9\\.\\-_@]+/);
    if(string != string.match(myRegEx)){
      $(this).parent().addClass("error").append("<span class='error'>" + errorMsg + "</span>");
      $("#edit_user_form input.submit").attr("disabled", "disabled");
    }
  });

  $(".demo_form .demo_submit").live("click", function(event) {
    event.preventDefault();
    if($(".demo_form .required").is(":visible")) {
      $(".demo_form .required:visible").prev().css("backgroundColor", "#F5A9A9");
    } else {
      //$(".demo_info_div").show();

      var firstname = $(".firstname").val();
      var lastname = $(".lastname").val();
      var organisation = $(".organisation").val();
      var contactno = $(".contact_no").val();
      var email = $(".email").val();
      var demovalue = $(".demo_type").val();
      $.ajax({ 
        url: base + 'scripts/webshopHandler.groovy?action=getDemo&language=' + ips.system.lang + '&firstname=' + firstname + '&lastname=' + lastname + '&organisation=' + organisation + '&contactno=' + contactno + '&email=' + email + '&demovalue=' + demovalue,
        cache: false,
        beforeSend: function() {
          $(".demo_info").hide();
          $("#loading").show();
        },
        success: function(data){
          $("#loading").hide();
          var demoText = (ips.system.lang == "no") ? "Informasjon om hvordan du skal laste ned din demoversjon har blitt sendt til " + email : "Information about how to download your demo version has been sent to " + email;
          $(".demo_info").html("<div class='demo_order_submitted'>" + demoText + "</div>"); 
        },
        complete: function() {
          $(".demo_info").show();    
          //Google analytics
          if(organisation.length > 0) {
            _gaq.push(['_trackPageview', '/fullfort_nedlasting_bedrift']);
          } else {
            _gaq.push(['_trackPageview', '/fullfort_nedlasting_ikkebedrift']);
          }       
        }  
      });
    }
  });

  // *** End Check input in checkout


  //Change complete order text when payment method changes
  $(".paymentMethod").die().live("change", function() {
    if($(this).val() == "invoice") {
      if(ips.system.lang == "no") {
        $("input.payment").val("Fullf\u00F8r ordre");
      } else {
        $("input.payment").val("Complete order");
      }
    } else {
      if(ips.system.lang == "no") {
        var text = "G\u00E5 til betaling"
        $("input.payment").val(text);
      } else {
        $("input.payment").val("Proceed to payment");
      }
    }
  });



  //If we come from a selected product, load license options
  if($("#selected_product_id").length > 0){
    var licenses = loadLicenses();
    licenseOptions(licenses);
  }

  //Set background css position
  if($(".article_webshop_no, .article_webshop_en,.webshop .step_two, .language_search, .log_in_webshop").length && !$("body.folder_contents").length) {
    $("body").css("backgroundImage", "url('/clue.no/filestore/dev/GFX/breadcrumbBG.png')");
    $("body").css("backgroundRepeat", "repeat-x");
    $("body").css("backgroundPosition", "0 386px");
  } else if($(".master, body.articles, .frontpage, body.folder_contents").length &&!$("body.checkout, body.users").length) {
    $("body").css("backgroundImage", "url('/clue.no/filestore/dev/GFX/breadcrumbBG.png')");
    $("body").css("backgroundRepeat", "repeat-x");
    $("body").css("backgroundPosition", "0 446px");
  }

  //If only one language in language list, select it
  if($("ol.languages input.checkbox").size() == 1) {
    $("ol.languages input.checkbox").attr("checked", true);
  }

  //Download demo link
  $(".download_demo_link").live("click", function(event) {
    event.preventDefault();
    downloadDemoForm($(this));
  });

$(".demo_os").live("change", function() {
  changeDemoOs($(this).val());
});


  //Close demo info div
  $("#demo_close_btn").live("click", function(event) {
    event.preventDefault();
    $(".demo_info_div").hide();
    $(".demo_info").hide();
  });

  updateUser();
  
  
  //Change license options when license quantity changes
  $("input#quantity").change(function(){
    var licenses = loadLicenses();
    var maxLicenseValue = findMaxLicenseValue(licenses);
    if($("input#quantity").val() < 1){
      $("input#quantity").val(1);
    } else if(parseInt($("input#quantity").val()) > maxLicenseValue){
      $("input#quantity").val(maxLicenseValue);
    }
    var licenses = loadLicenses();
    licenseOptions(licenses);
  });

  // Set options when product changes
  $("#product_list").change(function(){
    if($("#product_list :selected").val() != -1) {
      $("input#quantity").val("1");
      var license_id = "#license_price_id_" + $("#product_list :selected").val();
      $("select#license_type_hidden").html($(license_id).children().clone());
      var licenses = loadLicenses();
      licenseOptions(licenses);

      var os_id = "#os_id_" + $("#product_list :selected").val();
      $("select#os_hidden").html($(os_id).children().clone());

      var languages_id = "#languages_id_" + $("#product_list :selected").val();
      $(".languages").html($(languages_id).children().clone());

      //If only one language in language list, select it
      if($("ol.languages input.checkbox").size() == 1) {
        $("ol.languages input.checkbox").attr("checked", true);
      }
    }
  });

  if($("#product_list").length > 0) {
    $("#product_list :selected").trigger("change");
  }

  //Update dropdown for os when license type changes
  $("#license_type").change(function(){
    if($("#license_type :selected").val() != -1) {

      //clone from hidde options
      $("#os").html($("#os_hidden option").clone());
      $("#os").val(-1);
      var osArr = $("#license_type :selected").val().split("+")[1];

      //remove unwanted options
      $.each($("#os option"), function(index, value) {
        if(index > 0) {
          if(osArr.indexOf($(value).val()) == -1) {
            $(value).remove();
          }
        }
      });
    }
  });

  $(".remove_product_language").unbind().bind("click", function(e) {
    e.preventDefault();
    $.ajax({ 
      url: $(this).attr("href"),
      cache: false,
      success: function(data){
        window.location.replace(ips.system.request);
      }
    });
  });
  
  //Show cart when button is clicked
  $(".headerbottom_cart_btn").bind("click", function(event) {
    var izhidden = $(".headerbottom_cart").is(":hidden");
    if(izhidden){
      $(".headerbottom_cart_btn").animate({      
        right: 262
      }, 200, function() {
        $(".headerbottom_cart").slideToggle();
      });
    } else {
      $(".headerbottom_cart").slideToggle( function(){
        $(".headerbottom_cart_btn").animate({      
          right: 0
        }, 200, function() {
        });  
      });
    }
  });
  
  //Empty shopping basket
  $("#empty_basket").live("click", function(event) {
    event.preventDefault();
    $.ajax({ 
      url: base + 'scripts/webshopHandler.groovy?action=emptyBasket',
      cache: false,
      success: function(data){
        updateUser(); 
      }  
    });
  });
  
  //Select payex payment method
  $(".paymentMethod").bind("change", function(){
    $("#_att_paymentMethod").val($(this).val());
    $("input.payment").removeAttr("disabled");
  });
  
  $("input.payment").live("click", function(event){
    event.preventDefault();
    if($("#_att_paymentMethod").val().length == 0 || $("#accept_agreement:checked").val() == undefined || $(".licenseLanguage:checked").length == 0){
      var errorMsg;
      if ($("#_att_paymentMethod").val().length == 0) {
        errorMsg = (ips.system.lang == "no") ? "Vennligst velg betalingsm\u00E5te." : "Please choose payment method."; 
      } else if ($(".licenseLanguage:checked").length == 0) {
        errorMsg = (ips.system.lang == "no") ? "Vennligst velg lisensspr\u00E5k." : "Please choose a valid license language."; 
      } else {
        errorMsg = (ips.system.lang == "no") ? "Vennligst les og godta betingelsene f\u00F8r du g\u00E5r videre." : "Please read and accept the terms and conditions."; 
      }
      $(".submit_error").html(errorMsg);
      $(".submit_error").show(500).delay(4000).hide(500);
    } else {
      $("#returnUrl").val($("#returnUrl").val() + "&licenseLang=" + $(".licenseLanguage:checked").val());
      $("#redirectUrl").val($("#redirectUrl").val() + "&licenseLang=" + $(".licenseLanguage:checked").val());
      $("#checkout").submit();
    }
  });
  
  //login stuff
  $("#webshop_login").bind("click", function(event) {
    var number = 1;
    var selectedLicense = "";
    
    $.each($("select#license_type_hidden option"), function(index, option){
      var tempLicense = option.value.split("|");
      if(number >= tempLicense[1] && number <= tempLicense[2]){
        selectedLicense = option.value;
      }
      
    });
    event.preventDefault();
  }); 
  
  //If values are filled, enable webshop buttons
  $("#webshop_form").bind("change", function(){
    if($("input#quantity").val() > 0 && $("select#os option:selected").val() != -1 && $("select#license_type option:selected").val() != -1 &&$("input.checkbox:checked").size() > 0 && $("#product_list").val() > 0){
      $("#webshop_basket").removeAttr("disabled");
      $("#webshop_buy_now").removeAttr("disabled");
      $("#webshop_login").removeAttr("disabled");
    } else {
      $("#webshop_basket").attr("disabled", "disabled");
      $("#webshop_buy_now").attr("disabled", "disabled");
      $("#webshop_login").attr("disabled", "disabled");
    }    
  });
  
  $("#webshop_buy_now, #webshop_login").live("click",function(event){
    event.preventDefault();
    $("#webshop_buy_now, #webshop_login").attr("disabled", "disabled");
    var orderObj = prepareForAddToBasket();
    $("#webshop_form select").val(-1);
    $("#quantity").val(1);
    $(".languages .checkbox").attr("checked", false);
    $.ajax({ 
      url: base + 'scripts/webshopHandler.groovy?action=addToBasket&' + $.param(orderObj),
      async: false,
      cache: false,
      complete: function(){
        window.location.replace("?template=checkout");
      }  
    });
  });
  
  $("#order_now").live("click", function(){
    window.location.replace("?template=checkout&nocache=true&templatefolderid=" + topFolderID);
  });

  //On add to basket button
  $("#webshop_basket").bind("click", function(event) {
    event.preventDefault();
    $("#webshop_basket").attr("disabled", "disabled");
    var orderObj = prepareForAddToBasket();
    $("#webshop_form select").val(-1);
    $("#quantity").val(1);
    $(".languages .checkbox").attr("checked", false);
    $.ajax({ 
      url: base + 'scripts/webshopHandler.groovy?action=addToBasket&' + $.param(orderObj),
      async: false,
      cache: false,
      complete: function(){
        updateUser();
        if($(".headerbottom_cart").is(":hidden")){
          $(".headerbottom_cart_btn").click();  
        }
        $('html,body').animate({ scrollTop: $(".headerbottom").offset().top }, { duration: 'slow', easing: 'swing'});
      }  
    });
    $("#webshop_basket").removeAttr("disabled");
  });
  
  function prepareForAddToBasket() {
    var orderObj = {};
    orderObj.os = $("select#os").val();
    orderObj.quantity = $("input#quantity").val();
    orderObj.user_country = ips.system.user_country;
    orderObj.languages = "";
    $.each($("input.checkbox:checked"), function(index, checkbox){
      orderObj.languages += checkbox.value + ",";
    });

    orderObj.product_name = $("#product_list :selected").text();
    orderObj.product_type = $("#product_list :selected").attr("name");
    orderObj.license = $("select#license_type option:selected").val().split("+")[0];
    return orderObj;
  }

   // UTILITY


   // Searchform interaction
   var $searchForm = $("#search_form"), //CACHE
       $query = $searchForm.find(".query"),
       $label = $searchForm.find("label");
   if ($query.val() !== "") {$label.hide();}
   $searchForm.submit(function(){
   if ($query.val() === "") {return false;}
   });
   $query.focus(function(){$label.hide();}).blur(function(){
     if ($(this).val() === "") {$label.show();}
   });
   $searchForm.find("label").click(function(){
    $query.focus();
   }); 
  // EVENT DELEGATION - Not touching dom until click
  $(".externalLink").live("click", function(){
    $(this).attr("target", "_blank");
  });

  // VALIDATE E-MAIL.
  var emailpattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

   
  // NEWSLETTER SIGN UP
  jQuery("#newsletterForm").submit(function(e){
    e.preventDefault();
    var $this = jQuery(this); //cache
    var $email = $this.find("input.email"); //cache
    if(!$this.find(".response").get()[0]) {
      jQuery("<p class='response' />").prependTo($this);
    }
    var $response = $this.find(".response"); // Cache
    if (emailpattern.test($email.val())) {
      $response.text("Sending...");
      $.ajax({
        url: "?template=newsletterResponse;ajax=true;",
        data: $this.serialize(),
        error: function() {
          $response.text("Feil / Error");
        },
        success: function(data) {
          $response.text(ips.strings.godkjent);
          $email.removeClass("error").val("");
        }
      });
    } else {
      $email.addClass("error");
      $response.text(ips.strings.valid);
    }
  });


  // IPS FORM validation by sveinung@idium.no March 2010
  $("body").delegate("form", "submit", function(e){
    var $this = $(this), formid = $this.attr("id")+"", errors = [];
    // Start validation object
    //fix broken objects
    var ips = window.ips = window.ips ||{};
    ips.validate = ips.validate ||{};
    ips.validate[formid] = ips.validate[formid] ||{};
    //end fix broken objects

  // Reset, and FIND/QUERY viable <li> tags. Must be typical <li> with input. If different, change next find().
    $this.find("span.error").remove().end().find("li:not(.submit,.form_labelfield)").removeClass("error")
    // START each - > iterate li`s
    .each(function(i){
    // Needed vars and Cache selectors for convenience and "speed"
      var $li = $(this), $nextLi = $li.next(), $prevLi = $li.prev(), $field = $li.find("input,textarea,select").eq(0), fid = $field.attr("id"), fieldval = $field.val(), errorObj = {"id":fid,"$elem":$li,"message":""};
      // Utilty function for checking regex values
      var checkFunc = function(regexObj, thisval, message, errorObj){
      if (!regexObj.test(thisval)) {
       errorObj.message = message;
      } else {
       errorObj.valid = true; // used to make this rule more important than classes
      }
      return errorObj;  
      };
      // Iterating and validation all regexes in the general object
      $.each(ips.validate.general, function(property){
      if ($li.hasClass(property) && this.regex !== undefined ) {
        errorObj = checkFunc(this.regex, fieldval, this.message, errorObj);
      }
      });
      // Check for validation object
    if ( ips.validate[formid][fid] !== undefined && ips.validate[formid][fid].regex !== undefined ) {
     var fieldvalObj = ips.validate[formid][fid],
           errorMgs = fieldvalObj.message !== undefined ?  fieldvalObj.message : ips.strings.notvalid;
       errorObj = checkFunc(new RegExp(fieldvalObj.regex), fieldval, errorMgs, errorObj);
      } else {
      //fix missing objects
      ips.validate[formid][fid] = {};
      }
      if ( $li.hasClass("form_password") && errorObj.message === ''){
        errorObj = checkFunc(ips.validate.general.password.regex, fieldval, ips.validate.general.password.message, errorObj);
        if (errorObj.message === "" && fieldval !== $li.find(".confirm").val()) {
        errorObj.id = $li.find(".confirm").attr("id");
        errorObj.message = ips.validate.general.password.message;
        }
      }
      // Check username if form has class .loggedout -> Forms get resubmitted if error from server
      if ( $this.hasClass("loggedout") && $li.hasClass("username") && !(errorObj.valid)){
        var searchedUsername = $.data($field[0],"username"), // get "cacge"
            availFromPrevSubmit = $.data($field[0],"avail"); // get "cache"
        $.data($field[0],"username",fieldval); // write "cache"
        // Check if new desired username isnt equal to previous ones or if no username has been checked
        if ((fieldval !== searchedUsername) || (availFromPrevSubmit === null) ) { 
        // Async - check param, then set value on elem and resubmit form
        $.get(ips.system.base + "?module=Users&amp;action=Ajax.isUsernameAvailable&amp;username="+fieldval, function(data){
         $.data($field[0],"avail",data);
         // 'false' is serverresponse in plain text
         if (data == 'false') {
           setTimeout(function(){$this.submit();},100);
         }
        });
        } else {
        // check if this is checked and username is not avail === false
        if (availFromPrevSubmit == "false") {
          errorObj.message = ips.strings.usernamenotavail;  
        }  
        }
      }
      // check if .required and 
      if (fieldval === '' &&  $li.hasClass("required")) {
        // If not already a error - add a error message
      if (errorObj.message === '') {
          errorObj.message = ips.strings.cannotbeempty;
     }
      } else if ($li.hasClass("required") && errorObj.message === '') {
        // if checkbox is required
        if ($field.is("input[type=checkbox]") && $field.attr("checked") === false) {
          errorObj.message = ips.validate[formid][fid].message ||ips.strings.mustbechecked;
        }
      }
      // Todo, ADD : requiredIf - (e.g. email, checkbox )
      // Check for customclasses 'isequaltonext' and 'isequaltoprev' - > is in lowercase bacause of ips:classify
    if ($li.hasClass('isequaltonext')||$nextLi.hasClass('isequaltoprev')) {
        if (fieldval !== $nextLi.find("input").val()) {
        errorObj.message = $li.find("label").text() + ips.strings.mustbeequalto + $nextLi.find("label").text();
        }
      }  else if ($li.hasClass('isequaltoprev')||$prevLi.hasClass('isequaltonext')) {
        if (fieldval !== $prevLi.find("input").val()) {
        errorObj.message = $li.find("label").text() +  ips.strings.mustbeequalto + $prevLi.find("label").text();
        }
      }
      // Field is not required, NO error-msg should be generated
      if (fieldval === '' && !($li.hasClass("required"))) {
      errorObj.message = ''; 
      }
      // Push this errorObj if there is a message defined
      if ( errorObj.message !== undefined && errorObj.message !== '' ) {
      errors.push(errorObj);
      }
    }); //END each li`s

    if ( ips.system.parameters.debug ) {
      console.log(errors);
    }  // Process errors if there is any
    if ( errors.length > 0 ) {
      $( errors ).each(function(i){
        var $errorField = this.$elem.addClass("error").find("input,textarea,select").eq(0);
        if (i === 0) {;$errorField.focus();}
        $("<span class='error'>" + this.message + "</span>").insertAfter( $errorField );  
      });
      return false;
    // default action of the event will not be triggered.
    //e.preventDefault();
    // Keeps the rest of the handlers from being executed.
      //e.stopImmediatePropagation();
    }
  });
  // Possible to click the errors away
  $("span.error").live("click", function(){$(this).fadeOut();}); 
//FORM END
});
