var searchFocus = false;

nn=(document.layers)?true:false;
ie=(document.all)?true:false;

function keyDown(e) {
	var evt=(e)?e:(window.event)?window.event:null;
	if(evt){
		var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
		// Map search on enter
		if(key=="13" && searchFocus) {
			searchMap(document.getElementById('searchLocation').value);
		}
	}
}
document.onkeydown=keyDown;
if(nn) document.captureEvents(Event.KEYDOWN);

 
var handleCommentSuccess = function(o){
	if ('<!--NOTPOSTED-->'==o.responseText) {
		alert('To guard against spam, only one post in each section is permitted per user.');
	}
    if(o.responseText !== undefined){
		var quoteList = document.getElementById(o.argument[0]);
		var clearField = document.getElementById(o.argument[1]);
        quoteList.innerHTML = o.responseText + quoteList.innerHTML;
		clearField.value = '';
    }

};
 
var handleCommentFailure = function(o){
    var div = document.getElementById('container');
    if(o.responseText !== undefined){
        div.innerHTML = "<li>Transaction id: " + o.tId + "</li>";
        div.innerHTML += "<li>HTTP status: " + o.status + "</li>";
        div.innerHTML += "<li>Status code message: " + o.statusText + "</li>";
    }
};
 

var formName = "";
var formEmail = "";
var formPostcode = "";
var formContent = "";
var sUrl = "/req/s.php";

function validateForm(){

    formName = document.getElementById('name-field').value;
    formEmail = document.getElementById('email-field').value;
    formPostcode = document.getElementById('postcode-field').value;

    var valid = true;

    if(formName == ""){
        document.getElementById('name-field').className = "error";
        document.getElementById('name-field-label').className = "error";
        valid = false;
    }else{
        document.getElementById('name-field').className = "";
        document.getElementById('name-field-label').className = "";
    }
    if(formEmail == ""){
        document.getElementById('email-field').className = "error";
        document.getElementById('email-field-label').className = "error";
        valid = false;
    }else{
        document.getElementById('email-field').className = "";
        document.getElementById('email-field-label').className = "";
    }
    if(formPostcode == ""){
        document.getElementById('postcode-field').className = "error";
        document.getElementById('postcode-field-label').className = "error";
        valid = false;
    }else{
        document.getElementById('postcode-field').className = "";
        document.getElementById('postcode-field-label').className = "";
    }

    return valid;

}

function submitForm(){
    var r = document.getElementById('form-feedback');

    if(validateForm()){
        r.innerHTML = "Thank you for your interest. Now fill in sections 2, 3 &amp; 4.";
        r.className = "success";
    }else{
        r.innerHTML = "Please fill in all the fields before clicking submit";
        r.className = "error";
    }

}

function submitQuestion1(){

    var r = document.getElementById('question-1-response');

    if(validateForm()){

        formContent = document.getElementById('question-1-field').value;
		r.innerHTML = "";

        if(formContent != ""){
            document.getElementById('question-1-field').className = "";
            var callback =
            {
                success:handleCommentSuccess,
                failure:handleCommentFailure,
                argument: ['question-1-list','question-1-field']
            };

            var postData = "name="+formName+"&email="+formEmail+"&postcode="+formPostcode+"&comment="+formContent+"&type=3";

            var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);

        }else{
            document.getElementById('question-1-field').className = "error";
            r.innerHTML = "Please enter a comment";
        }
    }else{
        r.innerHTML = "Please fill in all of the required fields on the form at the top of this page";
    }
}

function submitQuestion2(){

    var r = document.getElementById('question-2-response');

    if(validateForm()){

        formContent = document.getElementById('question-2-field').value;

        if(formContent != ""){
            document.getElementById('question-2-field').className = "";
            var callback =
            {
                success:handleCommentSuccess,
                failure:handleCommentFailure,
                argument: ['question-2-list','question-2-field']
            };

            var postData = "name="+formName+"&email="+formEmail+"&postcode="+formPostcode+"&comment="+formContent+"&type=4";

            var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);

        }else{
            document.getElementById('question-2-field').className = "error";
            r.innerHTML = "Please enter a comment";
        }
    }else{
        r.innerHTML = "Please fill in all of the required fields on the form at the top of this page";
    }
}

var handleVoteSuccess = function(o){
    var v = document.getElementById(o.argument[0]);
    var v2 = YAHOO.util.Dom.getElementsByClassName('vote-val','div',v)[0];
    v2.innerHTML = o.responseText;
}
var handleVoteFailure = function(o){

}

function addVote(id,vote){

    var callback =
    {
        success:handleVoteSuccess,
        failure:handleVoteFailure,
        argument: ['quote-'+id]
    };

    var postData = "id="+id+"&vote="+vote;

    var request = YAHOO.util.Connect.asyncRequest('POST', '/req/v.php', callback, postData);

}

var handleFlagSuccess = function(o){
    var v = document.getElementById(o.argument[0]);
    v.parentNode.removeChild(v);
}
var handleFlagFailure = function(o){

}

function flag(id){
    var callback =
    {
        success:handleFlagSuccess,
        failure:handleFlagFailure,
        argument: ['quote-'+id]
    };

    var postData = "id="+id;

    var request = YAHOO.util.Connect.asyncRequest('POST', '/req/f.php', callback, postData);
}

var handleFlagLSuccess = function(o){

}
var handleFlagLFailure = function(o){

}
function flagL(id){
    var callback =
    {
        success:handleFlagLSuccess,
        failure:handleFlagLFailure
    };

    var postData = "id="+id;
    map.closeInfoWindow();

    var request = YAHOO.util.Connect.asyncRequest('POST', '/req/fl.php', callback, postData);
}


/********** MAP ***********/
var map;
var geocoder;
var localSearch;

var userMarker;

function createMap(){
    if (google.maps.BrowserIsCompatible()) {
        // Set up and configure map
        map = new google.maps.Map2(document.getElementById("map"));
        map.setCenter(new GLatLng(52.461,-1.876), 12);
        map.addControl(new GLargeMapControl3D());
        map.addControl(new GMapTypeControl());
        map.enableScrollWheelZoom();


        //create pin icon for users location
        var blueIcon = new GIcon();
        blueIcon.image = "http://maps.google.com/mapfiles/ms/icons/blue-pushpin.png";
        blueIcon.shadow = "http://maps.google.com/mapfiles/ms/icons/msmarker.shadow.png";
        blueIcon.iconSize=new GSize(32,32);
        blueIcon.shadowSize=new GSize(56,32);
        blueIcon.iconAnchor=new GPoint(10,32);
        blueIcon.infoWindowAnchor=new GPoint(16,0);
        userMarker = new GMarker(new GPoint(0,0),{
            draggable:'true',
            icon:blueIcon
        });
        GEvent.addListener(userMarker,"dragend",dragHandler);

        map.addOverlay(userMarker);
        userMarker.hide();

        GEvent.addListener(map,"click",clickHandler);

        localSearch = new google.search.LocalSearch();
        localSearch.setSearchCompleteCallback(null,localSearchCallback);

        /*geocoder = new google.maps.ClientGeocoder();
        geocoder.setBaseCountryCode("uk");*/
    
    }
}

function localSearchCallback(){
    if (localSearch.results[0]) {
        var resultLat = localSearch.results[0].lat;
        var resultLng = localSearch.results[0].lng;
        var point = new GLatLng(resultLat,resultLng);

        placeUserMarker(point,localSearch.results[0].titleNoFormatting);
    }else{
        alert("Address not found!");
    }
}

function searchMap(address){
    if(address != "Place or postcode")
        localSearch.execute(address + ", Birmingham, UK");
}
function clickHandler(overlay,point){
    if(!overlay){
        placeUserMarker(point);
    }
}

function placeUserMarker(point,title){
    map.panTo(point);
    userMarker.setLatLng(point);
    if(!title){title=''};
    userMarker.infoHtml = "<div class='info-window'><label for='question-3-field'>Location:</label> <input type='text' id='question-3-field' name='question-3-field' value='"+title+"'/><br />\n\
    <button type='button' onclick='submitLocation()' class='submit-button'>Submit</button><p id='question-3-response'></p></div>";
    userMarker.openInfoWindow(userMarker.infoHtml);
    userMarker.show();
}
function dragHandler(point){
    userMarker.openInfoWindow(userMarker.infoHtml);
}

function submitLocation(){
    var r = document.getElementById('question-3-response');

    if(validateForm()){

        formContent = document.getElementById('question-3-field').value;

        if(formContent != ""){
            document.getElementById('question-3-field').className = "";
            var callback =
            {
                success:handleLocationSuccess,
                failure:handleLocationFailure
            };

            var postData = "name="+formName+"&email="+formEmail+"&postcode="+formPostcode+"&title="+formContent+"&lat="+userMarker.getLatLng().lat()+"&lng="+userMarker.getLatLng().lng();

            var request = YAHOO.util.Connect.asyncRequest('POST', '/req/l.php', callback, postData);
            userMarker.title = formContent;
            userMarker.closeInfoWindow();
            userMarker.hide();
        }else{
            document.getElementById('question-3-field').className = "error";
            r.innerHTML = "Please enter a name for this location";
        }
    }else{
        r.innerHTML = "Please fill in all of the required fields on the form at the top of this page";
    }
}

function handleLocationSuccess(o){
    var marker = new GMarker(userMarker.getLatLng(),{title: userMarker.title});
    marker.bindInfoWindowHtml("<strong>"+userMarker.title+"</strong><br />1 second ago<br />by "+formName);
    map.addOverlay(marker);
}
function handleLocationFailure(o){
    userMarker.show();
}