﻿
var noContenders = 0;
var numberOfContendersToGet = 3;

var priceDontMind = true;
var wantDontMind = true;
var seatsDontMind = true;
var spaceDontMind = true;
var coloursDontMind = true;
var fuelDontMind = true;
var greenDontMind = true;
var speedDontMind = true;
var edit = false;
var postcode = '';
var distance = '';
var setupRan = false;


$(document).ready(function() {



    $('#priceSlider').slider({ range: true, min: 0, max: 55000, steps: 11, change: onPriceChanged });
    $('#seatsSlider').slider({ min: 1, max: 6, steps: 5, change: onSeatsChanged });
    $('#fuelSlider').slider({ min: 0, max: 50, steps: 4, change: onFuelChanged });
    // the value passed to the query is worked out by taking 100 away and inversing the answer
    $('#greenSlider').slider({ min: 0, max: 70, steps: 4, change: onGreenChanged });
    // the value passed to the query is worked out by taking 20 away and inversing the answer
    // eg, 0 becomes 19 and 13 becomes 7
    $('#speedSlider').slider({ min: 0, max: 12, steps: 3, change: onSpeedChanged });

    // bind up the controls
    bindWants();
    bindPrice();
    bindSeats();
    bindSpace();
    bindColours();
    bindFuel();
    bindGreen();
    bindSpeed();

    // if we are not editing then we are doing a new search
        // the show the questions
        $('.overlay').fadeOutOneByOne();
        $('#centrePanel').addClass("active");
            $('#contenderscount').fadeIn('fast');
        InitEditMode();
    // display colour name below colour selection

    $("#coloursQuestion img").bind("mouseenter", function() {

        $("#coloursName").html($(this).attr("id"));

    });
    $("#coloursQuestion img").bind("mouseleave", function() {

        $("#coloursName").html("");

    });

});
var bDisableSearch = false;

function InitEditMode() {
    //aquire js parameters
    if (!setupRan) {
        setupRan = true;
        // the show the questions

        var bCenterActive = false;
        bDisableSearch = true;
        // set the sliders and checkboxes to the selected values
        if (lsedit_lpriceMin!=null || lsedit_lpriceMax!=null){setPrice(lsedit_lpriceMin, lsedit_lpriceMax);bCenterActive=true;}
        if (lsedit_liwant != null)  {setWants(lsedit_liwant);bCenterActive=true;}
        if (lsedit_licarry != null) {setSeats(lsedit_licarry);bCenterActive=true;}
        if (lsedit_lspace != null) {setSpace(lsedit_lspace);bCenterActive=true;}
        if (lsedit_lcolours != null){ setColours(lsedit_lcolours);bCenterActive=true;}
        if (lsedit_lfuel!=null) {setFuel(lsedit_lfuel);bCenterActive=true;}
        if (lsedit_lgreen!=null) {setGreen(lsedit_lgreen);bCenterActive=true;}
        if (lsedit_lspeed != null) { setSpeed(lsedit_lspeed); bCenterActive = true; }
        if (lsedit_postcode != null) {
            postcode = lsedit_postcode;
            $('#postcode').val(lsedit_postcode)
         }
         if (lsedit_distance != null) {
             distance = lsedit_distance;
             $('#distance').val(lsedit_distance)
            }
        if (bCenterActive) {
            $('#centrePanel').addClass("active");
            $('.overlay').fadeOutOneByOne();
            $('.overlay').css('opacity', 0);
            $('#contenderscount').css('display', 'none');
        }
        bDisableSearch = false;
        GetContenders();
    }
}


function setPrice(minPrice, maxPrice) {
    if (minPrice != null && maxPrice != null) {
        $('#priceSlider').slider("moveTo", maxPrice, 1);
        $('#priceSlider').slider("moveTo", minPrice, 0);
    }
    else if (minPrice != null) {
        $('#priceSlider').slider("moveTo", minPrice, 0);
    }
    else if (maxPrice != null) {
        $('#priceSlider').slider("moveTo", maxPrice, 1);
    }
    setPriceDontMindUnselected();
}

function setWants(wants) {
    if (wants.length > 0) {
        $('#' + wants).toggleClass('wantselected');
        setWantDontMindUnselected();
    }
}


function setSeats(noSeats) {
    $('#seatsSlider').slider("moveTo", noSeats);
    setSeatsDontMindUnselected();
}

function setSpace(spaces) {
   
    if (spaces.length > 0) {
        $('#' + spaces).toggleClass('spaceselected');
        setSpaceDontMindUnselected();
    }

}

function setColours(colours) {
    $('.colour')
        .each(function() {
            // if this colour is contained in collection of colours then set it to selected
            if (colours.toString().indexOf($(this).attr("id").toLowerCase()) > -1) {
                $(this).toggleClass('colourselected');
            }
        });

    if (colours.length > 0) {
        setColoursDontMindUnselected();
    }
}

function setFuel(fuel) {
    $('#fuelSlider').slider("moveTo", fuel);
    setFuelDontMindUnselected();
}

function setGreen(green) {
    green = Math.abs(green - 100);
    $('#greenSlider').slider("moveTo", green);
    setGreenDontMindUnselected();
}

function setSpeed(speed) {
    speed = Math.abs(speed - 19);
    $('#speedSlider').slider("moveTo", speed);
    setSpeedDontMindUnselected();
}

function onGetParametersFailed() {
    displayGenericError();
}


// #########
// PRICE

function bindPrice() {
    $('#priceSlider').slider("moveTo", 55000, 1);
    $('#priceSlider').slider("moveTo", 0, 0);
}

function priceDontMindClicked() {
    priceDontMind = false;
    bindPrice();
    setPriceDontMind();
    GetContenders();
}

function onPriceChanged(e, ui) {
    var maxPrice = $('#priceSlider').slider("value", 1);
    var minPrice = $('#priceSlider').slider("value", 0);
    if (minPrice > 0 || maxPrice < 55000) {
        setPriceDontMindUnselected();
    }
    else {
        setPriceDontMind();
    }
    GetContenders();
}

function setPriceDontMindUnselected() {
    priceDontMind = false;
    // then unselect the dont mind
    $('#priceDontMind div:nth-child(1)').removeClass('boxselected').addClass('box');
    $('#priceDontMind div:nth-child(2)').removeClass('labelselected').addClass('label');
    // and bind its click event
    $('#priceDontMind').click(function() {
        priceDontMindClicked();
    });
}

function setPriceDontMind() {
    priceDontMind = true;
    $('#priceDontMind div:nth-child(1)').removeClass('box').addClass('boxselected');
    $('#priceDontMind div:nth-child(2)').removeClass('label').addClass('labelselected');
    // unbind its click event
    $('#priceDontMind').unbind('click');
}

// #########
// WANT
function bindWants() {
    $('.want').click(function() {
        // uncheck everything else and select me
        $(this).siblings('.want').removeClass('wantselected').addClass('want').end().toggleClass('wantselected');

        // if there is a want selected
        if (buildWantList().length > 0) {
            setWantDontMindUnselected();
        }
        else {
            setWantDontMind();
        }
        GetContenders();
    });
}


function wantDontMindClicked() {
    wantDontMind = false;
    $('.want').removeClass('wantselected').addClass('want');
    setWantDontMind();
    GetContenders();
}

function setWantDontMindUnselected() {
    wantDontMind = false;
    // then unselect the dont mind
    $('#wantDontMind div:nth-child(1)').removeClass('boxselected').addClass('box');
    $('#wantDontMind div:nth-child(2)').removeClass('labelselected').addClass('label');
    // and bind its click event
    $('#wantDontMind').click(function() {
        wantDontMindClicked();
    });
}

function setWantDontMind() {
    wantDontMind = true;
    $('#wantDontMind div:nth-child(1)').removeClass('box').addClass('boxselected');
    $('#wantDontMind div:nth-child(2)').removeClass('label').addClass('labelselected');
    // unbind its click event
    $('#wantDontMind').unbind('click');
}

// #########
// SEATS
function bindSeats() {
    $('#seatsSlider').slider("moveTo", 1);
}

function setSeatsDontMindUnselected() {
    seatsDontMind = false;
    // then unselect the dont mind
    $('#seatsDontMind div:nth-child(1)').removeClass('boxselected').addClass('box');
    $('#seatsDontMind div:nth-child(2)').removeClass('labelselected').addClass('label');
    // and bind its click event
    $('#seatsDontMind').click(function() {
        seatsDontMindClicked();
    });
}

function seatsDontMindClicked() {
    seatsDontMind = false;
    bindSeats();
    setSeatsDontMind();
    GetContenders();
}

function onSeatsChanged(e, ui) {
    var seats = $('#seatsSlider').slider("value");
    if (seats > 1) {
        setSeatsDontMindUnselected();
    }
    else {
        setSeatsDontMind();
    }
    GetContenders();
}

function setSeatsDontMind() {
    seatsDontMind = true;
    $('#seatsDontMind div:nth-child(1)').removeClass('box').addClass('boxselected');
    $('#seatsDontMind div:nth-child(2)').removeClass('label').addClass('labelselected');
    // unbind its click event
    $('#seatsDontMind').unbind('click');
}

// #########
// SPACE




function bindSpace() {
    $('.space').click(function() {
        // uncheck everything else and select me
        $('.splitleft').children().siblings('.space').removeClass('spaceselected').addClass('space'); //.end().toggleClass('spaceselected');
        $('.splitright').children().siblings('.space').removeClass('spaceselected').addClass('space'); //.end().toggleClass('spaceselected');
        $(this).siblings('.space').removeClass('spaceselected').addClass('space').end().toggleClass('spaceselected');
        // if there is a space selected

        if (buildSpace().length > 0) {
            setSpaceDontMindUnselected();
        }
        else {
            setSpaceDontMind();
        }
        GetContenders();
    });
}


function spaceDontMindClicked() {
    spaceDontMind = false;
    $('.space').removeClass('spaceselected').addClass('space');
    setSpaceDontMind();
    GetContenders();
}

function setSpaceDontMindUnselected() {
    spaceDontMind = false;
    // then unselect the dont mind
    $('#spaceforDontMind div:nth-child(1)').removeClass('boxselected').addClass('box');
    $('#spaceforDontMind div:nth-child(2)').removeClass('labelselected').addClass('label');
    // and bind its click event
    $('#spaceforDontMind').click(function() {
        spaceDontMindClicked();
    });
}

function setSpaceDontMind() {
    spaceDontMind = true;
    $('#spaceforDontMind div:nth-child(1)').removeClass('box').addClass('boxselected');
    $('#spaceforDontMind div:nth-child(2)').removeClass('label').addClass('labelselected');
    // unbind its click event
    $('#spaceforDontMind').unbind('click');
}



// #########
// COLOURS
function bindColours() {
    $('.colour').click(function() {
        $(this).toggleClass('colourselected');
        // if there is a space selected
        if (buildColoursList().length > 0) {
            setColoursDontMindUnselected();
        }
        else {
            setColoursDontMind();
        }
        GetContenders();
    });
}

function coloursDontMindClicked() {
    coloursDontMind = false;
    $('.colour').removeClass('colourselected').addClass('colour');
    setColoursDontMind();
    GetContenders();
}

function setColoursDontMindUnselected() {
    coloursDontMind = false;
    // then unselect the dont mind
    $('#coloursDontMind div:nth-child(1)').removeClass('boxselected').addClass('box');
    $('#coloursDontMind div:nth-child(2)').removeClass('labelselected').addClass('label');
    // and bind its click event
    $('#coloursDontMind').click(function() {
        coloursDontMindClicked();
    });
}

function setColoursDontMind() {
    coloursDontMind = true;
    $('#coloursDontMind div:nth-child(1)').removeClass('box').addClass('boxselected');
    $('#coloursDontMind div:nth-child(2)').removeClass('label').addClass('labelselected');
    // unbind its click event
    $('#coloursDontMind').unbind('click');
}

// #########
// FUEL

function bindFuel() {
    $('#fuelSlider').slider("moveTo", 0);
}

function fuelDontMindClicked() {
    fuelDontMind = false;
    bindFuel();
    setFuelDontMind();
    GetContenders();
}

function onFuelChanged(e, ui) {
    var seats = $('#fuelSlider').slider("value");
    if (seats > 1) {
        setFuelDontMindUnselected();
    }
    else {
        setFuelDontMind();
    }
    GetContenders();
}

function setFuelDontMindUnselected() {
    fuelDontMind = false;
    // then unselect the dont mind
    $('#fuelDontMind div:nth-child(1)').removeClass('boxselected').addClass('box');
    $('#fuelDontMind div:nth-child(2)').removeClass('labelselected').addClass('label');
    // and bind its click event
    $('#fuelDontMind').click(function() {
        fuelDontMindClicked();
    });
}

function setFuelDontMind() {
    fuelDontMind = true;
    $('#fuelDontMind div:nth-child(1)').removeClass('box').addClass('boxselected');
    $('#fuelDontMind div:nth-child(2)').removeClass('label').addClass('labelselected');
    // unbind its click event
    $('#fuelDontMind').unbind('click');
}

// #########
// GREEN

function bindGreen() {
    $('#greenSlider').slider("moveTo", 0);
}

function greenDontMindClicked() {
    greenDontMind = false;
    bindGreen();
    setGreenDontMind();
    GetContenders();
}

function onGreenChanged(e, ui) {
    var green = $('#greenSlider').slider("value");
    if (green > 0) {
        setGreenDontMindUnselected();
    }
    else {
        setGreenDontMind();
    }
    GetContenders();
}

function setGreenDontMindUnselected() {
    greenDontMind = false;
    // then unselect the dont mind
    $('#greenDontMind div:nth-child(1)').removeClass('boxselected').addClass('box');
    $('#greenDontMind div:nth-child(2)').removeClass('labelselected').addClass('label');
    // and bind its click event
    $('#greenDontMind').click(function() {
        greenDontMindClicked();
    });
}

function setGreenDontMind() {
    greenDontMind = true;
    $('#greenDontMind div:nth-child(1)').removeClass('box').addClass('boxselected');
    $('#greenDontMind div:nth-child(2)').removeClass('label').addClass('labelselected');
    // unbind its click event
    $('#greenDontMind').unbind('click');
}

// #########
// SPEED

function bindSpeed() {
    $('#speedSlider').slider("moveTo", 1);
}

function speedDontMindClicked() {
    speedDontMind = false;
    bindSpeed();
    setSpeedDontMind();
    GetContenders();
}

function onSpeedChanged(e, ui) {
    var speed = $('#speedSlider').slider("value");
    if (speed > 0) {
        setSpeedDontMindUnselected();
    }
    else {
        setSpeedDontMind();
    }
    GetContenders();
}

function setSpeedDontMindUnselected() {
    speedDontMind = false;
    // then unselect the dont mind
    $('#speedDontMind div:nth-child(1)').removeClass('boxselected').addClass('box');
    $('#speedDontMind div:nth-child(2)').removeClass('labelselected').addClass('label');
    // and bind its click event
    $('#speedDontMind').click(function() {
        speedDontMindClicked();
    });
}

function setSpeedDontMind() {
    speedDontMind = true;
    $('#speedDontMind div:nth-child(1)').removeClass('box').addClass('boxselected');
    $('#speedDontMind div:nth-child(2)').removeClass('label').addClass('labelselected');
    // unbind its click event
    $('#speedDontMind').unbind('click');
}

// ################
// ENTER POSTCODE
//function submitPostcode() {
//    var tbPostcode = $get("postcode");
//    distance = $get("distance").value;
//    if (tbPostcode.value.length > 0) {
//        postcode = tbPostcode.value;
//        GetEastingAndNorthing(tbPostcode.value, onGetEastingAndNorthingSuccess, onGetEastingAndNorthingFailure);
//    }
//    else {
//        displayError("Please enter a postcode");
//    }
//}

//function onGetEastingAndNorthingSuccess(result) {
//    // if the postcode is valid
//    if (result) {

//        $('.overlay').fadeOutOneByOne();
//        $('#centrePanel').addClass("active");

//        // hide the postcodequestion
//            $('#contenderscount').fadeIn('slow');
//    }
//    else {
//        displayError("The postcode is invalid!");
//    }
//}


// #########
// CONTENDERS
function GetContenders() {
    if (bDisableSearch) return;
    var paramsSelected = numberParamsSelected();
    if (paramsSelected >= 3) {

        // create some arrays to store the values that we choose
        names = new Array();
        values = new Array();

        if (!priceDontMind) {
            // get the values out of the controls
            if ($('#priceSlider').slider("value", 1) > 0) {
                names[names.length] = "lpriceMin";
                values[values.length] = $('#priceSlider').slider("value", 0);
            }
            if ($('#priceSlider').slider("value", 1) < 55000) {
                names[names.length] = "lpriceMax";
                values[values.length] = $('#priceSlider').slider("value", 1);
            }
        }

        if (!wantDontMind) {
            var wants = buildWantList();
            if (wants.length > 0) {
                names[names.length] = "liwant";
                values[values.length] = wants;
            }
        }

        if (!seatsDontMind) {
            names[names.length] = "licarry";
            values[values.length] = $('#seatsSlider').slider("value", 0);
        }

        if (!spaceDontMind) {
            var space = buildSpace();
            if (space.length > 0) {
                names[names.length] = "lspace";
                values[values.length] = space;
            }
        }

        if (!fuelDontMind) {
            names[names.length] = "lfuel";
            values[values.length] = $('#fuelSlider').slider("value", 0);
        }

        if (!greenDontMind) {
            names[names.length] = "lgreen";
            var greenValue = $('#greenSlider').slider("value", 0);
            greenValue = Math.abs(greenValue - 100)
            values[values.length] = greenValue;
        }

        if (!speedDontMind) {
            names[names.length] = "lspeed";
            var speedValue = $('#speedSlider').slider("value", 0);
            speedValue = Math.abs(speedValue - 19)
            values[values.length] = speedValue;
        }

        if (IsStringValid(distance)) distance = $get("distance").value;
        if (IsStringValid(postcode)) postcode = $get("postcode").value;


        //ensure colours are last in the param list
        if (!coloursDontMind) {
            var colours = buildColoursList();
            if (colours.length > 0) {
                names[names.length] = "lcolours";
                values[values.length] = colours;
            }
        }
        // show that were getting results
        $('#contenderscount').fadeOut('fast', function() {
            $('#gettingresults').fadeIn('fast', function() {
                GetLifeStyleContenders(names, values,postcode,distance, onGetContendersSuceeded, onGetContendersFailed);
            });
        }); 
    }
    else {
        // there are less than 3 so inform user to choose some more
        var contendersDiv = $get('contenders');
        contendersDiv.innerHTML = "Answer <b>" + (3 - paramsSelected) + " or more questions</b> to find your top contenders.";
    }

    $('#showTheContenders').fadeTo("fast", 0.3);
}
var lifestylequeryparams;
function onGetContendersSuceeded(results) {
    noContenders = results.Count;
    lifestylequeryparams = results.LifeStyleQueryParams;
    // show that were getting results
    $('#gettingresults').fadeOut('fast', function() {
        var contendersDiv = $get('contenders');
        var contendersContent = "You now have<br><b>" + noContenders + " contenders</b>";
        if (noContenders != "0") {
            contendersContent += "<br /><img src='" + StaticContentRoot + "images/lifestyle/letsviewthem.gif' />";
        }
        contendersDiv.innerHTML = contendersContent;

        $('#contenderscount').fadeIn('fast');
    });

    // enable the findNow button depending upon whether there are any contenders
    if (noContenders > 0) {
        $('#matchingContenders').slideDown('normal');
        $('#showTheContenders').fadeTo("fast", 1);

            $('#contenders').click(function() {
                showTheResults();
            });

        $('#showTheContenders').click(function() {
            showTheResults();
        });
    }
    else {
        $('#showTheContenders').unbind('click');
    }
}

function onGetContendersFailed() {
    displayGenericError();
}

function showTheResults() {
    // need to check the postcode and validate it
    var url = BuildJSUrl() + "lifestyle/models?" + lifestylequeryparams;
    //append dist and postcode
    var ps = $('#postcode').val();
    var ds = $('#distance').val();
    if (IsStringValid(ps)) {
        url = url + "&st=postcode&sv=" + ps
    }
    if (IsStringValid(ds)) {
        url = url + "&ds=" + ds;
    }
    RedirectJSUrl(url);
}

function doRedirect(result) {
    window.location.href = result;
}


// ################
// BUILD SELECTIONS
function buildWantList() {
    // currently only one can be selected so this 
    var iWant = "";
    $('.wantselected').each(function() {
        iWant += "," + $(this).attr("id");
    });
    return iWant.substr(1);
}

function buildSpace() {
    // this has been requested as a multiple selection?
    var space = "";
    $('.spaceselected')
        .each(function() {
            space += "," + $(this).attr("id");
        });
    return space.substr(1);
}

function buildColoursList() {
    var colours = "";
    $('.colourselected')
        .each(function() {
            colours += "|" + $(this).attr("id");
        });
    return colours.substr(1);
}

function numberParamsSelected() {
    var noSelected = 0;
    if (!priceDontMind) ++noSelected;
    if (!wantDontMind) ++noSelected;
    if (!seatsDontMind) ++noSelected;
    if (!spaceDontMind) ++noSelected;
    if (!coloursDontMind) ++noSelected;
    if (!fuelDontMind) ++noSelected;
    if (!greenDontMind) ++noSelected;
    if (!speedDontMind) ++noSelected;
    return noSelected;
}

function displayError(message) {
    var errorMsg = $get("errorMessage");
    errorMsg.style.display = 'block';
    errorMsg.className = 'errormessage';
    errorMsg.innerHTML = '<span class="lifestyle">' + message + '</span>';
}

function onGetEastingAndNorthingFailure() {
    displayGenericError();
}