﻿$(document).ready(function() {
  try {
    loadSettings();
  } catch (e) { }

  $(".lightbox a").lightbox({ fixedNavigation: true });
  $("a.lightbox").lightbox({ fixedNavigation: true });
  $("#ad_left img").mouseover(function() {
    var newTumbSrc = $(this).children("img").attr("src");
    var newFullSrc = $(this).attr("href");

    $(".enlarged").children("img").attr("src", newTumbSrc);
    $(".enlarged").attr("href", newFullSrc)

  });

  //set div height
  if ($.browser.opera) {
    $("#content").height($(window).height() - 245);
  }

  setTableStyle();

  // Kleur menu item oranje als het huidige categorie is.
  menulink = window.location.href;
  if (window.location.href.indexOf("product") > -1) {
    // Gaat om een product, krijg 2de link van kruimel.
    menulink = $(".crumbHead a")[1].href;
  }
  
  $("#topmenu li").click(function() {
    window.location = $(this).find("a").attr("href");
    return false;
  });

  $("#topmenu a").each(function() {
    if (menulink.indexOf(this.href) > -1) {
      $(this).css("color", "#606060");
      $(this).parent().css("background-image", "url(/images/menu_item_bg.gif)");
    }
  });

  //set datepicker
  $('input[id*=datepickerstart]').DatePicker({
    format: 'd-m-Y',
    date: [new Date(), '2030-01-01'],
    current: new Date(),
    starts: 1,
    onChange: function(formated, dates) {
      $("input[id*=datepickerstart]").val(formated);
      $("input[id*=datepickerstart]").DatePickerHide();
    }
  });
  $('input[id*=datepickerend]').DatePicker({
    format: 'd-m-Y',
    date: [new Date(), '2030-01-01'],
    current: new Date(),
    starts: 1,
    onChange: function(formated, dates) {
      $("input[id*=datepickerend]").val(formated);
      $("input[id*=datepickerend]").DatePickerHide();
    }
  });

  //fill images in edit
  var imgcount = 0;
  $("input[id*='extraImage']").each(function() {
    $(this).val($("div[id*='extraImageResult" + imgcount + "']").attr("value"));
    imgcount += 1;
  });

});

function setTableStyle() {
  $(".table tr").each(function(intIndex) {
  if (intIndex % 2 == 1)
    $(this).css("background-color", "#ADBC95");
  else
    $(this).css("background-color", "#C4D1B1");
  
  });

}

function loadSettings() {
  var cval = $.cookie('settings');
  /*if (cval != "") {
    //read data and execute
    if (!$.evalJSON(cval).menu) {
      toggleHeader(false);
    }
  }*/
}

function toggleHeader(setdata, menuopen) {
  var time;
  if (setdata){
    time = 800;
  } else {
    time = 0;
  }
  $("#head").toggle();
  $("#top_menu").toggle();

  var cookiedata;
  if ($("#head").css("display") == "none") {
    $("#toggleHead").css("margin-top", "0px");
    $("#toggleHead").html("Toon menu");

    //json data
    cookiedata = { menu: false };

  } else {
    $("#toggleHead").css("margin-top", "220px");
    $("#toggleHead").html("Verberg menu");

    //json data
    cookiedata = { menu: true };
  }
  if (setdata) {
    $.cookie('settings', $.toJSON(cookiedata), { expires: 365, path: '/' });
  }

}

function toggleButton(id) {
  $("input[id*='" + id + "']").disable();
}

function delPicture(hidden,input,result,imgid) {
  $.ajax({
    url: '/views/fileupload/upload.aspx',
    data: "pass=uploadform56&action=delete&filename=" + $("input[id*='" + hidden + "']").val(),
    success: function(data) {
      $('#' + result).html("");
      $('#' + hidden).val("");
      $('#' + input).show();
      if (imgid > -1) {
        new AjaxUpload('upload_button' + imgid, {
          action: '/views/fileupload/upload.aspx?pass=uploadform56',
          onSubmit: function(file, ext) {
            // allow only 1 upload
            //this.disable();
            if (!(ext && /^(jpg|png|jpeg|gif)$/i.test(ext))) {
              // extension is not allowed
              alert('Het gekozen bestand is niet geldig...kies een ander bestand.');
              return false;
            } else {
            $("#extraImageResult" + imgid).html("<img src='/Images/loading.gif'/ >Bezig met uploaden...");
            $("#upload_button" + imgid).hide();
            }
          },
          onComplete: function(file, response) {
            $("#extraImageResult" + imgid).html("<img width='125' src='/pictures/upload/thumb/" + response + "'/><br/><img class='delete' onclick=\"delPicture('extraImage" + imgid + "','upload_button" + imgid + "','extraImageResult" + imgid + "');\" src='/Images/delete.gif'/>&nbsp;" + response);
            $("input[id*='extraImage" + imgid + "']").val(response);
          }
        });
      }
    }
  });
}

function addExtraPic() {
  var count = parseInt($("input[id*='extraImagesCount']").val());
  if (count < 10) {
    //add extra image field
    $("div[id*='extraImages']").append("<input id='upload_button" + count + "' class='' type='file'/><input id='extraImage" + count + "' name='extraImage" + count + "' type='hidden' value=''/><div id='extraImageResult" + count + "'/>");

    new AjaxUpload('upload_button' + count, {
      action: '/views/fileupload/upload.aspx?pass=uploadform56',
      onSubmit: function(file, ext) {
        // allow only 1 upload
        //this.disable();
        if (!(ext && /^(jpg|png|jpeg|gif)$/i.test(ext))) {
          // extension is not allowed
          alert('Het gekozen bestand is niet geldig...kies een ander bestand.');
          return false;
        } else {
          $("#extraImageResult" + count).html("<img src='/Images/loading.gif'/ >Bezig met uploaden...");
          $("#upload_button" + count).hide();
        }
      },
      onComplete: function(file, response) {
        $("#extraImageResult" + count).html("<img width='125' src='/pictures/upload/thumb/" + response + "'/><br/><img class='delete' onclick=\"delPicture('extraImage" + count + "','upload_button" + count + "','extraImageResult" + count + "');\" src='/Images/delete.gif'/>&nbsp;" + response);
        $("input[id*='extraImage" + count + "']").val(response);
      }
    });
    $("#addExtraFoto").html("Voeg extra afbeelding toe");
  } else {
    $("#addExtraFoto").html("U kunt niet meer afbeeldingen toevoegen!");
  }
  $("input[id*='extraImagesCount']").val(count + 1);
  //$("input[id*='upload_button" + count + "']").trigger('click');
}

function checkInput() {
  var valid = true;
  var message = "";
//  if ($("input[id*='txtTitle']").val() == "") {
//    valid = false;
//    message += "- De titel is een verplicht veld! \n";
//  }
//  if ($("input[id*='txtOmschrijving']").val() == "") {
//    valid = false;
//    message += "- De omschrijving is een verplicht veld!\n";
//  }
  if ($("input[id*='headImage']").val() == "") {
    valid = false;
    message += "- De hoofd-afbeelding is een verplicht veld!\n";
  }
  if (message != "" && !valid) {
    message = "De volgende velden bent u vergeten in te vullen: \n\n" + message;
    alert(message);
  }
  return valid;
}

function toggleDiv(id,headId, toggle) {
  if (toggle) {
    $("tr[class*='" + id + "']").show();
    $("tr[class*='" + headId + "']").show();
  }
  else {
    $("tr[class*='" + id + "']").hide();
    $("tr[class*='" + headId + "']").hide();
  }
}

function toggleText(id, toggle) {
  if (toggle) {
    $("input[id*='" + id + "']").show();
    $("input[id*='" + id + "']").focus();
  }
  else
    $("input[id*='" + id + "']").hide();
}

function emptyBox(obj) {
  $(obj).val('');
}
var map;
var gdir;
var geocoder = null;
var addressMarker;

function loadMap() {
  
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));

    geocoder = new GClientGeocoder();
    if (geocoder) {
      var postal = $("input[id*='txtPostal']").val();
      if (postal != "") {
        postal = postal.toString().toUpperCase();
        $("input[id*='txtPostal']").val(postal);
        geocoder.getLocations(postal, showProvence);
        geocoder.getLatLng(
              postal,
              function(point) {
                if (!point) {
                  //alert("Adres niet gevonden, probeer");
                } else {
                  map.setCenter(point, 8);
                  var marker = new GMarker(point);
                  map.addOverlay(marker);
                  marker.openInfoWindowHtml("<b>Postcode:</b> " + postal);
                  //$("#map_canvas").hide();
                }
              }
            );
      }
    }

    gdir = new GDirections(map, document.getElementById("directions"));
   // GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);

    //setDirections("The Netherlands", "Hoogeveen", "nl_NL");
  }
}

function showProvence(response) {
  // Retrieve the object
  try {
    $("input[id*=txtProvence]").val(response.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName);
  } catch (e) { }
}

function setDirections(fromAddress, toAddress, locale) {
//  gdir.load("from: " + fromAddress + " to: " + toAddress,
//                { "locale": locale });
  checkAddress(fromAddress);
}

function checkAddress(adres) {
  geocoder2 = new GClientGeocoder();
  if (geocoder2) {
    geocoder2.getLatLng(
              adres,
              function(point) {
                if (!point) {
                  alert(adres + " is geen geldig adres. Voer als volgt in: Straat + huisnr, postcode plaats");
                }
              }
            );
  }
}

function handleErrors() {
  if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.nError code: " + gdir.getStatus().code);
  else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
    alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.n Error code: " + gdir.getStatus().code);

  else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
    alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.n Error code: " + gdir.getStatus().code);

  //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
  //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.n Error code: " + gdir.getStatus().code);

  else if (gdir.getStatus().code == G_GEO_BAD_KEY)
    alert("The given key is either invalid or does not match the domain for which it was given. n Error code: " + gdir.getStatus().code);

  else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
    alert("A directions request could not be successfully parsed.n Error code: " + gdir.getStatus().code);

  else alert("An unknown error occurred.");

}

function checkEmail(obj) {
  var email = $(obj).val();
  if (email != "") {
    $.ajax({
      type: "GET",
      url: "/nieuwe-advertentie-plaatsen.aspx",
      data: "email=" + email,
      success: function(msg) {
        var data = $.evalJSON(msg);
        if (data.loggedin) {
          $("#txtEmailMsg").html("U bent ingelogd onder dit email-adres.");
          $("input[class=submit]").removeAttr("disabled");
        } else {
          if (data.notavailable) {
            $("#txtEmailMsg").html("Dit e-mailadres bestaat al, kies een andere of log in!");
            $("input[class=submit]").attr("disabled", "disabled");
          } else {
            $("#txtEmailMsg").html("Dit e-mailadres is nog vrij!");
            $("input[class=submit]").removeAttr("disabled");
          }
        }
      }
    });
  }
}
var popup;
var reloadPage = false;
function PopUpLogin(reload) {
  if (reload)
    reloadPage = reload;
  popup = new Boxy($("#loginContent").html(), { title: "Vul uw e-mailadres en wachtwoord in", fixed: false, modal: true, closeText: "[ x ]" });
  $("#loginContent").remove();
  return false;
}

function checkLogin(email, pass, global, typeofpage) {
  var email2 = "";
  var pass2 = "";
  if (global) { //from session
    email2 = email;
    pass2 = pass;
  } else { //from fields
    var email2 = $("input[id*='" + email + "']").val();
    var pass2 = $("input[id*='" + pass + "']").val();
  }

  if ($("input[id*='btnSubmit']").val() == "Verstuur nieuw wachtwoord") { //forgot pass
    if (email2 != "") {
      $.get("/nieuwe-advertentie-plaatsen.aspx?forgetemail=" + email2, function(msg) {
        alert(msg);
      });
    } else {
      alert("Vul het emailadres in.");
    }
  } else { //login
    if (email2 != "" && pass2 != "") {
      $.get("/nieuwe-advertentie-plaatsen.aspx?emaillogin=" + email2 + "&pass=" + pass2, function(msg) {
        var logindata = $.evalJSON(msg);
        if (logindata.AdresRow1 != null) { //succes
          if (reloadPage) {
            window.location = window.location;
          }
          $("input[type='button']").attr("disabled", "disabled");
          $("input[id*='txtAdres']").val(logindata.AdresRow1);
          $("input[id*='txtPostal']").val(logindata.PostalCode);
          $("input[id*='txtCity']").val(logindata.City);
          $("input[id*='dllCountry']").val(logindata.CountryId);
          $("input[id*='txtRentor']").val(logindata.NameRentor);
          $("input[id*='txtCompany']").val(logindata.BusinessName);
          $("input[id*='txtTelefoon']").val(logindata.PhoneMain);
          $("input[id*='txtEmail']").val(logindata.EmailAdres);
          $("input[id*='CountryId']").val(logindata.CountryId);
          $("div[id*='pnlLogin']").html("Uw bent nu ingelogd als: <b>" + logindata.NameRentor + "</b>");
          $("li[id*='menu_login']").html("<a alt='Mijn advertenties' title='Mijn advertenties' href='/mijn-advertenties.aspx'>Mijn account</a>");

          //set cookie
          var cval = $.cookie('settings');
          var cookieval;
          if (cval != null) {
            cval = $.evalJSON(cval);
            cookieval = { menu: cval.menu, email: logindata.EmailAdres, hash: logindata.Password };
          } else {
            cookieval = { menu: true, email: logindata.EmailAdres, hash: logindata.Password };
          }
          $.cookie('settings', $.toJSON(cookieval),{ expires: 365, path: '/', domain: 'onlinecamperhuren.nl', secure: false });

         if (typeofpage == 'fromloginpage'){
            window.location = '/mijn-advertenties.aspx';
         }

         if (popup)
            popup.hide();
          $(".pnlContact input, .pnlContact select").attr("disabled", "disabled");
        } else { //not succesful login
          alert("Gegevens niet juist, probeer het opnieuw.");
        }
      });
    }
  }
  return false;
}

function logout() {
  $.cookie('settings', null,{ expires: -1, path: '/', domain: 'onlinecamperhuren.nl', secure: false });
  window.location.href = "/content/logout.aspx";
}

function togglePanel(classString,obj) {
  $("." + classString).toggle();
  if ($("." + classString).is(":visible")){
    $(obj).find("h2").attr("class", "head-open");
  }
  else {
    $(obj).find("h2").attr("class", "head-closed");
  }
}

function createDateField(index,divid) {
  var html = "<div id='rangeselected" + index + "'><img src='/images/delete.gif' alt='Verwijder periode' title='Verwijder periode' " + 
             "class='delete' onclick='delDate(" + index + ")'/>&nbsp;<input type='hidden' name='rangedata" + index + "' id='rangedata" + index + "' value=''/>" + 
             "<div class='range' id='range" + index + "'></div>&nbsp;&nbsp;&nbsp;&nbsp;<b>" + 
             "Weektarief:</b> € <input type='text' maxlength='7' name='rate" + index + "' id='rate" + index + "' value='<vul bedrag in>' onclick='emptyBox(this);' />" + 
             "<br/></div>";
  $("div[id*='" + divid + "']").append(html);
}

function delDate(index) {
  $("div[id*='rangeselected" + index + "']").remove();
}

function PopUpContent(url,name) {
  $.ajax({
    url: "/content/" + url + ".aspx",
    type: "GET",
    data: "mode=plain",
    success: function(data) {
      popup = new Boxy(data, { title: name, fixed: false, modal: true, closeText: "[ x ]" });
    }
  });
}

function PopUpMail(adid, periodid, desc, rentorname) {
  window.location = "/neem-contact-op-met-verhuurder.aspx?date=" + desc + "&adid=" + adid + "&periodid=" + periodid + "&rentorname=" + rentorname;
  /* sometimes popup doesnt work, so rebuild it to a simple redirect
  $.ajax({
    url: "/views/website/mail.aspx",
    type: "GET",
    data: "date=" + desc + "&adid=" + adid + "&periodid=" + periodid,
    success: function(data) {
      popup = new Boxy(data, { title: desc, fixed: false, modal: true, closeText: "[ x ]" });
      tinyMCE.init({
        mode: "textareas",
        theme: "advanced",
        theme_advanced_buttons1: "bold,italic,underline,bullist,numlist,link, unlink, indent,outdent, undo,redo,help",
        theme_advanced_buttons2: "",
        theme_advanced_buttons3: ""
      });
    }
  });*/
}

function SubmitMailForm(headid, adid, periodid) {
  var table = $("#" + headid);
  var email = escape($(table).find("#email").val());
  var name = escape($(table).find("#name").val());
  var subject = escape($(table).find("#subject").val());
  var msg = escape(tinyMCE.activeEditor.getContent());
  if (email != "" && name != "" && msg != ""){
    $.ajax({
      type: "GET",
      url: "/" + adid + "/ad.aspx?sendmail=true&periodid="  + periodid + "&email=" + email + "&name=" + name + "&subject=" + subject + "&msg=" + msg,
      success: function(msg) {
        var data = $.evalJSON(msg);
        if (data.succes) {
          alert("Bericht is succesvol verzonden, bedankt voor uw tijd. U ontvangt een kopie van het bericht.");
          history.go(-1);
          //popup.hide();
        } else {
          alert("Er ging iets mis tijdens het versturen: \n" + unescape(data.msg));
        }
      }
    });
  } else {
    alert("Vul eerst alle velden in!");
  }
}

function ForgetPass(emailid, passid,buttonid) {
  var email = $("#" + emailid).val();
  var button = $("#" + buttonid);
  $("#" + passid).hide();

  $(button).val("Verstuur nieuw wachtwoord");
  //$(button).attr("onclick","checkLogin('loginEmail','',false);return false;");
  $("#" + emailid).focus();
  
  
}
