function brpRouteWidget(opts, container){
	
	// properties
	var me=this;
	var UsingRouteDB = true;
	try {
		if (frpgetRouteListUrl == null) {
			UsingRouteDB = false;
		}
	}
	catch(e) {
		UsingRouteDB = false;
	}
	me.opts = cpyObj(opts, {buttonBasePath: brpBaseUrl + 'images/buttons',printPageUrl:'print1.html', iconPath: brpIconPath + 'lists/'});

    // temp override iconpath
    me.opts.iconPath = 'images/icons/lists/';    
    me.WebShopAllowed = true;
    
	me.container = $(container);
	me.locations = [];
	me.routeName = null;
	me.routeID = null;
	me.route = null;
	me.guid = null;
	me.roundTrip = false;
	me.routeType = 'U';
	me.barIndex = 0;
    me.options = null;
    me.validIdx =-1;
    me.routedetail = new brpRouteDetailWidget($('#route_detail'));
	// event methods
	me.onLocationsChanged = null;
	me.onLocationClicked = null;
	me.onRouteChanged = null;
	me.onPlanRoute = null;
    me.onClearRoute = null;  
    me.pois = brpCategories;
  
	// create tabs
	//TWISTED CHANGE
	$('ul.locationlist,ol.locationlist').sortable({
		update: function(event, ui) {
			
			var item = ui.item[0];
			var from = ui.item.attr('idx');
			var to = 0;
			
			while(item){
				if(item.nodeName=='LI') to+= 1;
				item= item.previousSibling;
			}
			to--;
			var el = me.locations.splice(from, 1)[0];
			me.locations.splice(to, 0, el);
			
			me.renderLocList();	
			me.computeRoute();
			event.stopPropagation();
		},
		axis: 'y',
		handle: '.handle',
		placeholder: 'drag'
	});
	
	// attach handlers
	$('.locations-clear').click(function(){
        me.clearPoi();    
        me.clearRoute();
        mw.loadIcons();
        me.clearLocations();

	});
	
	$('input:checkbox.roundtrip', container).click(function(event){me.checkRoundtrip();});
	
  $('#bar_startingpoint').click(function(){me.showFirstLoc();});  
  $('#bar_endpoint').click(function(){me.showLastLoc();});
  $('#bar_all').click(function(){me.showAllLoc();});   
  $('.print').click(function(event){me.printRoute();});
  $('.routeto', container).click(function(event){me.transport('to');});
  $('.routefrom', container).click(function(event){me.transport('from');});
  $('.offer-close').click(function(event){me.HideWebshopProduct();});
  $('#step1_head a', container).click(function(event){me.SetBar(1);me.showMap();});
  $('#step1_head a', container).click(function(event){me.HideWebshopProduct();});
  $('#step2_head a', container).click(function(event){me.SetBar(2);me.showMap();});
  $('#step2_head a', container).click(function(event){me.HideWebshopProduct();});
  $('#step3_head a', container).click(function(event){me.SetBar(3);me.showMap();});
  $('#step3_head a', container).click(function(event){me.HideWebshopProduct();});
  $('#step4_head a', container).click(function(event){me.SetBar(4);me.showMap();});
  $('#step4_head a', container).click(function(event){me.ShowWebshopProduct(me);});
  $('#next1', container).click(function(event){me.SetBar(2);me.showMap();});
  $('#next2', container).click(function(event){me.SetBar(3);me.showMap();});
  $('#next3', container).click(function(event){me.SetBar(4);me.showMap();});
  $('#next3', container).click(function(event){me.ShowWebshopProduct(me);});
  $('#prev2',	container).click(function(event){me.SetBar(1);me.showMap();});
  $('#prev3',	container).click(function(event){me.SetBar(2);me.showMap();});
  $('#prev4',	container).click(function(event){me.SetBar(3);me.showMap();});
  $('#prev4',	container).click(function(event){me.HideWebshopProduct();});
  $('#poi1_head a',	container).click(function(event){me.SetPoi(1);me.showMap();});
  $('#poi2_head a',	container).click(function(event){me.SetPoi(2);me.showMap();});
  $('#poi3_head a',	container).click(function(event){me.SetPoi(3);me.showMap();});
  
    
     
  
	// get state
	this.checkRoundtrip();
	this.SetBar(1);
    $('#start-info').hide();    
    $('#end-info').hide();    
	this.SetPoi(1);

	// Get Route
	if (UsingRouteDB){ 
		this.getRoute(getHttpParam('RouteID'));
	}

};

brpRouteWidget.prototype.clearRoute = function() {
    var me = this;
    me.routeID = null;
    me.routeName = null;
	me.routeType = 'U';
	me.roundTrip = false;
    me.routedetail.routeID = null;
    me.guid = null;
    $("#bar_open").removeClass("bar_open_return");
    $('#routename-name').val($('#routename-name').data('defaultVal'));
    $('#routename').val('');
    $('#routenametitle').html('');
    $('#routenametitle2').html('');

}

brpRouteWidget.prototype.clearPoi = function() {

    $('.selectall').attr('checked',false);
    $('.poi').each(function(){
        this.checked = false;            
        if (brpCategories[parseInt(this.value)])
            brpCategories[parseInt(this.value)].visible = false;
    });

}

brpRouteWidget.prototype.checkRoundtrip = function(){
 	this.roundTrip = $('.roundtrip', this.container).is(':checked');
	this.computeRoute();
}

brpRouteWidget.prototype.transport = function(fromto){
	if (fromto=='to'){
		var loc = this.locations[0];
		var url = 'http://routeplanner.falk.nl/rp/?action=0&lat2=' + loc.lat + '&lon2=' + loc.lon + '&name2=' + loc.name;
	}
	else {
		var loc = this.locations[this.locations.length-1];
		var url = 'http://routeplanner.falk.nl/rp/?action=0&lat1=' + loc.lat + '&lon1=' + loc.lon + '&name1=' + loc.name;
	}
	window.open(url);
}

brpRouteWidget.prototype.addLocation = function(loc){
	if ((this.locations.length==0)||(this.locations[this.locations.length-1]!=loc)){
		this.clearRoute();
		this.roundTrip = $('.roundtrip', this.container).is(':checked');
		this.locations.push(loc);
		this.renderLocList();
		this.computeRoute();
	}
    if (this.locations.length == 1)	{
      this.SetBar(2);
    }

}

brpRouteWidget.prototype.createLocRowClickHandler = function(idx){
	var me = this;
	return function(event){me.locRowClicked(event, idx);}; 
};

brpRouteWidget.prototype.createRouteRowClickHandler = function(idx){
	var me = this;
	return function(event){me.RouteRowClicked(event, idx);}; 
};

brpRouteWidget.prototype.RouteRowClicked = function(event, idx){
    this.getRoute(idx);
	event.stopPropagation();    
};

brpRouteWidget.prototype.locRowClicked = function(event, idx){
	var row = $('.locationlist li:eq(' + idx +  ')', this.container);
	if ( $(event.target).hasClass('locicon')
       || $(event.target).hasClass('locname')) {
		this.locationClicked(idx);
	}
	else {
		if ( $(event.target).hasClass('locdelete') ){
			this.locations.splice(idx, 1);
		}
		else if ( $(event.target).hasClass('locmovedown') ){
			var el = this.locations.splice(idx, 1)[0];
			this.locations.splice(idx + 1, 0, el);
		}
		else if ( $(event.target).hasClass('locmoveup') ){
			var el = this.locations.splice(idx, 1)[0];
			this.locations.splice(idx - 1, 0, el);
		}
		this.renderLocList();	
		this.computeRoute();	
	}
	event.stopPropagation();
};

brpRouteWidget.prototype.getRoute = function(RouteID,opt,validIdx) {
    if (RouteID) { 
        //this.clearLocations();
        var me = this;
        me.options = opt;
        me.validIdx = validIdx;
        $.getJSON(frpgetRouteUrl + '&callback=?', {'RouteID': RouteID}, function(data, textStatus) { me.afterGetRoute(data, textStatus) });
    }
};


    



    
    
	


                      
    
	

brpRouteWidget.prototype.getRouteList = function() {
    var me = this;
    $.getJSON(frpgetRouteListUrl + '&callback=?', {}, function(data, textStatus) { me.afterGetRouteList(data, textStatus) });
};

brpRouteWidget.prototype.afterGetRouteList = function(data, textStatus) {

  	function textLink(text){
		return '<a href="javascript:void(0);">' + text + '</a>'
	}

    
    $('.routelist', this.container).empty();
    var me = this;
    for(var I=0; I < data.length;I++) {
        var n = data[I].RouteID;
        var row = $('<li class="userrouterow"></li>').click(me.createRouteRowClickHandler(n));
        row.attr('idx',n);
        row.append(textLink(data[I].RouteName));
        if(data[I].Static) {
            $('#systemroutes').append(row);
        }
        else {
            $('#userroutes').append(row);
        }
    }
    $('.userrouterow').click(function(event){$('#step1_manual').show();});
};

brpRouteWidget.prototype.afterGetRoute = function(data, textStatus) {
    

    if(!data) return; 
    
    this.roundTrip = data.RoundTrip;
    this.routeID = data.RouteID;
    this.routeName = data.RouteName;
    this.routeType = data.RouteType;
    this.startPoint = data.StartPoint;
    this.endPoint = data.EndPoint;
    
    //update RouteDetail
    this.routedetail.routeID = data.RouteID;    

    $('.roundtrip', this.container).attr('checked', this.roundTrip);
    $('#routename-name').val(data.RouteName);
    $('#routename').val(data.RouteName);
    $('#routenametitle').html(data.RouteName);
    $('#routenametitle2').html(data.RouteName);
    
    if (getHttpParam('RouteID') != data.RouteID  || ('' == getHttpParam('toname') || '' == getHttpParam('sendername')))
    {
    	$('.welcomefrommail').hide();
    }
    else
    {
    	$('#emailtoname').html(getHttpParam('toname'));
	    $('#emailfromname').html(getHttpParam('sendername'));
	    $('#routewrapper').addClass('routewrapper_small');
	    $('.welcomefrommail').show();
    }
    this.locations = data['Locations'];
    if (!this.locations) 
      this.locations = [];
   	//
   	this.renderLocList();
	this.computeRoute();

    var p = data.Pois.split("|");
            	

	if (this.onShowCategorie)
	    this.onShowCategorie(p);
    
    this.showAllLoc();
    
    if (this.onDrawBase)
        this.onDrawBase(data.BaseCoords);
        
    if (this.options) {
        switch(this.options) {
        case ('A'):
  	        $('div#route_list').hide();
	        $('div#map').hide();
	        this.routedetail.renderPage(data,this.validIdx);
            break;          
        case ('I'):    
  	        $('div#route_list').hide();
	        $('div#route_detail').hide();
	        $('div#map').show();
            break;
        case ('P'):
            this.printRoute();
            break;
        case ('M'):
            this.setRoute();
            break;
        case ('O'):
            this.setSaveRoute();
            break;        
        case ('T'):
        case ('R'):            
        }
        this.options = null;
    }	    
};
brpRouteWidget.prototype.afterSetRoute = function(data, textStatus) {
    this.getRouteList();
};

brpRouteWidget.prototype.computeRoute = function() {
	if (this.locations)
	{
	    var len = this.locations.length;
        if (len >= 2 || (len == 1 && this.roundTrip)) {
		    if (this.onPlanRoute) this.onPlanRoute();
            var me = this, prms = this.serializeLocationsUrl({});
            $.getJSON(brpPlanRouteUrl + '&format=json&callback=?', prms, function(data, textStatus) { me.routeLoaded(data, textStatus) });
        } else if (this.route) {
		    this.route = null;
		    this.routeChanged();
        }
    }
}

brpRouteWidget.prototype.routeLoaded = function(data, textStatus){
	if (data != this.route){
		this.route = data;
		
		for(var i=0; i < this.route.sections.length; i++) {
		    if (this.route.sections[i].start.name == '')
		        this.route.sections[i].start.name = this.locations[i].name;
		} 
		if (this.route.sections[this.route.sections.length-1].destination.name == '')
		{
		    this.route.sections[this.route.sections.length-1].destination.name = this.locations[this.locations.length-1].name;
		}
		this.routeChanged();
	}
}

brpRouteWidget.prototype.clearLocations = function(){
	this.locations.length = 0;
    if ($('.roundtrip', this.container))
	    $('.roundtrip', this.container).attr('checked', false);
	this.roundTrip = false;
	this.renderLocList();
	this.computeRoute();
	$('.locationlist', this.container).empty();
	if (this.onClearRoute)
	    this.onClearRoute();
}

brpRouteWidget.iconStrDef = '<img id="%0" src="%1" alt="%2" width="27" height="27" />';
brpRouteWidget.iconStrUsr = '<img id="%0" src="%1" alt="%2" width="27" height="27" />';

brpRouteWidget.prototype.crtListIconTag = function(idx, loc){
	var path = this.opts.iconPath;
	var sIconNr = (loc.iconnr ? loc.iconnr.toLength(2) : '00');
	var imgUrl;
	if (idx == 0)
	{
	    imgUrl = './images/icons/map/start';
	}
	else if
	    (((!this.roundTrip) && (idx == this.locations.length-1))||
	    ((this.roundTrip) && (idx == this.locations.length)))
	    imgUrl = './images/icons/map/end';
	else
	    imgUrl = './images/icons/map/this';
	    
	if (loc.category == BRP_CAT_JUNCTIONS) {
		return brpRouteWidget.iconStrDef.format('icon' + loc.id, imgUrl+'junction%0.png'.format(sIconNr), loc.name);
    }
	if (loc.category == BRP_CAT_ADDRESS) {
	   if (idx ==0)  
	     return brpRouteWidget.iconStrDef.format('icon' + loc.id, './images/icons/map/startpuntjunction.png', loc.name);
	   else if (idx == this.locations.length-1)
	           return brpRouteWidget.iconStrDef.format('icon' + loc.id, './images/icons/map/starteindpunt.png', loc.name); 
	        else   
		       return brpRouteWidget.iconStrDef.format('icon' + loc.id, './images/icons/map/tussenpunt.png', loc.name);
	}
	if (loc.category){
		var icn = (brpCategories[loc.category] || {})['listIcon'];		
		if (icn) {
            var c = loc.category || '00';
            imgUrl += 'poi%0.png'.format(c.toLength(2));
            imgUrl = imgUrl.replace('this','');
            return brpRouteWidget.iconStrUsr.format('icon' + idx, imgUrl, loc['name']);
    }
	}
	if (loc.advicecode) {
		if (loc.advicecode == 'ToBicycleJunction')
			return brpRouteWidget.iconStrDef.format('icon' + idx, '%0junction%1.png'.format(path, sIconNr ), loc.advice);
		if (loc.advicecode == 'UserLocation')
			return brpRouteWidget.iconStrDef.format('icon' + idx, '%0&type=icon&id=%1.png'.format(brpUserIconPath, sIconNr ), loc.advice);
		return brpRouteWidget.iconStrDef.format('icon' + idx, '%0%1.png'.format(path, loc.advicecode.toLowerCase()), loc.advice)
	}
	return ''
}

brpRouteWidget.prototype.renderLocList = function(){

	function textLink(sClass, text){
		return '<a class="'+sClass+'" href="javascript:void(0);">' + text + '</a>'
	}

	function imageLink(sClass, src, alt){
		return '<a class="%0" href="javascript:void(0);">'.format(sClass)
      + '<img class="%0" src="%1" alt="%2" width="24" height="24" />'.format(sClass, src, alt)
      + '</a>';
	}
	
	
	if ((this.locations)&&(this.locations.length > 0))
	    $('#find-widget h3').html('Mijn volgende routepunt is');
	else
	    $('#find-widget h3').html('Ik wil fietsen vanaf');
	
	if ((this.locations)&&(this.locations.length > 1))
	    return;
	else
	{
	
	var me = this;
	$('.locationlist', this.container).empty();
	var header = $('<div class="pointright"><p>afstand &nbsp; tijd</p></div>');
	$('#locationheader', this.container).html(header);
	if (this.locations) 
	{	             
	    for (var n=0; n<this.locations.length; n++){
		    var row = $('<li></li>').click(me.createLocRowClickHandler(n)), loc = this.locations[n];
		    row.attr('idx',n);

            var oLeftDiv = $('<div class="pointleft"></div');
            $(this.crtListIconTag(n, loc))
               .addClass('locicon mappoint')
               .appendTo($('<a href="javascript:void(0);"></a>'))
               .appendTo($('<span class="icon"></span>'))
               .appendTo(oLeftDiv);       
            oLeftDiv.append(textLink('locname', loc['name']));
            row.append(oLeftDiv);

            var oRightDiv = $('<div class="pointright"></div');
                oRightDiv.append('<span class="lockm">0 km.</span>');
                oRightDiv.append('<span class="loctime"></span>');
                oRightDiv.append('<span class="button">'  + imageLink('locdelete',   $('body').data('sUiImageDirUrl')+'/mappoint-delete.png', 'Verwijder') + '</span>');
            row.append(oRightDiv);

            row.append('<div class="clearfix">&nbsp;</div>');

            $('ul.locationlist', this.container).append(row);

		    if (n==0)
		      $('#routestartpoint').html(loc['name']);

		    if (n==this.locations.length-1)
		      $('#routedestination').html(loc['name']);
    		    
	    } 
	    if (this.onLocationsChanged) this.onLocationsChanged(this.locations);
	    }
   }
}

brpRouteWidget.prototype.showFirstLoc = function(){
    if(this.locations && (this.locations.length >0)){
	    if (this.onLocationClicked) this.onLocationClicked(this.locations[0])
    }	
}
brpRouteWidget.prototype.showLastLoc = function(){
    if(this.locations && (this.locations.length >0)){
	    if (this.onLocationClicked) this.onLocationClicked(this.locations[this.locations.length-1])
    }	
}
brpRouteWidget.prototype.showAllLoc = function(){
    if(this.locations && (this.locations.length >0)){
         var cP = [];
         cP = this.CenterPointRoute(this);
         
         var C = [];
         C.x = Math.round(cP.centerX);
         C.y = Math.round(cP.centerY);
         
         var R = new  Andes.Rectangle(new Andes.Coordinate(cP.topX,cP.topY),new Andes.Coordinate(cP.bottomX, cP.bottomY) );
         
         var Z = mw.map.getRectZoomLevel(R);
         
         mw.zoomTo(C,Z);
    }
}
// callbacks
brpRouteWidget.prototype.locationClicked = function(idx){
	if (this.onLocationClicked) this.onLocationClicked(this.locations[idx])
}

brpRouteWidget.prototype.routeChanged = function(){
	this.renderItinerary();
}

brpRouteWidget.prototype.renderItinerary = function(){

    function textLink(sClass, text){
		return '<a class="'+sClass+'" href="javascript:void(0);">' + text + '</a>'
	}

	function imageLink(sClass, src, alt){
		return '<a class="%0" href="javascript:void(0);">'.format(sClass)
      + '<img class="%0" src="%1" alt="%2" width="24" height="24" />'.format(sClass, src, alt)
      + '</a>';
	}
    function addJuntion(loc ,cnt){
        var jRow = $('<li></li>').click(me.createLocRowClickHandler(cnt));
        jRow.attr('idx',cnt);
        
        var oLeftDiv = $('<div class="pointleft"></div');
        $(me.crtListIconTag(cnt, loc))
           .addClass('locicon mappoint handle')
           .appendTo($('<a href="javascript:void(0);"></a>'))
           .appendTo($('<span class="icon"></span>'))
           .appendTo(oLeftDiv);       
        if (loc['name'] == 'nn')
           oLeftDiv.append(textLink('locname', ''));
        else
           oLeftDiv.append(textLink('locname', loc['name']));
        jRow.append(oLeftDiv);
        
        var oRightDiv = $('<div class="pointright"></div');
        var time1 = Math.round(loc.distance / 17 * 60);
        oRightDiv.append('<span class="lockm">'   + loc.distance + '</span>');
        oRightDiv.append('<span class="loctime">' + time1 + '</span>');
        oRightDiv.append('<span class="button">'  + imageLink('locdelete',   $('body').data('sUiImageDirUrl')+'/mappoint-delete.png', 'Verwijder') + '</span>');
        jRow.append(oRightDiv);

        jRow.append('<div class="clearfix">&nbsp;</div>');

        $('ul.locationlist', this.container).append(jRow);

    
    }
	var me = this, linenr = 1;
    var jCnt=0;

	var header = $('<div class="pointright" style="width:102px;"><span class="lockm">km.</span><span class="loctime">min.</span><span class="lockm">&nbsp;</span></div>');
    $('#locationheader', this.container).html(header);	             

    $('.locationlist', this.container).empty();

	$('.itinerarylist', this.container).empty();

	if (this.route){
	
		$(this.route.sections).each(function(){
		    
		    //render junctionlist
		    
		    addJuntion(this.start ,jCnt)
            if (jCnt==0)
              $('#routestartpoint').html(this.start['name']);		    
		    jCnt++;
		    //end junctionlist
			
			var row = $('<li></li>');
			row.append('<div class="distance">' + this.start.distance + ' km</div>');
			row.append('<div class="icon">' + me.crtListIconTag(linenr, this.start) + '</div>');
			row.append('<div class="text">' + this.start.advice + '</div>');
			
			
			$('ul.itinerarylist', this.container).append(row);	
			linenr++;
		
			$(this.description).each(function(){
				var row = $('<li></li>');
				row.append('<div class="distance">' + this.distance + ' km</div>');
				row.append('<div class="icon">' + me.crtListIconTag(linenr, this) + '</div>');
				row.append('<div class="text">' + this.advice + '</div>');
				$('ul.itinerarylist', this.container).append(row);	
				linenr++;
			});
		});
		
		var row = $('<li></li>'), lst = this.route.sections[this.route.sections.length - 1];
		row.append('<div class="distance">' + lst.destination.distance + ' km</div>');
		row.append('<div class="icon">' + me.crtListIconTag(linenr, lst.destination) + '</div>');
		row.append('<div class="text">' + lst.destination.advice + '</div>');
		$('ul.itinerarylist', this.container).append(row);

        //render last location
 	    addJuntion(lst.destination ,jCnt)
        $('#routedestination').html(lst.destination['name']);
		//end last location			
	}
	else {
	    if (this.locations[0])
	       addJuntion(this.locations[0],0); 
	}
	
	if (this.onLocationsChanged) this.onLocationsChanged(this.locations);
	if (this.onRouteChanged) this.onRouteChanged(this.route);
}


brpRouteWidget.prototype.renderForPrint = function(){


   function crtListIconUrl(idx, loc){
	    var sIconNr = (loc.iconnr ? loc.iconnr.toLength(2) : '00');
	    var imgUrl;
	    if (idx == 0) 
	        imgUrl = 'start';
	    else if (idx == -1)  
	        imgUrl = 'end';  
	    else
	        imgUrl = 'this';
    	    
	    if (loc.category == BRP_CAT_JUNCTIONS) {
		    return imgUrl+'junction%0.png'.format(sIconNr);
        }
	    if (loc.category == BRP_CAT_ADDRESS) {
	       if (idx ==0)  
	         return  'startpuntjunction.png';
	       else if (idx == -1)
	               return 'starteindpunt.png'; 
	            else   
		           return 'tussenpunt.png';
	    }
	    if (loc.category){
		    var icn = (brpCategories[loc.category] || {})['listIcon'];		
		    if (icn) {
                var c = loc.category || '00';
                imgUrl += 'poi%0.png'.format(c.toLength(2));
                imgUrl = imgUrl.replace('this','');
                return imgUrl;
            }
	    }
	    if (loc.advicecode) {
		    if (loc.advicecode == 'ToBicycleJunction')
			    return  'thisjunction%0.png'.format(sIconNr );
		    if (loc.advicecode == 'UserLocation')
			    return '%0.png'.format(sIconNr );
		    return '%0.png'.format(loc.advicecode.toLowerCase());
	    }
	    return ''
    }

    function addRow(dist,icn,adv) {
        var me = this;
        me.distance = dist;
        me.icn = icn;
        me.adv = adv;
    }



	var me = this, linenr = 0;
    var rows = [];
	if (this.route){
	
		$(this.route.sections).each(function(){
		    
			rows.push( new addRow(this.start.distance, crtListIconUrl(linenr, this.start),this.start.advice));
			linenr++;
		
			$(this.description).each(function(){
                rows.push( new addRow(this.distance, crtListIconUrl(linenr, this),this.advice));
				linenr++;
			});
		});
		
		var lst = this.route.sections[this.route.sections.length - 1];
		rows.push( new addRow(lst.destination.distance, crtListIconUrl(-1,lst.destination),lst.destination.advice));
	}
	return rows;
}

brpRouteWidget.serializeAddLoc = function(p, loc){
	if (loc.category == BRP_CAT_ADDRESS){
		p.push('p');
		p.push(loc.x);
		p.push(',');
		p.push(loc.y)
	} else {
		if (loc.category == BRP_CAT_JUNCTIONS)
			p.push('j');
		else
			p.push('u');
		p.push(loc.id)
	}
}
brpRouteWidget.prototype.serializeLocationsUrl = function(a){
	var p = [], len = this.locations.length;
	for (var i = 0; i < len; i++) brpRouteWidget.serializeAddLoc(p, this.locations[i]);
	if (this.locations[len-1] != this.locations[0] && $('input:checkbox.roundtrip', this.container).is(':checked'))
		brpRouteWidget.serializeAddLoc(p, this.locations[0])
	a.p = p.join('');
	return a
}

brpRouteWidget.prototype.serializeRoute = function(){
	var line = 0;
	var s = '';
	if (this.route){
		$(this.route.sections).each(function(){
			$(this.description).each(function(){
				if (line>0) s += '|';
				s += this.distance + '|';
				s += this.advice + '|';
				s += this.advicecode + '|';
				s += this.x + '|';
				s += this.y + '|';
				s += this.icon;
				line++;
			});
		});
	}
	return s;
}

brpRouteWidget.prototype.printRoute = function() {
    if((this.locations) && (this.locations.length>1)) {
        if (($('#routename-name').val() !='')&&($('#routename-name').val() != $('#routename-name').data('defaultVal'))) {
    this.routeName = $('#routename-name').val();
          $('#routename').val(this.routeName);
          $('#routenametitle').html(this.routeName);
          $('#routenametitle2').html(this.routeName);
        }
	window.open(this.opts.printPageUrl);
	}
	else
	    alert('Maak of selecteer eerst een route.');
}
//Map function
brpRouteWidget.prototype.showMap = function() {  
    //show the map 
  	$('div#route_list').hide();
	$('div#route_detail').hide();
	$('div#map').show();
}

//SideBar Functions
brpRouteWidget.prototype.SetBar = function(n) {  
    function MakeHidden(p) {
         $('#step'+p+'_head').removeClass('active');
         $('#step'+p+'_content').hide();
         if (p != 4)
         {
         	$("#productContainer").hide();
         	$("#routeplanner_overlay").hide();
         }
    }
    if (n != 1) MakeHidden(1);
    if (n != 2) MakeHidden(2);
    if (n != 3) MakeHidden(3);
    if (n != 4) MakeHidden(4);
    if (n != 5) MakeHidden(5);
    
    $('#step'+n+'_head').addClass('active');
    $('#step'+n+'_content').show();
    



        

        
}

brpRouteWidget.prototype.SetPoi = function(n) {
    function MakeHidden1(p) {
         $('#poi'+p+'_head').removeClass('active');
         $('#poi'+p+'_content').hide();
    }
    if (n != 1) MakeHidden1(1);
    if (n != 2) MakeHidden1(2);
    if (n != 3) MakeHidden1(3);
    $('#poi'+n+'_head').addClass('active');
    $('#poi'+n+'_content').show();
}

brpRouteWidget.prototype.SetRouteBar = function(n) {
    function MakeHidden1(p) {
         $('#route'+p+'_head').removeClass('active');
         $('#route'+p+'_content').hide();
    }
    if (n != 1) MakeHidden1(1);
    if (n != 2) MakeHidden1(2);
    $('#route'+n+'_head').addClass('active');
    $('#route'+n+'_content').show();
}

brpRouteWidget.prototype.NewRoute = function() {
	this.clearLocations();
	$('#step1_manual').hide();
	
	$('#routenametitle').html('Uw eigen fietsroute');
  $('#routenametitle2').html('Uw geselecteerde fietsroute');
  
  $('#routename').val('Geef hier uw fietsroute een eigen naam');
  $('#routestartpoint').html('Klik in de kaart om een route te maken');
  $('.routedisttime').html('');
  $('#routedestination').html('');
  
	if ('' != getHttpParam('toname') ||  '' != getHttpParam('sendername'))
  {
  	$('#splash').show();
  }
}

brpRouteWidget.prototype.planAB = function(startP,endP) {
    this.clearLocations();
    this.addLocation(startP);
    this.addLocation(endP);
}


brpRouteWidget.prototype.allCoords = function(){

	if (this.route){
		var coords = new Array();
		$(this.route.sections).each(function(){
			$(this.coordinates).each(function(){
				coords.push(this);
			});
		});
		return coords;
	}
}





//Webshop Functions

brpRouteWidget.prototype.CenterPointRoute = function(me)
{
	var iTopX 		= 0;
	var iTopY 		= 0;
	var iBottomX 	= 0;
	var iBottomY 	= 0;
	var iCentralX = 0;
	var iCentralY	= 0; 
	if ('undefined' != typeof(me.locations[0]) )
	{
		iTopX 		= me.locations[0].x;
		iTopY 		= me.locations[0].y;
		iBottomX 	= me.locations[0].x;
		iBottomY 	= me.locations[0].y;
		iCentralX = me.locations[0].x;
		iCentralY	= me.locations[0].y; 
	}
	
	//calculate topleft and bottomright coordinates from route locations
	for (var n=0; n<me.locations.length; n++)
	{
		var loc = me.locations[n];
		
	  iTopX = Math.min(iTopX, loc.x);
	  iTopY = Math.min(iTopY, loc.y);
	  
	  iBottomX = Math.max(iBottomX, loc.x);
	  iBottomY = Math.max(iBottomY, loc.y);
	}
	
	var iCentralX = ((iBottomX - iTopX) / 2) + iTopX;
	var iCentralY = ((iBottomY - iTopY) / 2) + iTopY;
	
	var aResult = [];
	aResult['centerX'] = iCentralX;
	aResult['centerY'] = iCentralY;
	aResult['topX'] = iTopX;
	aResult['topY'] = iTopY;
	aResult['bottomX'] = iBottomX;
	aResult['bottomY'] = iBottomY;
	return aResult;
}

brpRouteWidget.prototype.ShowWebshopProduct = function(me, pagetype)
{
	$("#productcontainer").show();
	$("#routeplanner_overlay").show();
    $('#closeProductBlock').click(function(event){me.HideWebshopProduct();});
    $('#closeProductBlock img').attr('src','images/offer-close.png');
}
brpRouteWidget.prototype.HideWebshopProduct = function()
{
    if (this.WebShopAllowed)
    {
	$("#routeplanner_overlay").hide();
	$("#productcontainer").hide();
	}
}

brpRouteWidget.prototype.ShowWebshopProductLink = function(me)
{
	var aCenterPoints = [];
	aCenterPoints = me.CenterPointRoute(me);
	
	var iCentralX = aCenterPoints['centerX'];
	var iCentralY = aCenterPoints['centerY'];
	
	var url = "http://www.falk.nl/proxy.php?url=http%3A%2F%2Fwww.falk.nl%2Frouteplannerproduct.php%3Froutecx%3D"+iCentralX+"%26routecy%3D"+iCentralY+"%26type%3Dlink";
	
	$.getJSON('http://webwinkel.falk.nl/routeplannerproduct.php', {'routecx':iCentralX,'routecy':iCentralY}, function(data) { 
	    $(".sendtomyfriendproductlink").html(data);
	});
	/*$.get(url, {routecx:iCentralX, routecy:iCentralY, type:"link"}, function(data)
	{	
		$(".sendtomyfriendproductlink").html(data);
	});*/
}
