﻿/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
*       used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
*                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
*                             If set to null or omitted, the cookie will be a session cookie and will not be retained
*                             when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
*                        require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/

/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
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;
    }
};

   
var location1, location2;
var geocoder = new GClientGeocoder();
geocoder.setBaseCountryCode("nl");
var nearestAddressKmValue = 999999.9;
var nCalback = 0;
var callTimer = null;
function nameCallBack(boolUp, loc2) {
    if (boolUp==true) {
        if(callTimer){
            clearTimeout(callTimer);
        }
        callTimer = setTimeout('showGoogleAddres(\''+myNames[nCalback]+'\')',500);
      //  alert(myNames[nCalback]+" "+loc2.address);
    }
   nCalback++;
  loopCallBack();

}
var location1 = null;
function loopCallBack() {
    if (myAddresses != null && myAddresses.length > 0) {
        if (nCalback < myAddresses.length) {
            var i = nCalback;
            if (myAddresses[nCalback] != "") {
            
                geocoder.getLocations(myAddresses[nCalback], function(response) {
                    if (!response || response.Status.code != 200) {
                        //alert(""Sorry, we were unable to geocode the second address"");
                        nameCallBack(false);
                    }
                    else {
                        location2 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };
                        var glatlng1 = new GLatLng(location1.lat, location1.lon);
                        var glatlng2 = new GLatLng(location2.lat, location2.lon);
                        var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
                        var kmdistance = (miledistance * 1.609344).toFixed(1);

                        if (parseFloat(kmdistance) < parseFloat(nearestAddressKmValue)) {
                            nearestAddressKmValue = kmdistance;
                            document.getElementById('results').innerHTML = '<strong>Van: </strong>' + location1.address + '<br /><strong>Naar: </strong>' + location2.address + '<br /><strong>Afstand: </strong>' + kmdistance + ' Km<br/><br/>';
                             nameCallBack(true, location2);

                        } else {
                            nameCallBack(false);
                        }
                    }
                });
            } else {
                nameCallBack(false);

            }
        }
    }
}
function setPlaatsPost() {
if (document.forms[0].plaats.checked) {
        document.forms[0].address1.value = '';
        document.forms[0].address1.maxLength = 255;
        document.forms[0].address1.setAttribute("maxlength",255);
     //   document.forms[0].address1.setAttribute("size", 255);

    } else {

    document.forms[0].address1.value = '';
    document.forms[0].address1.maxLength = 6;
    document.forms[0].address1.setAttribute("maxlength", 6);
   // document.forms[0].address1.setAttribute("size", 6);
    }
}
function setLocation(x) {
    nCalback = 0;   
    document.getElementById('results').innerHTML = '<strong>Van: </strong><br /><strong>Naar: </strong><br /><strong>Afstand: <br/><br/>';
    nearestAddressKmValue = 999999.9;
  
    address =document.forms[0].address1.value ;
    geocoder.getLocations(address + ", Nederland, NL", function(response) {
        if (!response || response.Status.code != 200) {
            //alert(""Sorry, we were unable to geocode the first address"");
        }
        else {
            location1 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };
           loopCallBack();
        }
    });
}


var cindex = 0;
var notfound="";
var lastMarker=null;
var cIcon=null;
var cmsmode = 0;
function showGoogleAddres(linkItem) {
    maplay = document.getElementById("mapblock");
    if (maplay && maplay.style.display != 'block') {
        maplay.style.display = 'block';
        map = new GMap2(document.getElementById("mymap"));
        map.addControl(new GLargeMapControl());
        geocoder = new GClientGeocoder();
        map.setCenter(new GLatLng(37.546691, 93.164063), 15);
    }
     map.clearOverlays();
    var cindex = linkItem;
    if (linkItem && linkItem.innerText) {
        cindex = linkItem.innerText;
    }
    var did = null;

    for (var i in mapitems) {
         did = document.getElementById("info" + i);
        if (did) {
            did.style.display = 'none';
        }
    }

     if (mapitems[cindex] == null) {
        return;
    }
   
    did = document.getElementById("info" + cindex);
    
    if (did) {
        did.style.display = 'block';
    }
    gaddress = mapitems[cindex][1];
    //alert(gaddress);
    //alert(mapitems[cindex][0]);
    geocoder.getLatLng(mapitems[cindex][0],
	                   function(point) {
	                       if (!point) {
	                           notfound += mapitems[cindex][0] + " not found\n";
	                       } else {

	                       
	                           mapitems[cindex][4] = point;
	                           map.setCenter(point, 16);

	                           var marker = new PdMarker(point);

	                           marker.address = mapitems[cindex][0];
	                           marker.pagehref = mapitems[cindex][3];
	                           //var desc = mapitems[cindex][1];
	                           // alert(marker.address);
	                           lastMarker = marker;
	                           map.addOverlay(marker);
	                           // GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml("<div class='mapdesc'>"+desc+"</div>");});
	                           // GEvent.addListener(marker, "click", function() {document.location=this.pagehref});
	                           // GEvent.addListener(marker, "mouseover", function() { marker.openInfoWindowHtml("<div class='mapdesc'>" + desc + "</div>"); }
	                       }
	                   }
	                      );
}
function showAddress(setCenter) {
   if(cindex <mapitems.length){
	          gaddress = mapitems[cindex][1];
	          geocoder.getLatLng(mapitems[cindex][0],
	                   function( point) {
	                        if (!point) {
	                          notfound+=mapitems[cindex][0] + " not found\n";
				            } else {
				              mapitems[cindex][4] = point;
				              if(setCenter==1){
				                map.setCenter(point,16);
				              }
				                   
               var marker = new PdMarker(point);
							  							 
 marker.address = mapitems[cindex][0];
							  marker.pagehref = mapitems[cindex][3];
	                          var desc = mapitems[cindex][1];
	                         // alert(marker.address);
	                          lastMarker = marker;
				              map.addOverlay(marker);
	                         // GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml("<div class='mapdesc'>"+desc+"</div>");});
	                          GEvent.addListener(marker, "click", function() {document.location=this.pagehref});
	                          GEvent.addListener(marker, "mouseover", function() { marker.openInfoWindowHtml("<div class='mapdesc'>" + desc + "</div>"); }
	                      );
	                        }
				            cindex++;
				            setTimeout('showAddress()',0);
	                  });
	      
	  }else{
		if(notfound!=''){
		   alert(notfound);
		}else{

			map.zoomToMarkers(12,0);
		}

	  }
    }


function processRouteResult()
{
    // TODO test if any route was found
    var sm = lastMarker ;
    if (sm) {
        sm.closeInfoWindow();
    }
    // enable print-button
    //var print = document.getElementById('printroute');
    //print.className = '';
    // TODO adjust margins for route
    // TODO add 'clear route' link
}


function processRouteLoad()
{
    // this method gets called when a user submits a route request
}

function processErrorResult()
{
alert('Uw postcode of straat, plaatsnaam kan niet door Google gevonden worden');
    // this method gets called when a user submits a route request
}
var dir = null;
function submitRouteForm(form)
{
    var sm = lastMarker ;

    if (sm) {
        if(dir != null){
          dir.clear();
        }
        dir = new GDirections(window.map, document.getElementById('route'));
      
        document.getElementById('route').innerHTML='';
        GEvent.addListener(dir, "load", processRouteLoad);
        GEvent.addListener(dir, "addoverlay", processRouteResult);
        GEvent.addListener(dir, "error", processErrorResult);
      //    alert(form.departure.value+" " +sm.address);
      
        dir.loadFromWaypoints([form.departure.value+", Nederland",sm.address], {locale:"nl_NL"});
    }

    return false;
}




