﻿
/* ---------------------------------------------------------------------------------- */
/* ----- Functies: onLoad ----------------------------------------------------------- */
/* ---------------------------------------------------------------------------------- */
var lang = 'nl';
$(document).ready(function() {
  //FLASH
  if ($('#dokkum3d').length > 0) {
    loadScene(1);
  }

  // Lightbox activeren
  if ($("a[rel*=lightbox]").length > 0) {
    $("a[rel*=lightbox]").lightbox();
  }
  $("#overlay").css({ "opacity": "0.6" });

  $("#dokkum3d-overlay").css({ "opacity": "0.6" });

  // Carousel op home activeren
	if ($('#carousel_home_inner').length > 0) {
    var carousel_home = $('#carousel_home_inner').innerfade({
      speed: 'slow',
      timeout: 3500,
      type: 'sequence',
      containerheight: '297px'
    });
	}

  $("#locations_dropdown_inner").addClass("active");
  $("#types_dropdown_inner").addClass("active");
  $("#sfeerafbeeldingen img:not(img:first)").hide();
  if ($("#content #sfeerafbeeldingen img").length == 1) {
    $("#content #sfeerafbeeldingen .button_sfeerafbeeldingen").hide();
  }

  if (typeof initializeerKaart == 'function') {
    initializeerKaart();
  }

  $('#dokkum3d-popup #close').click(function() {
    $('#dokkum3d-popup').fadeOut(400, function() {
      $('#dokkum3d-overlay').fadeOut(400);
    });
  });

  // Dokkum Streets.
  if ($('#mycarousel').length > 0) {
    $('#mycarousel').jcarousel({
      scroll: 1,
      initCallback: mycarousel_initCallback
      // This tells jCarousel NOT to autobuild prev/next buttons
    });
  }
  if ($('#mycarousel2').length > 0) {
    $('#mycarousel2').jcarousel({
      scroll: 1,
      initCallback: mycarousel_initCallback
      // This tells jCarousel NOT to autobuild prev/next buttons
    });
  }

  $('.street-rechts').hide();

  $('.links').click(function() {
    $('.street-links').show();
    $('.street-rechts').hide();

    $('.dokkum-streets-title a').removeClass('active');
    $(this).addClass('active');
    return false;
  });

  $('.rechts').click(function() {
    $('.street-rechts').show();
    $('.street-links').hide();
    
    $('.dokkum-streets-title a').removeClass('active');
    $(this).addClass('active');
    return false;
  });
  
  // Translate.
  $.translate(function(){  //when the Google Language API is loaded
    $('#language_choice a').click(function() {
      // Vertalen.
      translateTo($(this).text());
    });
    
    // Controleren of er al een vertaling is gekozen.
    var destLang = $.cookie('destLang'); //get previously translated language
    if( destLang )  //if it was set then
        translateTo( destLang ); // translate.
  }); //end of Google Language API loaded
});

function translateTo( destLang ){ //this can be declared in the global scope too if you need it somewhere else
  // Laatste gekozen vertaling opslaan.
  $.cookie('destLang', destLang );
  $('body').translate( 'nl', destLang, {   //translate from english to the selected language
    fromOriginal:true   //always translate from english (even after the page has been translated)
  });
}

/* ---------------------------------------------------------------------------------- */
/* ----- Functies: Algemeen --------------------------------------------------------- */
/* ---------------------------------------------------------------------------------- */

// Dokkum streets
function mycarousel_initCallback(carousel) {
    $('.jcarousel-control a').bind('click', function() {
        carousel.scroll($.jcarousel.intval($(this).text()));
        return false;
    });

    $('.jcarousel-scroll select').bind('change', function() {
        carousel.options.scroll = $.jcarousel.intval(this.options[this.selectedIndex].value);
        return false;
    });

    $('.mycarousel-next').bind('click', function() {
        carousel.next();
        return false;
    });

    $('.mycarousel-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};

// Standaard-tekst in input verbergen (onFocus)
function textFieldFocus(object, defaultValue) {
  if (object.value == defaultValue) {
    object.value = "";
  }
}

// Standaard-tekst in input tonen (onBlur)
function textFieldBlur(object, defaultValue) {
  if (object.value == "") {
    object.value = defaultValue;
  }
}

var debug = false;
function printToConsole(text) {
  if (debug) {
    if (window.console) {
      //console.log(text);
    }
  }
}

// Dropdown tonen/verbergen
function toggleDropdown(evt){
  if (!evt) {
    var evt = window.event;
  }
  if ($("#locations_dropdown_inner").css("display") != 'block') {
    $("#locations_dropdown_inner").css("display", "block");
    evt.cancelBubble = true;
    document.body.onclick = toggleDropdown;
    return false;
  } else {
    $("#locations_dropdown_inner").css("display", "none");
    document.body.onclick = null;
    return true;
  }
} 

// Dropdown tonen/verbergen
function toggleDropdown2(evt){
  if (!evt) {
    var evt = window.event;
  }
  if ($("#types_dropdown_inner").css("display") != 'block') {
    $("#types_dropdown_inner").css("display", "block");
    evt.cancelBubble = true;
    document.body.onclick = toggleDropdown2;
    return false;
  } else {
    $("#types_dropdown_inner").css("display", "none");
    document.body.onclick = null;
    return true;
  }
} 

/* ---------------------------------------------------------------------------------- */
/* ----- Functies: Uitgelicht Kalender ---------------------------------------------- */
/* ---------------------------------------------------------------------------------- */

function changeMonth(intMonth, intYear, strType, strId) {
  var url = "ajax/ajax_kalender";
  // Via ajax nieuwe content ophalen en de data (HTML) op de juiste plaats in de content plaatsen.
  $.get("/pages/" + url + ".aspx?maand=" + intMonth + '&jaar=' + intYear + '&type=' + strType + '&id=' + strId + '&v=4', function(data){eval(data);});
}

/* ---------------------------------------------------------------------------------- */
/* ----- Functies: Locatie - Plaats ------------------------------------------------- */
/* ---------------------------------------------------------------------------------- */

function vorigeSfeerAfbeelding() {
  var cur = $('#sfeerafbeeldingen:visible img:visible');
  var next = null; 
  if ($('#sfeerafbeeldingen:visible img:first:visible').length > 0) {
    //next = $('#sfeerafbeeldingen img:not(img:visible):last');
    next = $('#sfeerafbeeldingen:visible img:last');
  } else {
    next = $('#sfeerafbeeldingen:visible img:visible').prev('img');
  }
  if ((cur.length > 0) && (next.length > 0)) {
    $(cur).fadeOut(300);
    $(next).fadeIn(300);
  } else {
    //$('#sfeerafbeeldingen a').hide();
  }
}

function volgendeSfeerAfbeelding() {
  var cur = $('#sfeerafbeeldingen:visible img:visible');
  var next = null; 
  if ($('#sfeerafbeeldingen:visible img:last:visible').length > 0) {
    next = $('#sfeerafbeeldingen:visible img:not(img:visible):first');
  } else {
    next = $('#sfeerafbeeldingen:visible img:visible').next('img');
  }
  if ((cur.length > 0) && (next.length > 0)) {
    $(cur).fadeOut(300);
    $(next).fadeIn(300);
  } else {
    //$('#sfeerafbeeldingen a').hide();
  }
}

function toggleParagraaf(div) {
  $(div).toggleClass('uitgeklapt');
}

/* ---------------------------------------------------------------------------------- */
/* ----- Functies: Google maps v2 --------------------------------------------------- */
/* ---------------------------------------------------------------------------------- */

var EARTH_RADIUS = 6378.137; //in kilometres
function drawCircle(map, centrePt, rangeValue) { 
  var boundaries = getBoundaries(centrePt, rangeValue); 
  var circle = new GGroundOverlay("/images/map_overlays/circle.png", boundaries); 
  map.addOverlay(circle);
}

function getBoundaries(centrePt, radius) { 
  var hypotenuse = Math.sqrt(2 * radius * radius); 
  var sw = getDestLatLng(centrePt, 225, hypotenuse); 
  var ne = getDestLatLng(centrePt, 45, hypotenuse); 
  return new GLatLngBounds(sw, ne);
}

function getDestLatLng(latLng, bearing, distance) { 
  var lat1 = latLng.latRadians(); 
  var lng1 = latLng.lngRadians(); 
  var brng = bearing*Math.PI/180;  
  var dDivR = distance/EARTH_RADIUS; 
  var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dDivR) + Math.cos(lat1) * Math.sin(dDivR) * Math.cos(brng)); 
  var lng2 = lng1 + Math.atan2(Math.sin(brng) * Math.sin(dDivR) * Math.cos(lat1), Math.cos(dDivR)-Math.sin(lat1) * Math.sin(lat2)); 
  return new GLatLng(lat2/ Math.PI * 180, lng2/ Math.PI * 180);
}


/* ---------------------------------------------------------------------------------- */
/* ----- Functies: Dokkum 3D -------------------------------------------------------- */
/* ---------------------------------------------------------------------------------- */

// Console print functie, crasht niet in het geval van IE.
function cPrint(string) {
  if (typeof(console) !== 'undefined' && console != null) {
	  //console.log(string);
	}
}

var curScene = 'x';
// Een bepaalde scene (1,2 of 3) van dokkum3d inladen.
function loadScene(sceneId) {
  //cPrint('Loadscene called with param: ' + sceneId);
  
	var blnAppend = false;
	if (curScene == 'x') {
	  blnAppend = true;
	}
	
	// Eventueel een object verwijderen.
	if (($('#content object:first').length > 0) && (curScene != sceneId)){
	  //cPrint('SWF Object verwijderen.');
	  $('#content #dokkum3d-container object:first').remove();
	  $('#content #dokkum3d-container').append($('<div id="dokkum3d"></div>'));
	  blnAppend = true;
	  $('#dokkum3d-progress').show();
	}
	
	if (blnAppend) {
	  // Variabelen instellen en flash loaden dmv swfobject.
	  //cPrint('Loading scene: ' + sceneId);
	  curScene = sceneId;
	  //params
	  var swf = '/interface/flash/3d/version1/d3d.swf?v=1' + new Date().getTime();
	  var width = "940";
	  var height = "522";
	  var version = "10.0.0";
	  var expressInstall = "expressInstall.swf";
	  //params
	  var params = {};
	  params.menu = 'false';
	  params.quality = 'high';
	  params.bgcolor = 'ffffff';
	  params.wmode = 'window';
	  params.allowFullScreen = 'false';
	  params.allowscriptaccess = 'always';
	  //attriubtes
	  var attributes = {};
	  attributes.name= 'application';
	  attributes.id = 'application';
	  attributes.align = 'left';
	  attributes.border = '0';
	  //flashvars
	  var flashvars = {};
	  flashvars.id = sceneId;
	  flashvars.xml = '/interface/flash/3d/version1/models_' + sceneId + '.xml';
	  flashvars.total = '3';
	  //embed
	  swfobject.embedSWF(swf, "dokkum3d", width, height, version,expressInstall, flashvars, params, attributes);
	  $('#content #dokkum3d-container').css('left','-9000px');
	}
	else
	{
	  //cPrint('No action has been taken.');
	}
}

function resetLoading() {

}

function loadingProgress(category, progress) {
 //cPrint('Loadingprogress: ' + category + ', ' + progress + '%.');
 //if ($('#dokkum3d-progress #' + category).length > 0) {
 //  $('#dokkum3d-progress #' + category).prev('div').attr('width',100 + 'px');
 //  $('#dokkum3d-progress #' + category).attr('width', progress);
 //} else {
 // $('#dokkum3d-progress').append('<div id="' + category + '" style="height: 1px; background-color: #ffde00; overflow: hidden; text-indent: -99999px; width:' + progress + 'px">' + category + '</div>');
  //}
  $('#dokkum3d-progress').show();
  
  var breedte = (progress / 100) * 163;

  $('#dokkum3d-progress #dokkum3d-loading').css('width', breedte + 'px');
  $('#dokkum3d-progress #dokkum3d-loading #dokkum3d-loading-tekst').html(category + ', ' + progress + '%.');
}

function loadComplete() {
  $('#dokkum3d-progress').hide();
  $('#content #dokkum3d-container').css('left','0px');
}

function toonWinkel(winkelId) {
  //cPrint(winkelId);
  // Via ajax de content van de winkel ophalen.
  loadWinkel(winkelId);
  // Eerst een loader in de popup tonen.
  // 
  $('#dokkum3d-overlay').height($(document).height()).fadeIn(400, function() {
    $('#dokkum3d-popup').fadeIn(400, function () {
      $('#content #dokkum3d-container').css('left','-9000px');
    });
  });
  return false;
}

function loadWinkel(winkelId) {
  //cPrint('loadWinkel: ' + winkelId);
  var url = "ajax/ajax_3d";
  // Via ajax nieuwe content ophalen en de data (HTML) op de juiste plaats in de content plaatsen.
  $.get("/pages/" + url + ".aspx?winkel=" + winkelId + '&v=1', function(data){
    cPrint('Winkel loaded');
    // De inhoud in de #dokkum3d-popup-content plaatsen.
    $('#dokkum3d-popup-content').replaceWith(data);
    
    $('#dokkum3d-popup #close').click(function() {
      $('#dokkum3d-popup').fadeOut(400, function() {
        $('#dokkum3d-overlay').fadeOut(400);
        $('#content #dokkum3d-container').css('left','0px');
      });
    });
    
    $("#sfeerafbeeldingen img:not(img:first)").hide();
    if ($("#content #sfeerafbeeldingen img").length == 1) {
      $("#content #sfeerafbeeldingen .button_sfeerafbeeldingen").hide();
    }
  });
}

// Cookie functionaliteit, vanwege het gebruik hiervan, dit opgenomen in de functions.js.
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            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
        }
        // CAUTION: 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;
    }
};