

function SubmitForm(formName, action) {    
    $.blockUI({message: $('#pleasewait')});
    // disabled fields do not get posted, so quickly enable them
    //$('[disabled="disabled"]').removeAttr('disabled'); 
    var form = document.getElementById(formName);    
    //form.innerHTML = form.innerHTML + "<input type=hidden name=next value='" + action +"'>";
    form.next.value = action;
    form.submit(); 
}

function SubmitFormSimple(formName) {
    $.blockUI({message: $('#pleasewait')});
    // disabled fields do not get posted, so quickly enable them
    //$('[disabled="disabled"]').removeAttr('disabled');
    var form = document.getElementById(formName);    
    form.submit();
}

function Buy() {
    var form = document.getElementById('ogoneform');  
    form.submit(); 
}

function loadPicture(checked, id, selector, lang) {
    if (checked) {
        $.getJSON('/' + lang + '/planner/input/picture/cityid/' + id,
            function(data) {
                $("#picture > img")[0].src = data.url;
                $("#picture > img")[0].alt = data.alt;
                var element = $("#picture > img");
                $("#picture > p.legend").text(data.alt);
                $("#cityReadDescription").text(data.cityReadDescription);
                $("#cityReadLink").attr("href", data.cityReadUrl);
                $("#cityReadLink").text(data.cityReadLinkText);
            });
    }
}

// when the from datepicker changes its value, the to datepicker should be changed:
// 1. the to datepicker should receive the value of the from datepicker
// 2. the to datepicker's minDate should be this value
// 3. the to datepicker's maxDate should be this value + 7 
function setToDate() {
    var fromdp = $("#from");
    var selectedDate = $("#from")[0].value;
    var todp = $("#to").data("datepicker");
    todp.input[0].value = selectedDate;
    var date = $.datepicker.parseDate(todp.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, todp.settings);
    $("#to").datepicker( "option", "minDate", date );
    var nextWeek = new Date(date.getTime() + 7 * 24 * 60 * 60 * 1000);
    $("#to").datepicker( "option", "maxDate", nextWeek);
}

function handleEnter() {    
    // get the nextButton element
    var nextButton = document.getElementById('nextButton');
    // follow the link after it
    window.location=nextButton.href;
}

function recordEvent(category, action, value)
{
    try{
        if(value == undefined)
        {
            _gaq.push(['_trackEvent', category, action]);
        }
        else
        {
            _gaq.push(['_trackEvent', category, action, value]);
        }
        
    }catch(e){}
}

function recordOutboundLink(link, trackpath, opennew) {
  try {
    _gaq.push(['_trackPageview', trackpath]);
        
  }catch(err){}

}

function logout(link) {
    FB.Connect.logoutAndRedirect(link.href);
}

function micropayment(trackPageViewName, lang, tripid, payboxid, countrycode) {    
    _gaq.push(['_trackPageview', '/micropayment/request']);
    var mollievars = 'id=' + payboxid + '&parameter[1]=' + tripid;
    // TODO Voeg eventueel de variabele 'land' toe (31 = Nederland, 32 = België) om het scherm met landkeuze over te slaan (bijvoorbeeld 'land=32');
    /*if (countrycode == '31' || countrycode == '32') {
        mollievars = mollievars + '&land=' + countrycode;
    }*/
    mbetaal(mollievars);
    // check every 5 seconds if the trip is paid...
    checkpayment(trackPageViewName, lang, tripid);
}

function checkpayment(trackPageViewName, lang, tripid) {
    $.ajax({url: '/en/planner/trip/checkpayment/trip/' + tripid,
        cache: false,
        success: function(data) { 
		var res = eval("(" + data + ")");
                if (res.bought == 'true') {                    
                    unlock();
                    _gaq.push(['_trackPageview', trackPageViewName + '/micropayment/success']);
                }
		else {
                    // reschedule checkpayment in one seconds
                    var methodName = 'checkpayment(\'' + trackPageViewName + '\', \'' + lang + '\', ' + tripid + ')';
                    window.setTimeout(methodName, 1000); 
                }
		
		
	    } 
    });
}

function print(trackPageViewName, lang, id, messageSelector) {
    //$.blockUI({ message: $(messageSelector) });
    _gaq.push(['_trackPageview', '/download/request']);
    location.href = '/' + lang + '/planner/trip/print';
    /*$.ajax({ url: '/' + lang + '/planner/trip/print', 
	    success: function(data) { 
			$.unblockUI(); 
			var res = eval("(" + data + ")"); 					        
			_gaq.push(['_trackPageview', trackPageViewName + '/download/success']);
			location.href = res.url; 
		    } 
	});*/
}

function unlock() {
    $('#paymentrequest').hide();
    $('#paymentlink').hide();
    // enable the boxes
    $('[disabled]').removeAttr('disabled');
    // remove locks
    $('.locked').removeClass('locked');
    $('#requestMessage').hide();
    $('#failureMessage').hide();
    $('#thankYou').show();
    if ($('#reload').length>0) {
        // if there is a reload div, reload the page (printout)
        $('#reload').show();
        location.reload(true);
    }
}

function checkPromoCode(lang) {
    var code = $('#promoCode').val();
    _gaq.push(['_trackPageview', '/promocode/check']);
    $.ajax({url: '/'+ lang +'/planner/trip/checkpromocode/code/' + code, 
        cache: false,
        success: function(data) { 
		var res = eval("(" + data + ")");
                if (res.bought == 'true') {                    
                    unlock();
                    _gaq.push(['_trackPageview', '/promocode/success']);
                }
		else {
                    _gaq.push(['_trackPageview', '/promocode/failure']);
                    $('#failureReason').text(res.failurereason);
                    $('#failureMessage').show();
                }			
	    } 
    });
}

function sort(dropdownId) {
    $.blockUI({ message: $('#pleasewait') });
    var selected = $("[id=\'" + dropdownId + "\']").val();
    window.location=selected;
}


function addToCart(poiid, poiname) {
    
    // 1 animatie
    var position = ($("[id=\'cartlist\']").offset());
    var position2 = ($("[id=\'block\']").offset());
    $("[id=\'block\']").animate({top:-((position2.top - position.top)-25),left:-(position2.left-position.left)}, 1000 ).fadeOut();
    $("[id=\'test\']").hide();
    
    // 2 naam toevoegen aan de list (js)
    var ul = document.getElementById('cartlist');
    var newli = document.createElement('li');
    newli.setAttribute('id',poiid);
    newli.innerHTML = poiname + '<a href=\'#\' onclick=\'removeFromCart(' + poiid + ')\'><img src="/images/icons/icon_trashcan.gif" /></a>';
    ul.appendChild(newli);

    // 3 ajax url aanroepen met poiid
    $.ajax({url: '/en/ajax/addtocart/poiid/' + poiid + '/poiname/' + poiname,
        cache: false,
        success: function(data) {
		
	    }
    });
}

function removeFromCart(poiid){

    // 1 verwijder uit de lijst
    var oldli = document.getElementById(poiid);
    var ul = oldli.parentNode;
    ul.removeChild(oldli);

    // 2 ajax url aanroepen met poiid
    $.ajax({url: '/en/ajax/removefromcart/poiid/' + poiid,
        cache: false,
        success: function(data) {

	    }
    });
}

function toggleNumberOfDays(){
    var selectedDays = $("[id=\'days\']").val();
    if(selectedDays == 1){
        $("[id=\'aankomst']").show();
        $("[id=\'aankomst-label']").show();
        $("[id=\'hotel']").hide();
        $("[id=\'hotel-label']").hide();
    }
    else if(selectedDays == ''){
        $("[id=\'aankomst']").hide();
        $("[id=\'aankomst-label']").hide();
        $("[id=\'hotel']").hide();
        $("[id=\'hotel-label']").hide();
    }
    else{
        $("[id=\'hotel']").show();
        $("[id=\'hotel-label']").show();
        $("[id=\'aankomst']").hide();
        $("[id=\'aankomst-label']").hide();
    }
}

function toggleCityMenu(){

    $("[id=\'citySelectBox']").show();
}

function toggleTripPlanMap(){

    $("[id=\'"+openMapPoi+"inner']").appendTo("[class=\'bd clearfix']");
    $("[id=\'dayPlannerList']").hide();
    $("[id=\'mapHolder']").show();
    $("[id=\'listbutton\']").removeClass('button icon iconList selected');
    $("[id=\'listbutton\']").addClass('button icon iconList');
    $("[id=\'mapbutton\']").addClass('button icon iconMap selected');
}

function toggleTripPlanList(){

    $("[id=\'"+openListPoi+"inner']").appendTo("[id=\'"+openListPoi+"append']");
    $("[id=\'dayPlannerList']").show();
    $("[id=\'mapHolder']").hide();
    $("[id=\'listbutton\']").addClass('button icon iconList selected');
    $("[id=\'mapbutton\']").removeClass('button icon iconMap selected');
    $("[id=\'mapbutton\']").addClass('button icon iconMap');
}

function toggleTripPlanTripDetail(id){

    openListPoi = id;
    $("[id=\'"+id+"inner']").appendTo("[id=\'"+id+"append']");
    $(".selectedTrip").hide();
    $(".selectedTripshort").show().removeClass('selectedTripshort');

    $(".selectedWalk").hide();
    $(".selectedWalkshort").show().removeClass('selectedWalkshort');

    $("[id=\'"+id+"short']").hide();
    $("[id=\'"+id+"long']").show();
    $("[id=\'"+id+"short']").addClass('selectedTripshort');
    $("[id=\'"+id+"long']").addClass('selectedTrip');
    
}

function toggleTripPlanWalkDetail(id){

    openListPoi = id;
    $("[id=\'"+id+"inner']").appendTo("[id=\'"+id+"append']");
    $(".selectedWalk").hide();
    $(".selectedWalkshort").show().removeClass('selectedWalkshort');

    $("[id=\'"+id+"short']").hide();
    $("[id=\'"+id+"long']").show();
    $("[id=\'"+id+"short']").addClass('selectedWalkshort');
    $("[id=\'"+id+"long']").addClass('selectedWalk');
    
}

function setVisibleMap(tripid){

    $("[id=\'"+tripid+"a0']").show();
}

function toggleMapViewNext(id,nextid){

    
    $("[id=\'"+id+"']").hide();
    $("[id=\'"+id+"inner']").appendTo("[id=\'"+id+"append']");
    $("[id=\'"+nextid+"']").show();

    $("[id=\'"+nextid+"inner']").appendTo("[class=\'bd clearfix']");
    
    openMapPoi = nextid;
    previousMarker = nextid;
}

function toggleMapViewPrevious(id,previousid){

    $("[id=\'"+id+"']").hide();
    $("[id=\'"+id+"inner']").appendTo("[id=\'"+id+"append']");
    $("[id=\'"+previousid+"']").show();

    $("[id=\'"+previousid+"inner']").appendTo("[class=\'bd clearfix']");

    openMapPoi = previousid;
    previousMarker = previousid;
}


function loadDayOfTrip(dayid){

    $("[id=\'"+openMapPoi+"inner']").appendTo("[class=\'bd clearfix']");
    $("[id=\'"+openListPoi+"inner']").appendTo("[id=\'"+openListPoi+"append']");

    $("[id=\'day"+previousDay+"']").hide();
    $("[id=\'day"+dayid+"']").show();
    $("[id=\'day"+dayid+"']").addClass('selected');

    previousDay= dayid;

    var markersArray = new Array();

    for(i=1;i<=trip['tripDays'][dayid]['activities'].length;i++){

        if(trip['tripDays'][dayid]['activities'][i-1]['type'] == 'visit'){
                markerObject = new Object();
                markerObject.uniqueid = trip['tripDays'][dayid]['activities'][i-1]['uniqueid'];
                markerObject.lat = trip['tripDays'][dayid]['activities'][i-1]['lat'];
                markerObject.lon = trip['tripDays'][dayid]['activities'][i-1]['lon'];
                markerObject.name= trip['tripDays'][dayid]['activities'][i-1]['name'];
                markerObject.icon = '/images/icons/marker_selected.gif';
                markersArray.push(markerObject );
            }
            else if(trip['tripDays'][dayid]['activities'][i-1]['type'] == 'start'){
                markerObject = new Object();
                markerObject.uniqueid = trip['tripDays'][dayid]['activities'][i-1]['uniqueid'];
                markerObject.lat = trip['tripDays'][dayid]['activities'][i-1]['lat'];
                markerObject.lon = trip['tripDays'][dayid]['activities'][i-1]['lon'];
                markerObject.name= trip['tripDays'][dayid]['activities'][i-1]['name'];
                markerObject.icon = '/images/icons/marker_selected.gif';
                markersArray.push(markerObject );
            }
            else if(trip['tripDays'][dayid]['activities'][i-1]['type'] == 'end'){
                markerObject = new Object();
                markerObject.uniqueid = trip['tripDays'][dayid]['activities'][i-1]['uniqueid'];
                markerObject.lat = trip['tripDays'][dayid]['activities'][i-1]['lat'];
                markerObject.lon = trip['tripDays'][dayid]['activities'][i-1]['lon'];
                markerObject.name= trip['tripDays'][dayid]['activities'][i-1]['name'];
                markerObject.icon = '/images/icons/marker_selected.gif';
                markersArray.push(markerObject );
            }
            else if(trip['tripDays'][dayid]['activities'][i-1]['type'] == 'walk'){
                for(y=1;y<=trip['tripDays'][dayid]['activities'][i-1]['activities'].length;y++){
                    markerObject = new Object();
                    markerObject.uniqueid = trip['tripDays'][dayid]['activities'][i-1]['activities'][y-1]['uniqueid'];
                    markerObject.lat = trip['tripDays'][dayid]['activities'][i-1]['activities'][y-1]['lat'];
                    markerObject.lon = trip['tripDays'][dayid]['activities'][i-1]['activities'][y-1]['lon'];
                    markerObject.name= trip['tripDays'][dayid]['activities'][i-1]['activities'][y-1]['name'];
                    markerObject.icon = '/images/icons/marker_selected.gif';
                    markersArray.push(markerObject );
                }
            }
    }
    
    var infowindow = new google.maps.InfoWindow(); 

    var marker, i,request;

    var directionsDisplay = new google.maps.DirectionsRenderer();
    var directionsService = new google.maps.DirectionsService();
    directionsDisplay.setMap(map);

    for(i=1;i<markersArray.length;i++){

        var lat = markersArray[i-1]['lat'];
        var lon = markersArray[i-1]['lon'];

        marker = new google.maps.Marker({position: new google.maps.LatLng(lat,lon), title:markersArray[i-1]['name'],        map: map,       icon:markersArray[i-1]['icon']});

        request = {
           origin: new google.maps.LatLng(markersArray[i-1]['lat'],markersArray[i-1]['lon']),
           destination: new google.maps.LatLng(markersArray[i]['lat'],markersArray[i]['lon']),
           travelMode: google.maps.DirectionsTravelMode.WALKING
         };

        var polylineArray = new Array();

        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                
                var path = response.routes[0].overview_path.length;

                for(n=0;n<path;n++){
                    polylineArray.push(new google.maps.LatLng(response.routes[0].overview_path[n].Ca,response.routes[0].overview_path[n].Ea));
                }
        }

        var flightPath = new google.maps.Polyline({
            path: polylineArray,
            strokeColor: "#212BEA",
            strokeOpacity: 0.5,
            strokeWeight: 3
        });

        flightPath.setMap(map);
            
        });

        map.setCenter(new google.maps.LatLng(markersArray[0]['lat'],markersArray[0]['lon']));

        google.maps.event.addListener(marker, 'click', (function(marker, i) {return function() {infowindow.setContent(markersArray[i-1]['name']);infowindow.open(map, marker)}})(marker, i));
        google.maps.event.addListener(marker, 'click', (function(marker, i) {return function() {toggleMapViewNext(previousMarker,markersArray[i-1]['uniqueid']);previousMarker = markersArray[i-1]['uniqueid'];}})(marker, i));
    }
}

function initialize() {
    
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    
    var myOptions = {
        zoom: 14,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map"),         myOptions);
}

function checkChangesVisisble(){

    if(numberOfChanges == 0){

        $("[id=\'changes']").hide();
    }else{

        $("[id=\'changes']").show();
    }
}

function changeDuration(id){

    var countList = 0;
    var index;
    
    if(changes.length>0){
        for(i=0;i<changes.length;i++){
            if(changes[i]['id']== id){
                countList++;
                index = [i];
                
            }
        }
        
        if(countList>0){
            changes.splice([index], 1);
            changeObject = new Object();
            changeObject.type = 'duration';
            changeObject.id = id;
            changeObject.value = $("[id=\'"+id+"']").val();
            numberOfChanges++;
            changes.push(changeObject);

            removeChange(id);
            checkChangesVisisble();
            addChange();
        }
        else{
            changeObject = new Object();
            changeObject.type = 'duration';
            changeObject.id = id;
            changeObject.value = $("[id=\'"+id+"']").val();
            numberOfChanges++;
            changes.push(changeObject);

            checkChangesVisisble();
            addChange();
        }
    }
    else{
        changeObject = new Object();
        changeObject.type = 'duration';
        changeObject.id = id;
        changeObject.value = $("[id=\'"+id+"']").val();
        numberOfChanges++;
        changes.push(changeObject);

        checkChangesVisisble();
        addChange();
    }
}

function changeDate(){

    var countList = 0;
    var index;

    if(changes.length>0){
        for(i=0;i<changes.length;i++){
            if(changes[i]['id']== 'startDate'){
                countList++;
                index = [i];
            }
        }

        if(countList>0){
            changes.splice([index], 1);
            changeObject = new Object();
            changeObject.type = 'date';
            changeObject.id = 'startDate';
            changeObject.value = $("[id=\'selectStartDay']").val();
            numberOfChanges++;
            changes.push(changeObject);

            removeChange('startDate');
            checkChangesVisisble();
            addChange();
        }
        else{
            changeObject = new Object();
            changeObject.type = 'date';
            changeObject.id = 'startDate';
            changeObject.value = $("[id=\'selectStartDay']").val();
            numberOfChanges++;
            changes.push(changeObject);

            checkChangesVisisble();
            addChange();
        }
    }
    else{
        changeObject = new Object();
        changeObject.type = 'date';
        changeObject.id = 'startDate';
        changeObject.value = $("[id=\'selectStartDay']").val();
        numberOfChanges++;
        changes.push(changeObject);

        checkChangesVisisble();
        addChange();
    }
}

function changeStartHoure(){

    var countList = 0;
    var index;

    if(changes.length>0){
        for(i=0;i<changes.length;i++){
            if(changes[i]['id']== 'startHoure'){
                countList++;
                index = [i];
            }
        }

        if(countList>0){
            changes.splice([index], 1);
            changeObject = new Object();
            changeObject.type = 'houre';
            changeObject.id = 'startHoure';
            changeObject.value = $("[id=\'startHoure']").val() +':' +$("[id=\'startMin']").val();
            numberOfChanges++;
            changes.push(changeObject);

            removeChange('startHoure');
            checkChangesVisisble();
            addChange();
        }
        else{
            changeObject = new Object();
            changeObject.type = 'houre';
            changeObject.id = 'startHoure';
            changeObject.value = $("[id=\'startHoure']").val() +':' +$("[id=\'startMin']").val();
            numberOfChanges++;
            changes.push(changeObject);

            checkChangesVisisble();
            addChange();
        }
    }
    else{
        changeObject = new Object();
        changeObject.type = 'houre';
        changeObject.id = 'startHoure';
        changeObject.value = $("[id=\'startHoure']").val() +':' +$("[id=\'startMin']").val();
        numberOfChanges++;
        changes.push(changeObject);

        checkChangesVisisble();
        addChange();
    }
}

function changeEndHoure(){

    var countList = 0;
    var index;

    if(changes.length>0){
        for(i=0;i<changes.length;i++){
            if(changes[i]['id']== 'endHoure'){
                countList++;
                index = [i];
            }
        }

        if(countList>0){
            changes.splice([index], 1);
            changeObject = new Object();
            changeObject.type = 'houre';
            changeObject.id = 'endHoure';
            changeObject.value = $("[id=\'endHoure']").val() +':' +$("[id=\'endMin']").val();
            numberOfChanges++;
            changes.push(changeObject);

            removeChange('endHoure');
            checkChangesVisisble();
            addChange();
        }
        else{
            changeObject = new Object();
            changeObject.type = 'houre';
            changeObject.id = 'endHoure';
            changeObject.value = $("[id=\'endHoure']").val() +':' +$("[id=\'endMin']").val();
            numberOfChanges++;
            changes.push(changeObject);

            checkChangesVisisble();
            addChange();
        }
    }
    else{
        changeObject = new Object();
        changeObject.type = 'houre';
        changeObject.id = 'endHoure';
        changeObject.value = $("[id=\'endHoure']").val() +':' +$("[id=\'endMin']").val();
        numberOfChanges++;
        changes.push(changeObject);

        checkChangesVisisble();
        addChange();
    }
}

function addChange(){

    var list = document.getElementById('changelist');

        if ( list.hasChildNodes() )
        {
            while ( list.childNodes.length >= 1 )
            {
                list.removeChild( list.firstChild );
            }
        }

    for(i=0;i<changes.length;i++){

        if(changes[i]['id'] == 'startDate'){

            var trfield = document.createElement('tr');
            trfield.setAttribute('id',changes[i]['id']+'change');

            list.appendChild(trfield);

            var tdfield = document.createElement('td');
            trfield.appendChild(tdfield);

            var bfield = document.createElement('b');
            tdfield.appendChild(bfield);
            bfield.appendChild(document.createTextNode(changes[i]['value']+' '+changes[i]['id']+' StartDag'));

        }
        else{
            var trfield = document.createElement('tr');
            trfield.setAttribute('id',changes[i]['id']+'change');

            list.appendChild(trfield);

            var tdfield = document.createElement('td');
            trfield.appendChild(tdfield);

            var bfield = document.createElement('b');
            tdfield.appendChild(bfield);
            bfield.appendChild(document.createTextNode(changes[i]['value']+' '+changes[i]['id']+' Bezoekduur'));
        }
    }
}

function removeChange(id){

    if(id == 'startDate'){
        var oldChange = document.getElementById('startDatechange');
        var changeList = oldChange.parentNode;
        changeList.removeChild(oldChange);
    }
    else{
        var oldChange = document.getElementById(id+'change');
        var changeList = oldChange.parentNode;
        changeList.removeChild(oldChange);
    }
}

function viewInList(id){

    toggleTripPlanList();
    toggleTripPlanTripDetail(id);
}

function toggleAddPeriod(){
    $("[id=\'addform']").show();
    $("[id=\'changeform']").hide();
}

function paymentStepTwo(){
    var country = ($("[id=\'location']").val());
    if(country == "BE" || country == "NL" || country == "FR" || country == "DE" || country == "GB"){
        window.location = "http://ctpdevelop.localhost/nl/payment/options/country/"+country;
    }
    else if(country == "Other"){
        $("[id=\'ogoneform']").submit();
    }
}

function paymentPhone(country){

    window.location = "http://ctpdevelop.localhost/nl/payment/paymentphone/country/"+country;
}

function paymentCard(){
    $("[id=\'ogoneform']").submit();
}

function showReport(type){
    
    if(type == 'days'){
        $("[id=\'tableDays']").show();
        $("[id=\'tableWeeks']").hide();
        $("[id=\'tableMonths']").hide();
        $("[id=\'chartDays']").show();
        $("[id=\'chartWeeks']").hide();
        $("[id=\'chartMonths']").hide();
    }
    else if(type == 'weeks'){
        $("[id=\'tableDays']").hide();
        $("[id=\'tableWeeks']").show();
        $("[id=\'tableMonths']").hide();
        $("[id=\'chartDays']").hide();
        $("[id=\'chartWeeks']").show();
        $("[id=\'chartMonths']").hide();
    }
    else if(type == 'months'){
        $("[id=\'tableDays']").hide();
        $("[id=\'tableWeeks']").hide();
        $("[id=\'tableMonths']").show();
        $("[id=\'chartDays']").hide();
        $("[id=\'chartWeeks']").hide();
        $("[id=\'chartMonths']").show();
    }
}


function SubmitForm(formName, action) {
    $.blockUI({message: $('#pleasewait')});
    // disabled fields do not get posted, so quickly enable them
    //$('[disabled="disabled"]').removeAttr('disabled'); 
    var form = document.getElementById(formName);    
    //form.innerHTML = form.innerHTML + "<input type=hidden name=next value='" + action +"'>";
    form.next.value = action;
    form.submit(); 
}

function SubmitFormSimple(formName) {
    $.blockUI({message: $('#pleasewait')});
    // disabled fields do not get posted, so quickly enable them
    //$('[disabled="disabled"]').removeAttr('disabled');
    var form = document.getElementById(formName);    
    form.submit();
}

function Buy() {
    var form = document.getElementById('ogoneform');  
    form.submit(); 
}

function loadPicture(checked, id, selector, lang) {
    if (checked) {
        $.getJSON('/' + lang + '/planner/input/picture/cityid/' + id,
            function(data) {
                $("#picture > img")[0].src = data.url;
                $("#picture > img")[0].alt = data.alt;
                var element = $("#picture > img");
                $("#picture > p.legend").text(data.alt);
                $("#cityReadDescription").text(data.cityReadDescription);
                $("#cityReadLink").attr("href", data.cityReadUrl);
                $("#cityReadLink").text(data.cityReadLinkText);
            });
    }
}

// when the from datepicker changes its value, the to datepicker should be changed:
// 1. the to datepicker should receive the value of the from datepicker
// 2. the to datepicker's minDate should be this value
// 3. the to datepicker's maxDate should be this value + 7 
function setToDate() {
    var fromdp = $("#from");
    var selectedDate = $("#from")[0].value;
    var todp = $("#to").data("datepicker");
    todp.input[0].value = selectedDate;
    var date = $.datepicker.parseDate(todp.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, todp.settings);
    $("#to").datepicker( "option", "minDate", date );
    var nextWeek = new Date(date.getTime() + 7 * 24 * 60 * 60 * 1000);
    $("#to").datepicker( "option", "maxDate", nextWeek);
}

function handleEnter() {    
    // get the nextButton element
    var nextButton = document.getElementById('nextButton');
    // follow the link after it
    window.location=nextButton.href;
}


function logout(link) {
    FB.Connect.logoutAndRedirect(link.href);
}

function micropayment(trackPageViewName, lang, tripid, payboxid, countrycode) {    
    _gaq.push(['_trackPageview', '/micropayment/request']);
    var mollievars = 'id=' + payboxid + '&parameter[1]=' + tripid;
    // TODO Voeg eventueel de variabele 'land' toe (31 = Nederland, 32 = België) om het scherm met landkeuze over te slaan (bijvoorbeeld 'land=32');
    /*if (countrycode == '31' || countrycode == '32') {
        mollievars = mollievars + '&land=' + countrycode;
    }*/
    mbetaal(mollievars);
    // check every 5 seconds if the trip is paid...
    checkpayment(trackPageViewName, lang, tripid);
}

function checkpayment(trackPageViewName, lang, tripid) {
    $.ajax({url: '/en/planner/trip/checkpayment/trip/' + tripid,
        cache: false,
        success: function(data) { 
		var res = eval("(" + data + ")");
                if (res.bought == 'true') {                    
                    unlock();
                    _gaq.push(['_trackPageview', trackPageViewName + '/micropayment/success']);
                }
		else {
                    // reschedule checkpayment in one seconds
                    var methodName = 'checkpayment(\'' + trackPageViewName + '\', \'' + lang + '\', ' + tripid + ')';
                    window.setTimeout(methodName, 1000); 
                }
		
		
	    } 
    });
}

function print(trackPageViewName, lang, id, messageSelector) {
    //$.blockUI({ message: $(messageSelector) });
    _gaq.push(['_trackPageview', '/download/request']);
    location.href = '/' + lang + '/planner/trip/print';
    /*$.ajax({ url: '/' + lang + '/planner/trip/print', 
	    success: function(data) { 
			$.unblockUI(); 
			var res = eval("(" + data + ")"); 					        
			_gaq.push(['_trackPageview', trackPageViewName + '/download/success']);
			location.href = res.url; 
		    } 
	});*/
}

function unlock() {
    $('#paymentrequest').hide();
    $('#paymentlink').hide();
    // enable the boxes
    $('[disabled]').removeAttr('disabled');
    // remove locks
    $('.locked').removeClass('locked');
    $('#requestMessage').hide();
    $('#failureMessage').hide();
    $('#thankYou').show();
    if ($('#reload').length>0) {
        // if there is a reload div, reload the page (printout)
        $('#reload').show();
        location.reload(true);
    }
}

function checkPromoCode(lang) {
    var code = $('#promoCode').val();
    _gaq.push(['_trackPageview', '/promocode/check']);
    $.ajax({url: '/'+ lang +'/planner/trip/checkpromocode/code/' + code, 
        cache: false,
        success: function(data) { 
		var res = eval("(" + data + ")");
                if (res.bought == 'true') {                    
                    unlock();
                    _gaq.push(['_trackPageview', '/promocode/success']);
                }
		else {
                    _gaq.push(['_trackPageview', '/promocode/failure']);
                    $('#failureReason').text(res.failurereason);
                    $('#failureMessage').show();
                }			
	    } 
    });
}

function sort(dropdownId) {
    $.blockUI({ message: $('#pleasewait') });
    var selected = $("[id=\'" + dropdownId + "\']").val();
    window.location=selected;
}


function addToCart(poiid, poiname) {
    
    // 1 animatie
    var position = ($("[id=\'cartlist\']").offset());
    var position2 = ($("[id=\'block\']").offset());
    $("[id=\'block\']").animate({top:-((position2.top - position.top)-25),left:-(position2.left-position.left)}, 1000 ).fadeOut();
    $("[id=\'test\']").hide();
    
    // 2 naam toevoegen aan de list (js)
    var ul = document.getElementById('cartlist');
    var newli = document.createElement('li');
    newli.setAttribute('id',poiid);
    newli.innerHTML = poiname + '<a href=\'#\' onclick=\'removeFromCart(' + poiid + ')\'><img src="/images/icons/icon_trashcan.gif" /></a>';
    ul.appendChild(newli);

    // 3 ajax url aanroepen met poiid
    $.ajax({url: '/en/ajax/addtocart/poiid/' + poiid + '/poiname/' + poiname,
        cache: false,
        success: function(data) {
		
	    }
    });
}

function removeFromCart(poiid){

    // 1 verwijder uit de lijst
    var oldli = document.getElementById(poiid);
    var ul = oldli.parentNode;
    ul.removeChild(oldli);

    // 2 ajax url aanroepen met poiid
    $.ajax({url: '/en/ajax/removefromcart/poiid/' + poiid,
        cache: false,
        success: function(data) {

	    }
    });
}

function toggleNumberOfDays(){
    var selectedDays = $("[id=\'days\']").val();
    if(selectedDays == 1){
        $("[id=\'aankomst']").show();
        $("[id=\'aankomst-label']").show();
        $("[id=\'hotel']").hide();
        $("[id=\'hotel-label']").hide();
    }
    else if(selectedDays == ''){
        $("[id=\'aankomst']").hide();
        $("[id=\'aankomst-label']").hide();
        $("[id=\'hotel']").hide();
        $("[id=\'hotel-label']").hide();
    }
    else{
        $("[id=\'hotel']").show();
        $("[id=\'hotel-label']").show();
        $("[id=\'aankomst']").hide();
        $("[id=\'aankomst-label']").hide();
    }
}

function toggleCityMenu(){

    $("[id=\'citySelectBox']").show();
}

function toggleTripPlanMap(){

    $("[id=\'"+openMapPoi+"inner']").appendTo("[class=\'bd clearfix']");
    $("[id=\'dayPlannerList']").hide();
    $("[id=\'mapHolder']").show();
    $("[id=\'listbutton\']").removeClass('button icon iconList selected');
    $("[id=\'listbutton\']").addClass('button icon iconList');
    $("[id=\'mapbutton\']").addClass('button icon iconMap selected');
}

function toggleTripPlanList(){

    $("[id=\'"+openListPoi+"inner']").appendTo("[id=\'"+openListPoi+"append']");
    $("[id=\'dayPlannerList']").show();
    $("[id=\'mapHolder']").hide();
    $("[id=\'listbutton\']").addClass('button icon iconList selected');
    $("[id=\'mapbutton\']").removeClass('button icon iconMap selected');
    $("[id=\'mapbutton\']").addClass('button icon iconMap');
}

function toggleTripPlanTripDetail(id){

    openListPoi = id;
    $("[id=\'"+id+"inner']").appendTo("[id=\'"+id+"append']");
    $(".selectedTrip").hide();
    $(".selectedTripshort").show().removeClass('selectedTripshort');

    $(".selectedWalk").hide();
    $(".selectedWalkshort").show().removeClass('selectedWalkshort');

    $("[id=\'"+id+"short']").hide();
    $("[id=\'"+id+"long']").show();
    $("[id=\'"+id+"short']").addClass('selectedTripshort');
    $("[id=\'"+id+"long']").addClass('selectedTrip');
    
}

function toggleTripPlanWalkDetail(id){

    openListPoi = id;
    $("[id=\'"+id+"inner']").appendTo("[id=\'"+id+"append']");
    $(".selectedWalk").hide();
    $(".selectedWalkshort").show().removeClass('selectedWalkshort');

    $("[id=\'"+id+"short']").hide();
    $("[id=\'"+id+"long']").show();
    $("[id=\'"+id+"short']").addClass('selectedWalkshort');
    $("[id=\'"+id+"long']").addClass('selectedWalk');
    
}

function setVisibleMap(tripid){

    $("[id=\'"+tripid+"a0']").show();
}

function toggleMapViewNext(id,nextid){

    
    $("[id=\'"+id+"']").hide();
    $("[id=\'"+id+"inner']").appendTo("[id=\'"+id+"append']");
    $("[id=\'"+nextid+"']").show();

    $("[id=\'"+nextid+"inner']").appendTo("[class=\'bd clearfix']");
    
    openMapPoi = nextid;
    previousMarker = nextid;
}

function toggleMapViewPrevious(id,previousid){

    $("[id=\'"+id+"']").hide();
    $("[id=\'"+id+"inner']").appendTo("[id=\'"+id+"append']");
    $("[id=\'"+previousid+"']").show();

    $("[id=\'"+previousid+"inner']").appendTo("[class=\'bd clearfix']");

    openMapPoi = previousid;
    previousMarker = previousid;
}


function loadDayOfTrip(dayid){

    $("[id=\'"+openMapPoi+"inner']").appendTo("[class=\'bd clearfix']");
    $("[id=\'"+openListPoi+"inner']").appendTo("[id=\'"+openListPoi+"append']");

    $("[id=\'day"+previousDay+"']").hide();
    $("[id=\'day"+dayid+"']").show();
    $("[id=\'day"+dayid+"']").addClass('selected');

    previousDay= dayid;

    var markersArray = new Array();

    for(i=1;i<=trip['tripDays'][dayid]['activities'].length;i++){

        if(trip['tripDays'][dayid]['activities'][i-1]['type'] == 'visit'){
                markerObject = new Object();
                markerObject.uniqueid = trip['tripDays'][dayid]['activities'][i-1]['uniqueid'];
                markerObject.lat = trip['tripDays'][dayid]['activities'][i-1]['lat'];
                markerObject.lon = trip['tripDays'][dayid]['activities'][i-1]['lon'];
                markerObject.name= trip['tripDays'][dayid]['activities'][i-1]['name'];
                markerObject.icon = '/images/icons/marker_selected.gif';
                markersArray.push(markerObject );
            }
            else if(trip['tripDays'][dayid]['activities'][i-1]['type'] == 'start'){
                markerObject = new Object();
                markerObject.uniqueid = trip['tripDays'][dayid]['activities'][i-1]['uniqueid'];
                markerObject.lat = trip['tripDays'][dayid]['activities'][i-1]['lat'];
                markerObject.lon = trip['tripDays'][dayid]['activities'][i-1]['lon'];
                markerObject.name= trip['tripDays'][dayid]['activities'][i-1]['name'];
                markerObject.icon = '/images/icons/marker_selected.gif';
                markersArray.push(markerObject );
            }
            else if(trip['tripDays'][dayid]['activities'][i-1]['type'] == 'end'){
                markerObject = new Object();
                markerObject.uniqueid = trip['tripDays'][dayid]['activities'][i-1]['uniqueid'];
                markerObject.lat = trip['tripDays'][dayid]['activities'][i-1]['lat'];
                markerObject.lon = trip['tripDays'][dayid]['activities'][i-1]['lon'];
                markerObject.name= trip['tripDays'][dayid]['activities'][i-1]['name'];
                markerObject.icon = '/images/icons/marker_selected.gif';
                markersArray.push(markerObject );
            }
            else if(trip['tripDays'][dayid]['activities'][i-1]['type'] == 'walk'){
                for(y=1;y<=trip['tripDays'][dayid]['activities'][i-1]['activities'].length;y++){
                    markerObject = new Object();
                    markerObject.uniqueid = trip['tripDays'][dayid]['activities'][i-1]['activities'][y-1]['uniqueid'];
                    markerObject.lat = trip['tripDays'][dayid]['activities'][i-1]['activities'][y-1]['lat'];
                    markerObject.lon = trip['tripDays'][dayid]['activities'][i-1]['activities'][y-1]['lon'];
                    markerObject.name= trip['tripDays'][dayid]['activities'][i-1]['activities'][y-1]['name'];
                    markerObject.icon = '/images/icons/marker_selected.gif';
                    markersArray.push(markerObject );
                }
            }
    }
    
    var infowindow = new google.maps.InfoWindow(); 

    var marker, i,request;

    var directionsDisplay = new google.maps.DirectionsRenderer();
    var directionsService = new google.maps.DirectionsService();
    directionsDisplay.setMap(map);

    for(i=1;i<markersArray.length;i++){

        var lat = markersArray[i-1]['lat'];
        var lon = markersArray[i-1]['lon'];

        marker = new google.maps.Marker({position: new google.maps.LatLng(lat,lon), title:markersArray[i-1]['name'],        map: map,       icon:markersArray[i-1]['icon']});

        request = {
           origin: new google.maps.LatLng(markersArray[i-1]['lat'],markersArray[i-1]['lon']),
           destination: new google.maps.LatLng(markersArray[i]['lat'],markersArray[i]['lon']),
           travelMode: google.maps.DirectionsTravelMode.WALKING
         };

        var polylineArray = new Array();

        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                
                var path = response.routes[0].overview_path.length;

                for(n=0;n<path;n++){
                    polylineArray.push(new google.maps.LatLng(response.routes[0].overview_path[n].Ca,response.routes[0].overview_path[n].Ea));
                }
        }

        var flightPath = new google.maps.Polyline({
            path: polylineArray,
            strokeColor: "#212BEA",
            strokeOpacity: 0.5,
            strokeWeight: 3
        });

        flightPath.setMap(map);
            
        });

        map.setCenter(new google.maps.LatLng(markersArray[0]['lat'],markersArray[0]['lon']));

        google.maps.event.addListener(marker, 'click', (function(marker, i) {return function() {infowindow.setContent(markersArray[i-1]['name']);infowindow.open(map, marker)}})(marker, i));
        google.maps.event.addListener(marker, 'click', (function(marker, i) {return function() {toggleMapViewNext(previousMarker,markersArray[i-1]['uniqueid']);previousMarker = markersArray[i-1]['uniqueid'];}})(marker, i));
    }
}

function initialize() {
    
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    
    var myOptions = {
        zoom: 14,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map"),         myOptions);
}

function checkChangesVisisble(){

    if(numberOfChanges == 0){

        $("[id=\'changes']").hide();
    }else{

        $("[id=\'changes']").show();
    }
}

function changeDuration(id){

    var countList = 0;
    var index;
    
    if(changes.length>0){
        for(i=0;i<changes.length;i++){
            if(changes[i]['id']== id){
                countList++;
                index = [i];
                
            }
        }
        
        if(countList>0){
            changes.splice([index], 1);
            changeObject = new Object();
            changeObject.type = 'duration';
            changeObject.id = id;
            changeObject.value = $("[id=\'"+id+"']").val();
            numberOfChanges++;
            changes.push(changeObject);

            removeChange(id);
            checkChangesVisisble();
            addChange();
        }
        else{
            changeObject = new Object();
            changeObject.type = 'duration';
            changeObject.id = id;
            changeObject.value = $("[id=\'"+id+"']").val();
            numberOfChanges++;
            changes.push(changeObject);

            checkChangesVisisble();
            addChange();
        }
    }
    else{
        changeObject = new Object();
        changeObject.type = 'duration';
        changeObject.id = id;
        changeObject.value = $("[id=\'"+id+"']").val();
        numberOfChanges++;
        changes.push(changeObject);

        checkChangesVisisble();
        addChange();
    }
}

function changeDate(){

    var countList = 0;
    var index;

    if(changes.length>0){
        for(i=0;i<changes.length;i++){
            if(changes[i]['id']== 'startDate'){
                countList++;
                index = [i];
            }
        }

        if(countList>0){
            changes.splice([index], 1);
            changeObject = new Object();
            changeObject.type = 'date';
            changeObject.id = 'startDate';
            changeObject.value = $("[id=\'selectStartDay']").val();
            numberOfChanges++;
            changes.push(changeObject);

            removeChange('startDate');
            checkChangesVisisble();
            addChange();
        }
        else{
            changeObject = new Object();
            changeObject.type = 'date';
            changeObject.id = 'startDate';
            changeObject.value = $("[id=\'selectStartDay']").val();
            numberOfChanges++;
            changes.push(changeObject);

            checkChangesVisisble();
            addChange();
        }
    }
    else{
        changeObject = new Object();
        changeObject.type = 'date';
        changeObject.id = 'startDate';
        changeObject.value = $("[id=\'selectStartDay']").val();
        numberOfChanges++;
        changes.push(changeObject);

        checkChangesVisisble();
        addChange();
    }
}

function changeStartHoure(){

    var countList = 0;
    var index;

    if(changes.length>0){
        for(i=0;i<changes.length;i++){
            if(changes[i]['id']== 'startHoure'){
                countList++;
                index = [i];
            }
        }

        if(countList>0){
            changes.splice([index], 1);
            changeObject = new Object();
            changeObject.type = 'houre';
            changeObject.id = 'startHoure';
            changeObject.value = $("[id=\'startHoure']").val() +':' +$("[id=\'startMin']").val();
            numberOfChanges++;
            changes.push(changeObject);

            removeChange('startHoure');
            checkChangesVisisble();
            addChange();
        }
        else{
            changeObject = new Object();
            changeObject.type = 'houre';
            changeObject.id = 'startHoure';
            changeObject.value = $("[id=\'startHoure']").val() +':' +$("[id=\'startMin']").val();
            numberOfChanges++;
            changes.push(changeObject);

            checkChangesVisisble();
            addChange();
        }
    }
    else{
        changeObject = new Object();
        changeObject.type = 'houre';
        changeObject.id = 'startHoure';
        changeObject.value = $("[id=\'startHoure']").val() +':' +$("[id=\'startMin']").val();
        numberOfChanges++;
        changes.push(changeObject);

        checkChangesVisisble();
        addChange();
    }
}

function changeEndHoure(){

    var countList = 0;
    var index;

    if(changes.length>0){
        for(i=0;i<changes.length;i++){
            if(changes[i]['id']== 'endHoure'){
                countList++;
                index = [i];
            }
        }

        if(countList>0){
            changes.splice([index], 1);
            changeObject = new Object();
            changeObject.type = 'houre';
            changeObject.id = 'endHoure';
            changeObject.value = $("[id=\'endHoure']").val() +':' +$("[id=\'endMin']").val();
            numberOfChanges++;
            changes.push(changeObject);

            removeChange('endHoure');
            checkChangesVisisble();
            addChange();
        }
        else{
            changeObject = new Object();
            changeObject.type = 'houre';
            changeObject.id = 'endHoure';
            changeObject.value = $("[id=\'endHoure']").val() +':' +$("[id=\'endMin']").val();
            numberOfChanges++;
            changes.push(changeObject);

            checkChangesVisisble();
            addChange();
        }
    }
    else{
        changeObject = new Object();
        changeObject.type = 'houre';
        changeObject.id = 'endHoure';
        changeObject.value = $("[id=\'endHoure']").val() +':' +$("[id=\'endMin']").val();
        numberOfChanges++;
        changes.push(changeObject);

        checkChangesVisisble();
        addChange();
    }
}

function addChange(){

    var list = document.getElementById('changelist');

        if ( list.hasChildNodes() )
        {
            while ( list.childNodes.length >= 1 )
            {
                list.removeChild( list.firstChild );
            }
        }

    for(i=0;i<changes.length;i++){

        if(changes[i]['id'] == 'startDate'){

            var trfield = document.createElement('tr');
            trfield.setAttribute('id',changes[i]['id']+'change');

            list.appendChild(trfield);

            var tdfield = document.createElement('td');
            trfield.appendChild(tdfield);

            var bfield = document.createElement('b');
            tdfield.appendChild(bfield);
            bfield.appendChild(document.createTextNode(changes[i]['value']+' '+changes[i]['id']+' StartDag'));

        }
        else{
            var trfield = document.createElement('tr');
            trfield.setAttribute('id',changes[i]['id']+'change');

            list.appendChild(trfield);

            var tdfield = document.createElement('td');
            trfield.appendChild(tdfield);

            var bfield = document.createElement('b');
            tdfield.appendChild(bfield);
            bfield.appendChild(document.createTextNode(changes[i]['value']+' '+changes[i]['id']+' Bezoekduur'));
        }
    }
}

function removeChange(id){

    if(id == 'startDate'){
        var oldChange = document.getElementById('startDatechange');
        var changeList = oldChange.parentNode;
        changeList.removeChild(oldChange);
    }
    else{
        var oldChange = document.getElementById(id+'change');
        var changeList = oldChange.parentNode;
        changeList.removeChild(oldChange);
    }
}

function viewInList(id){

    toggleTripPlanList();
    toggleTripPlanTripDetail(id);
}

function toggleAddPeriod(){
    $("[id=\'addform']").show();
    $("[id=\'changeform']").hide();
}

function menu() {
    //ACCORDION BUTTON ACTION	
	$('ul.parent li a').click(function() {
		if($(this).hasClass('accordion')){			
			$(this).siblings('ul').slideDown('normal');	
			$(this).removeClass('accordion');
			$(this).addClass('x-accordion');	
		}else{
			$(this).siblings('ul').slideUp('normal');	
			$(this).removeClass('x-accordion');
			$(this).addClass('accordion');
		}
		
	});	
	 
	// HIDE THE DIVS ON PAGE LOAD	
	$("ul.parent li ul").hide();
	
	// ADJUST THE ACTIVE LINK 
	$("ul.parent li.active ul").show();
	$("ul.parent li.active a").removeClass('accordion');
	$("ul.parent li.active a").addClass('x-accordion');
}

/**
 * @param targetImg - jQuery selector for target image
 * @param boxWrapClass - image wrapper class which defined the resulting size of the thumbnail
 */
function initBorder(targetImg,boxWrapClass,group){
    if(boxWrapClass == null) boxWrapClass = 'thumb-box-wrap';

    if(group == null) group = 'current-thumbnail';

    
    //check for the Panoramio data- attributes: owner-name and owner-url
    //add panoramio overlay class
    //add link to the owner's profile on Panoramio

    var owner = $(targetImg).data('owner');
    var url = $(targetImg).data('url');
    // wrap it first with div to generate its uniform size
    $(targetImg).wrap('<div class="'+boxWrapClass+'" />');
    
    // apply attribute to generated link
    $(targetImg).each(
        function(index, element)
        {
            // Thumbnail preparation
            // get image alt and title value
            //var previewImage = $(targetImg).attr('alt');
            var previewImage = $(element).data('imgurl');
            var previewTitle = $(element).attr('title');
            $('<a></a>').addClass('borderthumb').attr({href:previewImage, title:previewTitle, rel:group}).insertBefore(element);
            $(element).removeAttr('title').removeAttr('alt');
        }
    );

        $("a[rel='"+group+"']").colorbox(
            {
                onComplete:function(){
                    var image = $(targetImg).filter(
                        function(){ return $(this).data('imgurl') == $.colorbox.element().get(0); }
                    ).get(0);
                    
                    if(typeof(image) != "undefined")
                    {
                        
                        var exurl = $(image).data('exurl');                        
                        
                        if(exurl != undefined)
                        {                        
                            //load panoramio copyright stuff
                            var photourl = $(image).data('photourl');
                            var width = $(image).data('width');
                            var height = $(image).data('height');
                            var owner = $(image).data('owner');
                            var url = $(image).data('url');
                            var title = $(image).data('title');
                            
                            var text = 
                                '<div class="cbox_overlay">'+
                                '<div class="cbox_logo"><a href="http://panoramio.com" target="_blank"><img src="http://www.panoramio.com/img/logo-tos.png"/></a>Photos are copyrighted by their owners</div>'+
                                '<div class="cbox_bottom"> <a href="'+photourl+'">"'+title+'"</a> by <a href="'+url+'">' + owner+'</a></div>'+
                                '</div>';
                                ;
                            $('.cboxPhoto').before(text);
                            //setTimeout(function(){$('.cboxPhoto').prepend(text);},2000);                                 

                            
                        }
                        
                    }
                    
                    
                }
            }
        );

}

function resultBorder(resImg){
	$(resImg).each(function(){
		// Thumbnail preparation
	    // get image alt and title value
	    var previewImage = $(this).attr('alt');
    	var previewTitle = $(this).attr('title');
		var previewID = $(this).attr('id');

		// wrap it first with div to generate its uniform size
	    $(this).wrap('<div class="resultBoxWrap" />');

		// apply attribute to generated link
	    $('<a></a>').addClass('resultBoxBorder').attr({href:previewImage, title:previewTitle, rel:previewID}).insertBefore(this);
	    $(this).removeAttr('title').removeAttr('alt');
		 //activate the lightbox functionality

	    $("a[rel='"+previewID+"']").colorbox();
	});
}


// to resize the page thumbnail, to fit within the rounded corner
function pageImageResize()  {   
    // Resize the image aspect ratio with class 'resizesmall'
    $('.resizesmall').each(function() {
        var intH;
        var intW;
        var maxW = $(this).css('width').replace('px','');
        var maxH = $(this).css('height').replace('px','');
        intH = parseInt(maxH);
        intW = parseInt(maxW);
        var ratio = 0;  // Used for aspect ratio
        var width = $('.resizesmall img').width();    // Current image width
        var height = $('.resizesmall img').height();  // Current image height       
        // Check if the current width is larger than the max
        if(width > intW){
            ratio = intW / width;   // get ratio for scaling image
            $('.resizesmall img').css("width", intW); // Set new width
            $('.resizesmall img').css("height", height * ratio);  // Scale height based on ratio
            height = height * ratio;    // Reset height to match scaled image
            width = width * ratio;    // Reset width to match scaled image
        }
        // Check if current height is larger than max
        if(height > intH){
            ratio = intH / height; // get ratio for scaling image
            $('.resizesmall img').css("height", intH);   // Set new height
            $('.resizesmall img').css("width", width * ratio);    // Scale width based on ratio
            width = width * ratio;    // Reset width to match scaled image
        }
        $(this).css('width', 'auto' );
        $(this).css('height', 'auto' );
    });     
    
    // Resize the image aspect ratio with class 'resizemedium'
    $('.resizemedium').each(function() {
        var intH;
        var intW;
        var maxW = $('.resizemedium').css('width').replace('px','');
        var maxH = $('.resizemedium').css('height').replace('px','');
        intH = parseInt(maxH);
        intW = parseInt(maxW);
        var ratio = 0;  // Used for aspect ratio
        var width = $('.resizemedium img').width();    // Current image width
        var height = $('.resizemedium img').height();  // Current image height
        //alert (intW);
        //alert (width);
        // Check if the current width is larger than the max
        if(width > intW){
            ratio = intW / width;   // get ratio for scaling image
            $('.resizemedium img').css("width", intW); // Set new width
            $('.resizemedium img').css("height", height * ratio);  // Scale height based on ratio
            height = height * ratio;    // Reset height to match scaled image
            width = width * ratio;    // Reset width to match scaled image
        }
        // Check if current height is larger than max
        if(height > intH){
            ratio = intH / height; // get ratio for scaling image
            $('.resizemedium img').css("height", intH);   // Set new height
            $('.resizemedium img').css("width", width * ratio);    // Scale width based on ratio
            width = width * ratio;    // Reset width to match scaled image
        }
        $(this).css('width', 'auto' );
        $(this).css('height', 'auto' );
    });     
    
    // Resize the image aspect ratio with class 'resizelarge'
    $('.resizelarge').each(function() {
        var intH;
        var intW;
        var maxW = $(this).css('width').replace('px','');
        var maxH = $(this).css('height').replace('px','');
        intH = parseInt(maxH);
        intW = parseInt(maxW);
        var ratio = 0;  // Used for aspect ratio
        var width = $('.resizelarge img').width();    // Current image width
        var height = $('.resizelarge img').height();  // Current image height
        // Check if the current width is larger than the max
        if(width > intW){
            ratio = intW / width;   // get ratio for scaling image
            $('.resizelarge img').css("width", intW); // Set new width
            $('.resizelarge img').css("height", height * ratio);  // Scale height based on ratio
            height = height * ratio;    // Reset height to match scaled image
            width = width * ratio;    // Reset width to match scaled image
        }
        // Check if current height is larger than max
        if(height > intH){
            ratio = intH / height; // get ratio for scaling image
            $('.resizelarge img').css("height", intH);   // Set new height
            $('.resizelarge img').css("width", width * ratio);    // Scale width based on ratio
            width = width * ratio;    // Reset width to match scaled image
        }       
        $(this).css('width', 'auto' );
        $(this).css('height', 'auto' );
    });     
    
}

function initAutoComplete(targetInput, data) {
	function log(event, data, formatted) {
		$("<li>").html( !data ? "No match!" : "Selected: " + formatted).appendTo("#result");
	}

	function formatItem(row) {
		return row[0] + " (<strong>id: " + row[1] + "</strong>)";
	}
	function formatResult(row) {
		return row[0].replace(/(<.+?>)/gi, '');
	}

	$(targetInput).focus().autocomplete(data);
}

function selectMenu(){
	$('.selectMenu').selectmenu({
					style:'popup',
					menuWidth: 180
	});
}


function rangeSlider(targetD, minNum, maxNum, dMin, dMax, isCurrency) {
        $(targetD).each( function(){
                var tName = targetD.substring(1);
                var cSymbol = '';
                if(isCurrency){
                        cSymbol = '\u20AC';
                } 

                $('<p class="rangeMinMax '+tName+'Value">'+cSymbol+dMin+' - '+cSymbol+dMax+'</p><input id="'+tName+'Min" name="'+tName+'Min" value="'+dMin+'" type="hidden" /><input id="'+tName+'Max" name="'+tName+'Max" value="'+dMax+'" type="hidden" />').insertBefore(this);
                $(this).slider({
                                range: true,
                                min: minNum,
                                max: maxNum,
                                values: [ dMin, dMax ],
                                slide: function ( event, ui) {
                                        $(this).siblings( '.'+tName+'Value' ).text( cSymbol + ui.values[ 0 ] + " - "+cSymbol + ui.values[ 1 ] );
                                        $(this).siblings( '#'+tName+'Min' ).val( ui.values[ 0 ] );
                                        $(this).siblings( '#'+tName+'Max' ).val( ui.values[ 1 ] );
                                }
                }); // slider
  });
}

function transportCountry(){
    country = $("[id=\'location']").val();
    
    if(country == 'BE'){
        $("[id=\'transportoptionsformBE']").show();
        $("[id=\'transportoptionsformAN']").hide();
        $("[id=\'transportoptionsformGB']").hide();
    }
    else if(country == 'NL' || country == 'FR' || country == 'DE' || country == 'GH' || country == 'Other'){
        $("[id=\'transportoptionsformBE']").hide();
        $("[id=\'transportoptionsformAN']").show();
        $("[id=\'transportoptionsformGB']").hide();
    }
    else if(country == 'GB'){
        $("[id=\'transportoptionsformBE']").hide();
        $("[id=\'transportoptionsformAN']").hide();
        $("[id=\'transportoptionsformGB']").show();
    }
}

function initializeMapCities(getlat,getlon,zoom){

    var lat = getlat;
    var lon = getlon;
    var mapzoom = zoom;
    var noLocation = new google.maps.LatLng(lat, lon);
    var initialLocation;
    var browserSupportFlag =  new Boolean();
    var map;
    var markers = markerArray;

    var myOptions = {
        zoom: mapzoom,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map"),         myOptions);

    map.setCenter(noLocation);
    for(i=0;i<=markers.length;i++){
        setMarker(markers[i]);
    }

    function setMarker(marker1){
        if (marker1==null) {
            return;
        }
        var contentString;
        if(marker1['url'] == null){
            contentString = marker1['windowText'];
        }
        else{
            contentString = "<a href='"+marker1['url']+"'>"+marker1['windowText']+"</a>";
        }
        var image = marker1['markerIcon'];
        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });
        var location = new google.maps.LatLng(marker1['latitude'],  marker1['longitude']);
        var marker = new google.maps.Marker({
            position: location,
            map: map,
            icon: image,
            title: marker1['windowText']
        });
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
        });
    }
}

function singleSlider(targetD, targetLabel,  minNum, maxNum, defaultVal, incVal ){
	$(targetD).each( function() {
		$(this).slider({
			value:defaultVal,
			min: minNum,
			max: maxNum,
			step: incVal,
			slide: function( event, ui ) {
				$(targetLabel).text(ui.value);
			}
		});
		$(targetLabel).text( $(this).slider('value') );
	});
}

function resizeMap(targetD){
	$(window).resize(function() {
		$(targetD).height($(window).height()).width($(window).width());
	});
}

// dynamic rating generator
function dynaRate(classNeym){
	var sName = $(classNeym).attr('id')+'.score';
	$(classNeym).raty({
					  path: 'images',
					  scoreName: sName,
					  size: 24,
					  starOff:      'big-star0.png',
					  starOn:      'big-star1.png'
	});
}

// dynamic rating generator using smaller star
function dynaRateSmall2(classnaym, imageName){
	$(classnaym).each( function() {
		var sName = $(this).attr('id')+'.score';
		var defaultVal = parseInt( $(this).attr('title')+'.score');
		$(this).raty({
			click:		function(score, evt) {
				addTripCR(this.attr('id'), score);
			},
			path:		'/images',
			scoreName: 	sName,
			size: 		24,
			starOff:	imageName + '-off.png',
			starOn:		imageName + '-on.png',
			start: 		defaultVal,
			hintList:	""
		});
	});
}


// dynamic rating generator using smaller star
function dynaRateSmall(classnaym){
	$(classnaym).each( function() {
		var sName = $(this).attr('id')+'.score';
		var defaultVal = parseInt( $(this).attr('title')+'.score');
		$(this).raty({
                    click: function(score, evt) { alert('Hello Dennis, ID: ' + this.attr('id') + '\nscore: ' + score + '\nevent: ' + evt); },
					 path: '/images',
					 scoreName: sName,
					 size: 24,
					 starOff:      'star-off.png',
					 starOn:      'star-on.png',
					 start: defaultVal
				});
	});
}

function initialvalues() {
    $('#citytripplanform > :input').each( function() {
        var id = $(this).attr('id');
        var val = $(this).val();
        alert ('input id ' + id + ' has initial value ' + val);
    });

}

/**
* @param mapId - html element id to init the map into
* @param markers - array of markers in the following format: {lat:,lon:,icon:,hash:}
* @param directions - object of walking directions in the following format: {hash:{lat:, lon,}}
*/
function initMapPrint(mapId, markers, directions) {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 14,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById(mapId),         myOptions);

    var waypts = [];
    var start = null;
    var end = null;

	var polylineArray = new Array();        

	        

    var bounds = new google.maps.LatLngBounds();
    for(i=0;i<markers.length;i++){
        var markerData = markers[i];

		if(typeof(markerData.hash) != "undefined")
		{
			if(typeof(directions[markerData.hash]) !="undefined" && directions[markerData.hash].length > 0)
			{
				var marker_directions = directions[markerData.hash];
				for(var direction in marker_directions)
				{
					var direction_location = new google.maps.LatLng(marker_directions[direction][0],marker_directions[direction][1]);
					polylineArray.push(direction_location);
				}
			}
		}

        var location = new google.maps.LatLng(markerData.lat,  markerData.lon);
        if (i==0) {
            start = location;
        } else if (i==markers.length-1) {
            end = location;
        } else {
            waypts.push({location:location, stopover:true});
        }
        var marker = new google.maps.Marker({
            position: location,
            map: map,
            icon: markerData.icon
        });
        bounds.extend(location);
    }
    map.fitBounds(bounds);
	//draw the route using cloudmade instructions
	var flightPath = new google.maps.Polyline({
        path: polylineArray,
        strokeColor: "#212BEA",
        strokeOpacity: 0.5,
        strokeWeight: 3
    });

    flightPath.setMap(map);
    /*
	//replaced by cloudmade directives
	var directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers:true});
    var directionsService = new google.maps.DirectionsService();
    directionsDisplay.setMap(map);

    request = {
           origin: start,
           destination: end,
           waypoints: waypts,
           optimizeWaypoints: false,
           travelMode: google.maps.DirectionsTravelMode.WALKING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });*/


}

function trackPageView(name) {
    _gaq.push(['_trackPageview', name]);
}

function SubmitOgone(formName) {
    var form = document.getElementById(formName);
    form.submit();
}

/**
 * Add a read-only raty control
 * @param selector - div element to initialize the widget within
 * @param number - number of stars in max rating
 * @param start - number of stars highlighted(rating value)
 */
function addRatYLocked(selector, number, start)
{
    $(selector).raty({
        start:	start,
        number: number,
        readOnly:true,
        path: '/images',
	cancelOff: 'cancel-off.png',
	cancelOn: 'cancel-on.png'
    });
}

function addRatY(selector, scoreName, start, number, cancel, cancelHint, size, hintList, starOff, starOn, width) {
    
    var cancelHintSelector = "#"+cancelHint;    
    var cancelHintEval = "";
    if (cancelHintSelector.length  > 1) {
        var cancelHintText = $(cancelHintSelector).text();
        cancelHintEval = eval(cancelHintText);
    }
    
    var hintListSelector = "#"+hintList;    
    var hintListEval = "";
    if (hintListSelector.length  > 1) {
        var hintListText = $(hintListSelector).text();
        hintListEval = eval(hintListText);
    }
    $(selector).raty({
		scoreName:	scoreName,
                start:          start,
		number:		number,		
		cancel: 	cancel,
                cancelHint:     cancelHintEval,
		path: '/images',
		cancelOff: 'cancel-off.png',
		cancelOn: 'cancel-on.png',
		size: size,
		hintList:     hintListEval,
		starOff:      starOff,
		starOn:      starOn,
		width: width,
		click:function(score,evt){
		    //the trip plan page - show the appropriate label next to the raty container
		    if($(this).attr('id') == "dayrating")
		    {			
			$('#numberofdays').html($('#page_plan_form_days_'+score).html());
		    }
		    
		}
    });
}

function addRatYStars(selector, scoreName, start, hintList, cancelHint) {
    addRatY(selector, scoreName, start, 4, true, cancelHint, 16, hintList, 'star-off.png', 'star-on.png', null);
}

function addRatYSuitCase(selector, scoreName, start, hintList) {
    addRatY(selector, scoreName, start, 5, false, '', 21, hintList, 'day1-off.png', 'day1-on.png', 160);
}

function initMap(lat, lon, zoom, mapTypeId) {
    var noLocation = new google.maps.LatLng(lat, lon);
    var map;
    var myOptions = {
        zoom: zoom,
        mapTypeId: mapTypeId
    };
    map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
    map.setCenter(noLocation);
    return map;
}

function addMarker(map, lat, lon, contentString, image, title){
    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    var position = new google.maps.LatLng(lat, lon);
    var marker = new google.maps.Marker({
        position: position,
                    map: map,
                    icon: image,
                    title:title
    });
    google.maps.event.addListener(marker, 'click', function() {
                    infowindow.open(map,marker);
    });
}

function getsetgoPopup() {
    // POPUP
    var myOpen = function(hash) { hash.w.fadeIn('500').show(); };
    var myClose = function(hash) { hash.w.fadeOut('600',function(){hash.o.remove(); });  };
    if ($.browser.msie) {
        myOpen = '';
	myClose = '';
    }
    $('.popup-message.popup-print').jqm({
                modal: false,
                //trigger: '.btn-print.btn-locked',
                closeClass: 'close-popup',
                overlay: 30,
                onShow: myOpen,
                onHide: myClose
            });

    $('.popup-message.popup-voucher').jqm({
                modal: false,
                //trigger: '.btn-print.btn-locked',
                closeClass: 'close-popup',
                overlay: 30,
                onShow: myOpen,
                onHide: myClose
            });

    $('.popup-message.popup-iphone').jqm({
        modal: false,
        //trigger: '.btn-iphone.btn-locked',
        closeClass: 'close-popup',
        overlay: 30,
        onShow: myOpen,
        onHide: myClose
    });
    $('.popup-message.popup-android').jqm({
        modal: false,
        //trigger: '.btn-android.btn-locked',
        closeClass: 'close-popup',
        overlay: 30,
        onShow: myOpen,
        onHide: myClose
    });
    $('.popup-message.popup-bookmark').jqm({modal: false, trigger: '.btn-bookmark', closeClass: 'close-popup', overlay: 30, onShow: myOpen, onHide: myClose});
    //$('.popup-message.popup-share').jqm({modal: false, trigger: '.btn-share', closeClass: 'close-popup', overlay: 30, onShow: myOpen, onHide: myClose,overlayClass:'fjnweirfwr'});

    $('.popup-message.popup-email').jqm(
	{
	    modal: false,	    
	    closeClass: 'close-popup',
	    overlay: 30,
	    onShow: function(hash){

		var email = $('.bookmark-email-wrap input[name*=email]').val();
		
		hash.w.fadeIn('500').show();

		if($('.popup-message.popup-email').data('processed') !== true || email != $('.popup-message.popup-email').data('email'))
		{//prevent duplicate sendmail requests to the same email
		    $('.popup-message.popup-email .ajax-loader').show();
		    $('.popup-message.popup-email .popup-content').hide();
		    $.post(
			$('#frmbookmark').attr('action'),
			{
			    email:email
			},
			function(data)
			{
			    $('.popup-message.popup-email').find('.popup-content').html(data);
			    $('.popup-message.popup-email .ajax-loader').hide();
			    $('.popup-message.popup-email .popup-content').show();
			    //set the processed flag for this dialog
			    $('.popup-message.popup-email').data('processed',true);
			    $('.popup-message.popup-email').data('email',email);
			}
		    );
		}
		
	    },
	    onHide: function(hash)
	    {
		
		hash.w.fadeOut(
		    '600',
		    function(){
			hash.o.remove();			
		    }
		);
	    }
	}
    );
}

function homenavigation() {
    $('#cities .navigation a').hover(
			function(){
				$('#cities .navigation a.current').removeClass('current');
				$(this).addClass('current');
				$('#cities .banner .show').removeClass('show');
                                $('#cities ' + $(this).attr('href')).addClass('show');
				return false;
			}
		);
    $('#cities .navigation a').click(
			function(){
                            
                            var href = $('#cities a#' + $(this).attr('href')).attr('href');

                            if(href !== undefined)
                            {
                                window.location.href = href;
                            }
                            else
                            {
                                window.location.href = '#footer';
                            }
                            return false;
			}
		);
}

function homecombobox() {
    
        //var errorMsg = $('<div class="errormessage" style="display:none;font-size:20px;color:red;position:absolute;top:48px;left:55px;">Choose city!</div>');

        //$('#cityform').parent().css('position','relative');

        //$('.ui-autocomplete-input').keypress(function(){
        //    errorMsg.css('display','none');
        //});

       // errorMsg.insertBefore('#cityform');
        //$('#cityform').insertBefore(errorMsg);
        $('#cityform').submit(function(){
            var cityVal = $('#cityname').val();
            if(cityVal == '0') {
                //errorMsg.css('display','block');
                //$('#cityname').val('enter city');                
            }
            else {
                window.location.href = cityVal;
            }
            return false;
        });

}


function print_r(x, max, sep, l) {

	    l = l || 0;
	    max = max || 10;
	    sep = sep || ' ';

	    if (l > max) {
	        return "[WARNING: Too much recursion]\n";
	    }

	    var
	        i,
	        r = '',
	        t = typeof x,
	        tab = '';

	    if (x === null) {
	        r += "(null)\n";
	    } else if (t == 'object') {

	        l++;

	        for (i = 0; i < l; i++) {
	            tab += sep;
	        }

	        if (x && x.length) {
	            t = 'array';
	        }

	        r += '(' + t + ") :\n";

	        for (i in x) {
	            try {
	                r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
	            } catch(e) {
	                return "[ERROR: " + e + "]\n";
	            }
	        }

	    } else {

	        if (t == 'string') {
	            if (x == '') {
	                x = '(empty)';
	            }
	        }

	        r += '(' + t + ') ' + x + "\n";

	    }

	    return r;

	}

sprintf = (function() {
	function get_type(variable) {
		return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
	}
	function str_repeat(input, multiplier) {
		for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
		return output.join('');
	}

	var str_format = function() {
		if (!str_format.cache.hasOwnProperty(arguments[0])) {
			str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
		}
		return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
	};

	str_format.format = function(parse_tree, argv) {
		var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
		for (i = 0; i < tree_length; i++) {
			node_type = get_type(parse_tree[i]);
			if (node_type === 'string') {
				output.push(parse_tree[i]);
			}
			else if (node_type === 'array') {
				match = parse_tree[i]; // convenience purposes only
				if (match[2]) { // keyword argument
					arg = argv[cursor];
					for (k = 0; k < match[2].length; k++) {
						if (!arg.hasOwnProperty(match[2][k])) {
							throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
						}
						arg = arg[match[2][k]];
					}
				}
				else if (match[1]) { // positional argument (explicit)
					arg = argv[match[1]];
				}
				else { // positional argument (implicit)
					arg = argv[cursor++];
				}

				if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
					throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
				}
				switch (match[8]) {
					case 'b': arg = arg.toString(2); break;
					case 'c': arg = String.fromCharCode(arg); break;
					case 'd': arg = parseInt(arg, 10); break;
					case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
					case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
					case 'o': arg = arg.toString(8); break;
					case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
					case 'u': arg = Math.abs(arg); break;
					case 'x': arg = arg.toString(16); break;
					case 'X': arg = arg.toString(16).toUpperCase(); break;
				}
				arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
				pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
				pad_length = match[6] - String(arg).length;
				pad = match[6] ? str_repeat(pad_character, pad_length) : '';
				output.push(match[5] ? arg + pad : pad + arg);
			}
		}
		return output.join('');
	};

	str_format.cache = {};

	str_format.parse = function(fmt) {
		var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
		while (_fmt) {
			if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
				parse_tree.push(match[0]);
			}
			else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
				parse_tree.push('%');
			}
			else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
				if (match[2]) {
					arg_names |= 1;
					var field_list = [], replacement_field = match[2], field_match = [];
					if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
						field_list.push(field_match[1]);
						while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
							if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
								field_list.push(field_match[1]);
							}
							else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
								field_list.push(field_match[1]);
							}
							else {
								throw('[sprintf] huh?');
							}
						}
					}
					else {
						throw('[sprintf] huh?');
					}
					match[2] = field_list;
				}
				else {
					arg_names |= 2;
				}
				if (arg_names === 3) {
					throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
				}
				parse_tree.push(match);
			}
			else {
				throw('[sprintf] huh?');
			}
			_fmt = _fmt.substring(match[0].length);
		}
		return parse_tree;
	};

	return str_format;
})();

var vsprintf = function(fmt, argv) {
	argv.unshift(fmt);
	return sprintf.apply(null, argv);
};

function bounceMarker(marker)
{
    marker.setAnimation(google.maps.Animation.BOUNCE);

    setTimeout(function () {
        marker.setAnimation(null);
    }, 5000);
}

/**
 * https://gist.github.com/1153608
 *
 */
String.prototype.format = function(i, safe, arg) {

  function format() {
    var str = this, len = arguments.length+1;

    // For each {0} {1} {n...} replace with the argument in that position.  If 
    // the argument is an object or an array it will be stringified to JSON.
    for (i=0; i < len; arg = arguments[i++]) {
      safe = typeof arg === 'object' ? JSON.stringify(arg) : arg;
      str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe);
    }
    return str;
  }

  // Save a reference of what may already exist under the property native.  
  // Allows for doing something like: if("".format.native) { /* use native */ }
  //format.native = String.prototype.format;

  // Replace the prototype property
  return format;

}();

/*
 * Add page to bookmarks
 * (used on the GetSetGo page)
 */
function CreateBookmarkLink(selector, url, title) {    
    if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
		return false;
    } else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title);
		return false;
    }
    else if(window.opera) { // Opera Browsers
		$("a.jQueryBookmark").attr("href",bookmarkUrl);
		$("a.jQueryBookmark").attr("title",bookmarkTitle);
		$("a.jQueryBookmark").attr("rel","sidebar");	
		return false;
    }
    return true;
 }


