/* ==============================================
Integrated Multimap - Dyson Airblade UK
Author: Nick Aspinall - 13/11/2008
Updated: 
Updated On: 
============================================== */
var mapviewer, searcher, loading, markers, search, pre_search;
var multi_address_select, city, country_code, address_select, address_city, postalcode, max_distance, count, start_index, filter1, filter2, filter3, return_fields, submitbtn;
var funcRef = resultsLoaded;
var myInterval, myWait = 0;
// Including the 'client_id' ensures that clicking on a result logs it as such within the reports:
var rfs = ['client_id', 'name', 'street', 'town', 'country', 'pc', 'telephone', 'lat', 'lon'];

/* Custom global variables for animation logic */
var haveResults = false;
var firstSearch = true;
var currentErr = false;
var btnDisabled = false;
	
/* ----- LISTENERS ------ */
Event.observe(window, 'load', function() {
    Event.observe("retailers", "submit", function(event) {
        Event.stop(event);
    });
    enableBtn();
    Event.observe("submitRetailersForm", "mousedown", doSearch);
    mapviewer = new MultimapViewer($('mapviewer'));
});
/* ----- DOM ElEMENTS ------ */
function backButton() {
    var backLink = document.createElement("a");
    backLink.href = "javascript:void(0)";
    backLink.className = "back";
    backLink.id = "backLink";
    var backLinkNode = document.createTextNode("Back");
    backLink.appendChild(backLinkNode);
    $('backLinks').appendChild(backLink);
    $('backLink').style.display = "none";
}
/* ------ MAIN FUNCTIONS ------ */
function doSearch() {
    disableBtn();
    setTimeout('enableBtn()', 5000);
    if (currentErr) {
        msgOut();
    }
    setTimeout('cleanUp()', 500);
    mapviewer.removeAllOverlays();
    markers = new Array();
	var city  = $('city').value;
	var postalcode  = $('postalcode').value;
	var radius  = $('radius').value;
    myaddress = new MMAddress();
    myaddress.country_code = "UK";
	myaddress.city = city;
    myaddress.postal_code = postalcode;
	var mySearchResults = initSearch();
	return(false);
}
function cleanUp() {
    var message = $('message');
    var record_list = $('recordListDiv');
    while (record_list.firstChild) {
       record_list.removeChild(record_list.firstChild);
    }             
}
function initSearch() {
    searcher = new MMSearchRequester( funcRef );
    // Construct variables for use as starting location for search:    		
	search = new MMSearch(); 
    search.address = new MMAddress();
    search.address.city=$('city').value;
    search.address.postal_code=$('postalcode').value;
    search.address.country_code = "UK";   
    // Set return fields and maximum number of records to return from search:
	search.return_fields = rfs;
    search.count = 10;    
    search.max_distance = $('radius').value;
    search.min_distance = 0;
    search.distance_units = "miles";
    return searcher.search( search );
}
function fadeOut() {
	new Effect.Fade('buy', { 
		duration: 0.5
	});
}
function fadeOutMap() {
	$('mapviewer').setStyle({
		'height':'0px'
	});
    new Effect.Morph('multimapResults', {
        style: 'min-height:0em; height:auto; height:0em !important',
        duration: 0.5
    });
}

function hideMap() {
    $('map').setStyle({
        opacity: 0.0
    });
}
/*function killMapviewer() {
	$('mapviewer').setStyle({
        display:none;
    });
}*/
function fadeBack() {
   	//When the back link is in pressed, fade out map
	new Effect.Morph('doubleColumn', {
		style: 'min-height:30em; height:auto; height:30em !important',			 
		duration: 0.5,
		afterFinish: function() { fadeOutMap(); }
    });
	new Effect.Fade('multimapResults', { 
		from: 1.1,
		to: 0.001,
		duration: 0.5
		});
	//Fade out back link
	new Effect.Fade('backLink', {
		duration: 0.5
		});
	//Slide up and fade out the error message if present
	if (currentErr) {
		msgOut();
		}
	setTimeout('panelsIn()', 1000)
	//setTimeout('killMapviewer()', 500)
}
function backButtonIn() {
    //Create a new link object if not already present
    if (!$('backLink')) {
        backButton();
    }
    Event.observe("backLink", "mousedown", fadeBack);
    new Effect.Appear('backLink', {
        from: 0.0,
        to: 1.1,
        duration: 0.5
    });
}
//Once the map has been shown, then the back button clicked, the original panels will appear and set the variables back to their original states
function panelsIn() {
    new Effect.Appear('buy', { 
		from: 0.0,
		to: 1.1,
		duration: 0.5
	});
	haveResults = false;
	firstSearch = true;
}
function openInfoBox( type, target) {
     if( target.infoBoxOpened() ) {
        target.closeInfoBox();
    }
    else {
        target.openInfoBox( );
    }
}
function createMarker(location, display_name, num) {
    // Creates marker
    var marker = mapviewer.createMarker(location, {'text' : num});
    marker.setInfoBoxContent('<p>' + display_name + '<' + '/p>');
    return marker;
}
function resultsLoaded() {
    var container = $('message');
    var el = document.createElement('ol');
    el.id = 'recordList';
    var start_index_value = 1;    
    // Loop through each record set:
    for ( var count=0, l = searcher.record_sets.length; count < l; count++ ) {
        // If an error was returned for the record set, display details and return:
        if ( searcher.record_sets[count].error ) {
            var err =  '';
            if ( searcher.record_sets[count].error.error_explanation ) {
                err =  searcher.record_sets[count].error.error_explanation;
            } else {
                err =  'Your request failed. Error code: ' + searcher.record_sets[count].error.error_code;
            }
            alert( err );
            return;  
        } 
        // If not, check to see if individual records have been returned:
        if ( searcher.record_sets[count].records ) {
            // Loop through each record in the record set, and add it to the list below the map,
            // and populate the infobox text:           
            for (var record_count = 0, rl = searcher.record_sets[count].records.length; record_count < rl; record_count++ ) {
               var record = searcher.record_sets[count].records[record_count];                  
               var anchor = handleRecord(record, start_index_value + record_count);
               var record = searcher.record_sets[count].records[record_count];                  
               var tr = handleRecord(record, start_index_value + record_count); 
               el.appendChild (tr);
           }
           playResults(record_count, el, markers);
       } else {
           if (!(currentErr)) {
               hideResults();
               setTimeout('hideMap()', 600);
           }
           handleError('MM_GEOCODE_NO_MATCHES', container);
       }
   }

   if (searcher.record_sets.length == 0) {
       if (!(currentErr)) {
           hideResults();
           setTimeout('hideMap()', 600);
       }
       handleError('MM_GEOCODE_NOT_RECOGNISED', container);
   }
}       
function playResults(record_count,el,markers) {
	var recordContainer = $('recordListDiv');
	if (firstSearch) {
	    fadeOut();
	    backButtonIn();
	} else {
	    if (currentErr) {
	        hideMap();
	    } else {
            hideResults();
        }
    }
    //This periodical executer is allowing the user to return multiple result sets, if they click more than once on the search button.
    new PeriodicalExecuter(function(pe) {
        resizeDown(record_count);
        recordContainer.appendChild(el);
		mapviewer.goToPosition ( mapviewer.getAutoScaleLocation(markers) );
	    pe.stop();
	}, 0.75);
}
//This is called everytime a new set of results is displayed, it resizes the height and fades in the map results
function resizeDown(record_count) {
    var newHeight = calculateHeight(record_count);
    hideMap();
    if (firstSearch) {
       $('multimapResults').setStyle({
            minHeight: '30em',
			height: 'auto',
			height: '30em !important',
            opacity: 0.0
        });
		$('mapviewer').setStyle({
			'height':'350px'
		});
        new Effect.Appear('multimapResults', {
            from: 0.0,
            to: 1.1,
            duration: 1.0
        });
        firstSearch = false;
    }
    new Effect.Morph('multimapResults', {
        style: 'min-height:' + ((newHeight * 6.6) + 2.2) + 'em; height:auto; height:' + ((newHeight * 6.6) + 2.2) + 'em',
        duration: 1.0
    });
    new Effect.Morph('doubleColumn', {
        style: 'min-height:' + ((newHeight * 6.6) + 2.2) + 'em; height:auto; height:' + ((newHeight * 6.6) + 2.2) + 'em',
        duration: 1.0
    });
    setTimeout('showResults()', 500);
}
//Works out the number of 'li' elements in the recordList element 
function calculateHeight(displayHeight) {
    if (displayHeight < 6) {
        var displayHeight = 6;
    }
    return displayHeight;
}
function showResults() {
    new Effect.Appear('map', {
        from: 0.0,
        to: 1.1,
        duration: 0.5
    });
    haveResults = true;
    enableBtn();
}
function hideResults() {
    new Effect.Fade('map', {
        from: 1.1,
        to: 0.01,
        duration: 0.5
    });
}
function handleRecord ( record, num ) {
    // Create marker text for the infobox for this record:    
    var marker_text = "<p><strong>Result #" + num + "</strong></p>";
    marker_text += "<h2>" + record.name + "</h2>";
    marker_text += "<p><strong>Address: </strong><br/>";
    if (record.street.length > 0) { marker_text += record.street += " "; }
    if (record.town.length > 0) { marker_text += record.town += " "; }
    if (record.pc.length > 0) { marker_text += record.pc; }
    marker_text += "<br/>";
    if (record.telephone.length > 0) { marker_text += "<br/><strong>Tel: </strong>" + record.telephone; }
    if (record.distance) {
        marker_text += "<p><strong>Distance: </strong>" /*+ record.distance.km + " km, "*/ + record.distance.miles + " miles<" + "/p>"
    }
    var el = document.createElement ( 'ol' );
    el.id = 'recordList';
    if ( record.point ) {   
        var marker = createMarker( record.point, marker_text, num);
        markers.push(marker);
    } 
    // Creates DOM elements for the Results List     
    // Link
    var anchor = document.createElement ( 'a' );
    anchor.href = '#';
    anchor.record_id = record.id;
    anchor.appendChild(document.createTextNode ( record.name ));
    anchor.onclick = function () { openInfoBox ( 'click', marker ); return false; };    
    // Address
    var address = document.createElement ( 'div' );
    address.appendChild(document.createTextNode ( record.street ));
    address.appendChild(document.createTextNode ( " " ));
    address.appendChild(document.createTextNode ( record.town ));
    address.appendChild(document.createTextNode ( " " ));
    address.appendChild(document.createTextNode ( record.pc ));
    // Telephone
    var telephone = document.createElement ( 'div' );
    telephone.appendChild(document.createTextNode ( "Tel :" ));
    telephone.appendChild(document.createTextNode ( record.telephone ));  
    var tr = document.createElement ( 'li' );
    el.appendChild(tr);    
    var tds = [   
        anchor,   
        address,
        telephone
    ]; 
    for ( i  = 0; i < tds.length; i++) {
        tr.appendChild(tds[ i ]);
    } 
    return tr;
}
// Error handling functions
	/* APPEAR AND OPEN */
	function msgIn() {
		new Effect.Appear('msgTxt', {
		    from: 0.0,
			to: 1.1,
			duration: 0.5
			}); 
		if (!(currentErr)) {
			currentErr = true;
		}
	}
	function msgDown() {
	    $('msgTxt').style.display = 'none';
	    $('message').style.display = 'block';
		new Effect.Morph('message', { 
			style: 'height:6em',
			duration: 0.5
			});
		setTimeout('msgIn()', 500);	
	}
	/* FADE AND CLOSE */
	function msgOut() {
		new Effect.Fade('msgTxt', {
		    from: 1.1,
			to: 0.0,
			duration: 0.5
			});
		setTimeout('msgUp()', 500);
	}
	function msgUp() {
		new Effect.Morph('message', { 
			style: 'height:0em',
			duration: 0.5
    }); 
    currentErr = false;
}
	function handleError(err) {
	    new PeriodicalExecuter(function(pe) {
	  	    errorMsg(err);
		    pe.stop();
	    }, 1.0);
}
function errorMsg(err) {
	var msg = $('msgTxt')
	if (err == 'MM_GEOCODE_MULTIPLE_MATCHES') {
		msg.innerHTML = "I'm sorry, your search has returned too many results for a location. Please try narrowing your search criteria."
	}else if (err == 'MM_GEOCODE_NO_MATCHES') {
		msg.innerHTML ="I'm sorry, your search has returned no results. Please try widening your search criteria."
	}else if (err == 'MM_GEOCODE_NOT_RECOGNISED') {
	    msg.innerHTML = "I'm sorry, we don't know where you mean, please check and try again."
	}else {
		msg.innerHTML ="I'm sorry, there seems to have been a problem with your search. Please try some different criteria."
	}
	msgDown();
	enableBtn();
}
function disableBtn() {
    $('submitRetailersForm').disabled = true;
    $('submitRetailersForm').style.cursor = 'not-allowed';
    btnDisabled = true;
    
}
function enableBtn() {
    //if ('btnDisabled == true') {
    $('submitRetailersForm').disabled = false;
    $('submitRetailersForm').style.cursor = 'pointer';
        btnDisabled = false;
    //}
}
