﻿var userDomain;
var locationsScroller;
var keyphrasesScroller;
var clickedLocations = new Array();
var clickedKeywords = new Array();
var submittedLocations = new Array();
var submittedKeyPhrases = new Array();
var updatedLocations = new Array();
var runningTotal = 0.0;
var currHelp = 1;
var totalKeyphrases = 0;
var totalLocations = 0
var lastLocationID = "";
var currentLocationID = "";
var lastRange = 5;
var currentRange = 5;
var overwriteLocation = false;
var quoteRef = "";
var empRef = "";
var cusName = "";
var cusEmail = "";
var isUpdate = false;

window.onload = function () {
    // get the user domain for use with the handlers
    userDomain = "http://" + window.location.host + "/resources/Handlers/KeyphraseDemo";
    // Create a panel scroller
    locationsScroller = Scroller("locationsContainer", "locations", -30);
    keyphrasesScroller = Scroller("keyphrasesContainer", "keyphrases", -30);
    if (window.location.search != "") {
        var queryString = "";
        if (window.location.search.indexOf("&") > -1) {
            queryString = window.location.search.split("&");
            quoteRef = queryString[0].split("=")[1];
            empRef = queryString[1].split("=")[1];
        }
        else {
            quoteRef = window.location.search.split("=")[1];
        }
        if (empRef != "") {
            document.getElementById('referrerCodeInput').setAttribute("readonly", "readonly");
            document.getElementById('referrerCodeInput').value = empRef;
        }
        else {
            document.getElementById('emailPanel').style.height = "260px";
            document.getElementById('emailMainLabel').innerHTML = "Update your estimate";
            // hide the send button
            document.getElementById('emailSendButton').style.height = "0px";
            var updateButton = document.createElement("div");
            updateButton.setAttribute("id", "updateButton");
            updateButton.setAttribute("onclick", "sendEmail();");
            document.getElementById('leftPanel').appendChild(updateButton);
        }
        if (quoteRef != "") {
            isUpdate = true;
            var d = new Date();
            var time = d.getTime();
            var strURL = userDomain + "/getQuote.ashx?ref=" + quoteRef + "&d=" + time;
            $.get(strURL, function (data) {
                if (data != "") {
                    var temp = data.split("~");
                    cusName = temp[4];
                    cusEmail = temp[5];
                    document.getElementById('emailNameInput').value = cusName;
                    document.getElementById('emailAddressInput').value = cusEmail;
                    clickedKeywords = temp[0].split("^");
                    document.getElementById('selectedKeywords').innerHTML = clickedKeywords.length;
                    clickedLocations = temp[1].split("^");
                    submittedLocations = temp[2].split("^");
                    for (var i = 0; i < submittedLocations.length; i++) {
                        currentRange = parseInt(submittedLocations[i].split(",")[1], 10);
                        lastRange = currentRange;
                        var locID = submittedLocations[i].split(",")[0];
                        getMajorLocations(locID, true);
                    }
                    submittedKeyPhrases = temp[3].split("^");
                    for (var j = 0; j < submittedKeyPhrases.length; j++) {
                        var keyID = submittedKeyPhrases[j].split(",")[0];
                        var keyText = submittedKeyPhrases[j].split(",")[1];
                        var tempElem = document.createElement("div");
                        var d = new Date();
                        var time = d.getTime();
                        var strURL = userDomain + "/getKeyPhrases.ashx?search=" + keyText.replace(/ /gi, ",") + "&d=" + time;

                        jQuery.ajax({
                            url: strURL,
                            success: function (result) {
                                tempElem.innerHTML = result;
                                addMasterKeyPhrase(tempElem, keyID, keyText, true);
                            },
                            async: false
                        });
                    }
                    calculateResults();
                }
            });
        }
    }
};

function setRange(elem) {
    if (IsNumeric(elem.value)) {
        currentRange = parseInt(elem.value, 10);
    }
    else {
        elem.value = lastRange;
    }
}

function getKeyphrases(elem) {
    // call the get keywords handler to return a list of keywords related to the submitted text
    // and populate them into the drop down list for selection
    var text = elem.value;
    if (text.length > 1) {
        var tempWords = text.split(" ");
        var textToSearch = ""
        for (var i = 0; i < tempWords.length; i++) {
            if (tempWords[i].length > 1) {
                textToSearch += tempWords[i] + " ";
            }
        }
        if (textToSearch != "") {
            elem.style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/loading.gif')";
            var d = new Date();
            var time = d.getTime();
            var strURL = userDomain + "/getKeyPhrases.ashx?search=" + textToSearch + "&d=" + time;
            $.get(strURL, function (data) {
                if (data != "locNotFound") {
                    if (elem.id == "keyphraseSearchInput2") {
                        document.getElementById('keyphrasesContainer').style.top = "1056px";
                        $('html').animate({
                            scrollTop: document.getElementById('combinationResultsPanel').offsetTop
                        }, 500);
                    }
                    else {
                        document.getElementById('keyphrasesContainer').style.top = "97px";
                    }
                    document.getElementById('keyphrases').innerHTML = data;
                    document.getElementById('keyphrasesContainer').style.display = "inline";
                    keyphrasesScroller.setScrollHeight();
                }
                elem.style.backgroundImage = "none";
            });
        }
    }
}

function addMasterKeyPhrase(elem, id, text, revisit) {
    // before we add a new keyphrase group we need to hide the previously added ones
    var keyPhraseResults = document.getElementById('keywordsResults');
    for (var i2 = 0; i2 < keyPhraseResults.childNodes.length; i2++) {
        if (keyPhraseResults.childNodes[i2].className == "keyPhrasesContainer") {
            var subPanel = keyPhraseResults.childNodes[i2];
            subPanel.style.height = "0px";
            subPanel.previousSibling.childNodes[2].className = "subDivMoreView phrases";
        }
    }
    var keyPhraseContainer;
    // get the keyphrase that was clicked in the drop down list, add it to the local array
    if (!revisit) {
        document.getElementById('keyphraseSearchInput').value = text;
        keyPhraseContainer = document.getElementById('keyphrases');
        clickedKeywords.push(id + "," + text + "," + elem.getAttribute("price") + "," + id);
        keyPhraseContainer.removeChild(elem);
    }
    else {
        keyPhraseContainer = elem;
    }
    var masterPhrasePanel = "<div class=\"keyPhrasesHeader\">" +
        "<div class=\"removeButton\" onclick=\"removeMasterKeyPhrase(this, '" + id + "')\"></div>" +
        "<div class=\"keyPhrasesName\">" + text + "</div>" +
        "<div class=\"subDivMoreHide phrases\" style=\"color:#000000; text-indent:60px;\" onclick=\"showKeyphrases(this, 'kPhrase-" + id + "');\">" + keyPhraseContainer.childNodes.length + " phrases available</div>" +
        "</div>";
    if (!revisit) {
        masterPhrasePanel += "<div id=\"kPhrase-" + id + "\" class=\"keyPhrasesContainer\" style=\"height:" + (23 * keyPhraseContainer.childNodes.length) + "px;\">";
    }
    else {
        masterPhrasePanel += "<div id=\"kPhrase-" + id + "\" class=\"keyPhrasesContainer\" style=\"height:" + (23 * (keyPhraseContainer.childNodes.length - 1)) + "px;\">";
    }
    for (var i = 0; i < keyPhraseContainer.childNodes.length; i++) {
        var subPanel2 = keyPhraseContainer.childNodes[i];
        if (subPanel2.id.replace("phrase-", "") != id) {
            masterPhrasePanel += "<div id=\"" + subPanel2.id + "\" class=\"keyDiv " + subPanel2.id.replace("phrase-", "") + "\" style=\"background-image:url(http://image.locallinkup.com/keyPhraseSampler/available.gif); color:#929497;\"" +
            " onclick=\"keyphraseClicked(this,'" + subPanel2.id.replace("phrase-", "") + "','" + subPanel2.innerHTML + "','" + subPanel2.getAttribute("price") + "','" + id + "');\">" +
            subPanel2.innerHTML +
            "</div>";
        }
    }
    masterPhrasePanel += "</div>";
    document.getElementById("keywordsResults").innerHTML += masterPhrasePanel;
    totalKeyphrases += keyPhraseContainer.childNodes.length;
    document.getElementById('generatedKeywords').innerHTML = "/" + totalKeyphrases;
    document.getElementById("resultsBackgroundPanel1").style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/key_loc_results_back.gif')";
    document.getElementById('keyphrasesContainer').style.display = "none";
    keyphrasesScroller.setScrollVisible("none");
    if (!revisit) {
        if (clickedLocations.length > 0) {
            calculateResults();
        }
    }
    else {
        selectDeselectInitialKeyPhrases();
    }
}

function removeMasterKeyPhrase(elem, id) {
    var keyPhraseContainer = elem.parentNode.nextSibling;
    for (var i = 0; i < keyPhraseContainer.childNodes.length; i++) {
        var phraseID = keyPhraseContainer.childNodes[i].id.split("-")[1];
        for (var j = 0; j < clickedKeywords.length; j++) {
            var clickedPhraseID = clickedKeywords[j].split(",")[0];
            if (phraseID == clickedPhraseID) {
                clickedKeywords.splice(j, 1);
                j--;
            }
            if (id == clickedPhraseID) {
                clickedKeywords.splice(j, 1);
                j--;
            }
        }
    }
    if (clickedLocations.length > 0) {
        calculateResults();
    }
    keyPhraseContainer.parentNode.removeChild(keyPhraseContainer);
    elem.parentNode.parentNode.removeChild(elem.parentNode);
}

function keyphraseClicked(elem, phraseID, phrase, price, masterID) {
    // if this element is not currently selected
    if (elem.style.backgroundImage.indexOf("available") > -1) {
        // add the clicked keyword the local array
        clickedKeywords.push(phraseID + "," + phrase + "," + price + "," + masterID);
        document.getElementById('selectedKeywords').innerHTML = clickedKeywords.length;
        // change the image to the chosen image
        elem.style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/chosen.gif')";
        // change the class to show the right colour of text
        elem.style.color = "#000000";
    }
    // if this element is currently selected
    else {
        // remove the clicked keyword the local array
        for (var i = 0; i < clickedKeywords.length; i++) {
            if (clickedKeywords[i] == phraseID + "," + phrase + "," + price + "," + masterID) {
                clickedKeywords.splice(i, 1);
                document.getElementById('selectedKeywords').innerHTML = clickedKeywords.length;
            }
        }
        // change the image to the available image
        elem.style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/available.gif')";
        // change the class to show the right colour of text
        elem.style.color = "#929497";
    }
    if (clickedLocations.length > 0) {
        calculateResults();
    }
}

function showKeyphrases(elem, id) {
    // show or hide the key phrases sub panel
    var subPanel = document.getElementById(id);
    if (subPanel.offsetHeight < 5) {
        $(subPanel).animate({ height: ((subPanel.childNodes.length * 23) - 1) + "px" }, 1000);
        elem.className = "subDivMoreHide phrases";
    }
    else {
        $(subPanel).animate({ height: "0px" }, 1000);
        elem.className = "subDivMoreView phrases";
    }
}

function getLocations(elem) {
    var text = elem.value;
    if (text != "") {
        if (text.length > 3) {
            // call the get locations handler to return a list of location related to the submitted text
            // and populate them into the drop down list for selection
            var d = new Date();
            var time = d.getTime();
            document.getElementById('locationSearchInput').style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/loading.gif')";
            var strURL = userDomain + "/getLocations.ashx?search=" + text + "&d=" + time;
            $.get(strURL, function (data) {
                if (data != "locNotFound") {
                    document.getElementById('locations').innerHTML = data;
                    document.getElementById('locationsContainer').style.display = "inline";
                    locationsScroller.setScrollHeight();
                }
                document.getElementById('locationSearchInput').style.backgroundImage = "none";
            });
        }
    }
}

function adLocation(elem) {
    // set the text in the search box, hide the selection list and call getMajorLocations to get them
    document.getElementById('locationSearchInput').value = elem.innerHTML;
    document.getElementById('locationsContainer').style.display = "none";
    locationsScroller.setScrollVisible("none");
    currentLocationID = elem.id.split("-")[1];
}

function searchLocations() {
    if (currentLocationID != "") {
        var locationSubmitted = false;
        for (var i = 0; i < submittedLocations.length; i++) {
            if (submittedLocations[i] == currentLocationID) {
                locationSubmitted = true;
            }
        }
        if (!locationSubmitted) {
            submittedLocations.push(currentLocationID);
            getMajorLocations(currentLocationID, false);
        }
        else {
            if (currentRange != lastRange) {
                var locResultsPanel = document.getElementById('locationsResults');
                var tempLocCount = 0;
                for (var j = 0; j < locResultsPanel.childNodes.length; j++) {
                    if (locResultsPanel.childNodes[j].className != null) {
                        if (locResultsPanel.childNodes[j].className.indexOf("majors") > -1) {
                            if (parseInt(locResultsPanel.childNodes[j].getAttribute("count")) > tempLocCount) {
                                tempLocCount = parseInt(locResultsPanel.childNodes[j].getAttribute("count"));
                            }
                            locResultsPanel.childNodes[j].parentNode.removeChild(locResultsPanel.childNodes[i]);
                            i--;
                        }
                    }
                }
                totalLocations -= tempLocCount;
                document.getElementById('generatedLocations').innerHTML = "/" + totalLocations;
                getMajorLocations(currentLocationID, false);
            }
        }
    }
}

function getMajorLocations(locationID, revisit) {
    // show the loading animation and get the major loactions
    document.getElementById('locationSearchInput').style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/loading.gif')";
    var d = new Date();
    var time = d.getTime();
    var strURL = userDomain + "/getMajorLocations.ashx?placeid=" + locationID + "&range=" + currentRange + "&d=" + time;
    $.get(strURL, function (datab) {
        // if this is an update due to change of distance then we need to move the clicked locations from the previous search into a temporary array
        if (lastRange != currentRange) {
            updatedLocations = new Array();
            for (var j = 0; j < clickedLocations.length; j++) {
                var tempContents = clickedLocations[j].split(",");
                if (tempContents[3] == currentLocationID) {
                    if (tempContents[0] != currentLocationID) {
                        updatedLocations.push(clickedLocations[j]);
                    }
                    clickedLocations.splice(j, 1);
                    j--;
                }
            }
        }
        var newLocsList;
        // count used to show how many keyphrases were returned, shown underneath the results panel
        var tempArray = datab.split("^^");
        totalLocations += parseInt(tempArray[0], 10);
        document.getElementById('generatedLocations').innerHTML = "/" + totalLocations;
        // break up the return value into its 2 or 3 components
        if (tempArray.length == 4) {
            if (!revisit) {
                //  populate the stored locations array initially with the master location that was selected earlier
                clickedLocations.push(tempArray[1]);
            }
            // add the results to the results panel
            document.getElementById("locationsResults").innerHTML += tempArray[2];
            newLocsList = tempArray[3].split(",");
        }
        else {
            // add the results to the results panel
            document.getElementById("locationsResults").innerHTML += tempArray[1];
            newLocsList = tempArray[2].split(",");
        }
        // change the background image on the results panel
        document.getElementById("resultsBackgroundPanel2").style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/key_loc_results_back.gif')";
        document.getElementById('selectedLocations').innerHTML = clickedLocations.length;
        document.getElementById('locationSearchInput').style.backgroundImage = "none";
        if (lastRange != currentRange) {
            var tempCounter = 0;
            // if this is an update due to change of distance now wee need to readd any matching locations from the new search that macth locations selected in the old search
            // adjust the click locations list to contain locations from the previous search
            for (var i = 0; i < newLocsList.length; i++) {
                for (var k = 0; k < updatedLocations.length; k++) {
                    var tempContents2 = updatedLocations[k].split(",");
                    if (newLocsList[i] == tempContents2[0]) {
                        clickedLocations.push(updatedLocations[k]);
                        updatedLocations.splice(k, 1);
                        tempCounter++;
                    }
                }
            }
            lastRange = currentRange;
        }
        document.getElementById('selectedLocations').innerHTML = clickedLocations.length;
        if (!revisit) {
            if (clickedKeywords.length > 0) {
                calculateResults();
            }
        }
        else {
            selectDeselectInitialLocations();
        }
    });
}

function selectDeselectInitialLocations() {
    var locationsResultsPanel = document.getElementById('locationsResults');
    for (var i = 0; i < clickedLocations.length; i++) {
        var idToFind = clickedLocations[i].split(',')[0];
        for (var j = 0; j < locationsResultsPanel.childNodes.length; j++) {
            var mainPanel = locationsResultsPanel.childNodes[j];
            if (mainPanel.className.indexOf("locDivBig") == 0) {
                var majorTownPanel = mainPanel.childNodes[0];
                if (majorTownPanel.className.indexOf(idToFind) > -1) {
                    //change the image to the chosen image
                    majorTownPanel.style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/chosen.gif')";
                    // change the class to show the right colour of text
                    majorTownPanel.style.color = "#000000";
                }
                if (majorTownPanel.className.indexOf("subDivMinors") > -1) {
                    for (var k = 0; k < majorTownPanel.childNodes.length; k++) {
                        var subPanel = majorTownPanel.childNodes[k];
                        if (subPanel.className.indexOf(idToFind) > -1) {
                            //change the image to the chosen image
                            subPanel.style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/chosen.gif')";
                            // change the class to show the right colour of text
                            subPanel.style.color = "#000000";
                        }
                    }
                }
            }
        }
    }




    for (var l = 0; l < clickedLocations.length; l++) {
        var classToFind = "minorTown" + clickedLocations[l].split(',')[0];
        $("." + classToFind).each(function () {
            // change the image to the chosen image
            this.style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/chosen.gif')";
            // change the class to show the right colour of text
            this.style.color = "#000000";
        });
    }
}

function selectDeselectInitialKeyPhrases() {
    var keywordsResultsPanel = document.getElementById('keywordsResults');
    for (var i = 0; i < clickedKeywords.length; i++) {
        var idToFind = clickedKeywords[i].split(',')[0];
        for (var j = 0; j < keywordsResultsPanel.childNodes.length; j++) {
            var mainPanel = keywordsResultsPanel.childNodes[j];
            if (mainPanel.className == "keyPhrasesContainer") {
                for (var k = 0; k < mainPanel.childNodes.length; k++) {
                    var subPanel = mainPanel.childNodes[k];
                    if (subPanel.className.indexOf(idToFind) > -1) {
                        //change the image to the chosen image
                        subPanel.style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/chosen.gif')";
                        // change the class to show the right colour of text
                        subPanel.style.color = "#000000";
                    }
                }
            }
        }
    }
}

function removeMajorLocation(elem, placeID) {
    var majorLocID = elem.parentNode.className.split(" ")[1].replace("majors", ""); // locDivBig majors14066
    var locsResultsPanel = elem.parentNode.parentNode;
    for (var h = 0; h < locsResultsPanel.childNodes.length; h++) {
        var majorPanel = locsResultsPanel.childNodes[h];
        if (majorPanel.className.indexOf("locDivBig") == 0) {
            var majorPanelID = majorPanel.className.split(" ")[1].replace("majors", "");
            if (majorPanelID == majorLocID) {
                var locationsContainer = majorPanel.nextSibling;
                if (locationsContainer.childNodes.length > 0) {
                    for (var i = 0; i < locationsContainer.childNodes.length; i++) {
                        var locID = locationsContainer.childNodes[i].id.split("-")[1];
                        for (var j = 0; j < clickedLocations.length; j++) {
                            var clickedLocID = clickedLocations[j].split(",")[0];
                            if (locID == clickedLocID) {
                                clickedLocations.splice(j, 1);
                                j--;
                            }
                            if (placeID == clickedLocID) {
                                clickedLocations.splice(j, 1);
                                j--;
                            }
                        }
                    }
                }
                else {
                    for (var k = 0; k < clickedLocations.length; k++) {
                        var clickedLocID2 = clickedLocations[k].split(",")[0];
                        if (placeID == clickedLocID2) {
                            clickedLocations.splice(k, 1);
                            k--;
                        }
                    }
                }
                locationsContainer.parentNode.removeChild(locationsContainer);
                majorPanel.parentNode.removeChild(majorPanel);
                h--;
            }
        }
    }
    if (clickedKeywords.length > 0) {
        calculateResults();
    }
}

function showMinors(elem, id, range) {
    // when a major show more button is clicked
    var subPanel = document.getElementById(id);
    // if the minor list is already populated, show it
    if (subPanel.childNodes.length > 0) {
        if (subPanel.offsetHeight < 5) {
            $(subPanel).animate({ height: ((subPanel.childNodes.length * 23) - 1) + "px" }, 500);
            elem.className = "subDivMoreHide";
        }
        else {
            $(subPanel).animate({ height: "0px" }, 500);
            elem.className = "subDivMoreView";
        }
    }
    // if the minor panel isn't yet populated, populate it first and then show it
    else {
        var placeID = id.replace("minors", "");
        var d = new Date();
        var time = d.getTime();
        var strURL = userDomain + "/getMinorLocations.ashx?placeid=" + placeID + "&parentID=" + subPanel.className.replace("subDivMinors majors", "") + "&range=" + range + "&d=" + time;
        $.get(strURL, function (data) {
            subPanel.innerHTML = data;
            $(subPanel).animate({ height: ((subPanel.childNodes.length * 23) - 1) + "px" }, 1000);
            elem.className = "subDivMoreHide";
            selectDeselectInitialLocations();
        });
    }
}

function locationClicked(elem, loc, locID, price, parentID, range) {
    // if this element is not currently selected
    if (elem.style.backgroundImage.indexOf("available") > -1) {
        // add the clicked location the local array
        clickedLocations.push(locID + "," + loc + "," + price + "," + parentID + "," + range);
        document.getElementById('selectedLocations').innerHTML = clickedLocations.length;
        // change the image to the chosen image
        elem.style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/chosen.gif')";
        // change the class to show the right colour of text
        elem.style.color = "#000000";
    }
    // if this element is currently selected
    else {
        // remove the clicked location the local array
        for (var i = 0; i < clickedLocations.length; i++) {
            if (clickedLocations[i] == locID + "," + loc + "," + price + "," + parentID + "," + range) {
                clickedLocations.splice(i, 1);
                document.getElementById('selectedLocations').innerHTML = clickedLocations.length;
            }
        }
        // change the image to the available image
        elem.style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/available.gif')";
        // change the class to show the right colour of text
        elem.style.color = "#929497";
    }
    if (clickedKeywords.length > 0) {
        calculateResults();
    }
}

function calculateResults() {
    runningTotal = 0.0;
    // show the appropriate help text
    showHelp(3);
    $('html').animate({
        scrollTop: document.getElementById('combinationResultsPanel').offsetTop
    }, 500);
    document.getElementById("combinationResultsOuterPanel").style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/combi_results_back.gif')";
    // calculate the totals according to the selected elements (as they are clicked)
    var results = "";
    document.getElementById('totalKeyPhrases').innerHTML = clickedLocations.length * (clickedKeywords.length * 3);
    document.getElementById('emailPhrasesChosen').innerHTML = clickedLocations.length * (clickedKeywords.length * 3);
    document.getElementById('totalKeyPhrasesGenerated').innerHTML = "/" + clickedLocations.length * (clickedKeywords.length * 3);
    // generate the individual group panels to put in the final results panel
    for (var i = 0; i < clickedLocations.length; i++) {
        for (var j = 0; j < clickedKeywords.length; j++) {
            var indiCost = Math.round((parseFloat(clickedLocations[i].split(",")[2]) * parseFloat(clickedKeywords[j].split(",")[2])) * 100) / 100;
            if (indiCost < 0.10) {
                indiCost = 0.10;
            }
            var indiCostText = formatFloat(indiCost.toString());

            var groupTotalCost = Math.round((indiCost * 3) * 100) / 100;
            runningTotal += groupTotalCost;
            var groupTotalCostText = groupTotalCost.toString();
            groupTotalCostText = formatFloat(groupTotalCostText);
            results += "<div id=\"" + clickedLocations[i].split(",")[0] + "^^" + clickedKeywords[j].split(",")[0] + "^^" + clickedLocations[i].split(",")[3] + "^^" + clickedKeywords[j].split(",")[3] + "^^" + clickedLocations[i].split(",")[4] + "\" class=\"groupPanel\">" +
                "<div id=\"arrow" + i + j + "\" class=\"openArrow\" onclick=\"showSubGroup(this.parentNode, '" + i + j + "')\"></div>" +
                "<div class=\"removeGroupButton\" onclick=\"removeGroup(this.parentNode, '" + groupTotalCostText + "', '" + clickedLocations[i].split(",")[1] + "', '" + clickedKeywords[j].split(",")[1] + "')\"></div>" +
                "<div class=\"baseText\" onclick=\"showSubGroup(this.parentNode, '" + i + j + "')\">" + clickedLocations[i].split(",")[1] + " - " + clickedKeywords[j].split(",")[1] + "</div>" +
                "<div id=\"groupCost" + i + j + "\"class=\"baseCost\">£" + groupTotalCostText + "</div>" +
                "<div class=\"mainSubGroupPanel\">" +
                "<div class=\"subGroupPanel\" style=\"border-bottom:1px solid #929497; border-top:1px solid #929497;\">" +
                "<div class=\"baseButton\" onclick=\"addRemSubGroup(this, '" + indiCostText + "', '" + i + j + "')\" style=\"background-image:url('http://image.locallinkup.com/keyPhraseSampler/chosen.gif');\"></div>" +
                "<div class=\"baseTextSub\">" + clickedKeywords[j].split(",")[1] + " in " + clickedLocations[i].split(",")[1] + "</div>" +
                "<div class=\"baseCostSub\">£" + indiCostText + "</div>" +
                "</div>" +
                "<div class=\"subGroupPanel\" style=\"border-bottom:1px solid #929497;\">" +
                "<div class=\"baseButton\" onclick=\"addRemSubGroup(this, '" + indiCostText + "', '" + i + j + "')\" style=\"background-image:url('http://image.locallinkup.com/keyPhraseSampler/chosen.gif');\"></div>" +
                "<div class=\"baseTextSub\">" + clickedKeywords[j].split(",")[1] + " " + clickedLocations[i].split(",")[1] + "</div>" +
                "<div class=\"baseCostSub\">£" + indiCostText + "</div>" +
                "</div>" +
                "<div class=\"subGroupPanel\">" +
                "<div class=\"baseButton\" onclick=\"addRemSubGroup(this, '" + indiCostText + "', '" + i + j + "')\" style=\"background-image:url('http://image.locallinkup.com/keyPhraseSampler/chosen.gif');\"></div>" +
                "<div class=\"baseTextSub\">" + clickedLocations[i].split(",")[1] + " " + clickedKeywords[j].split(",")[1] + "</div>" +
                "<div class=\"baseCostSub\">£" + indiCostText + "</div>" +
                "</div>" +
                "</div></div>";
        }
    }
    // add the new panels
    document.getElementById('combinationResults').innerHTML = results;
    // update the totals in the bottom panel
    var runningTotalText = (Math.round(runningTotal * 100) / 100).toString();
    runningTotalText = formatFloat(runningTotalText);
    var cappedTotalText = (Math.round((runningTotal * 0.25) * 100) / 100).toString();
    cappedTotalText = formatFloat(cappedTotalText);
    document.getElementById('KeyPhrasesTotalCost').innerHTML = "£" + runningTotalText;
    document.getElementById('KeyPhrasesCost').innerHTML = "£" + cappedTotalText;
    document.getElementById('emailMaximumCost').innerHTML = "£" + runningTotalText;
    document.getElementById('emailTotalCost').innerHTML = "£" + cappedTotalText;
}

function showSubGroup(elem, index) {
    // show or hide the sub panels hidden inside the main results group panels
    if (elem.offsetHeight < 30) {
        document.getElementById('arrow' + index).className = "closeArrow";
        $(elem).animate({ height: "99px" }, 500);
    }
    else {
        document.getElementById('arrow' + index).className = "openArrow";
        $(elem).animate({ height: "24px" }, 500);
    }
}

function addRemSubGroup(elem, cost, index) {
    // add or remove a sub group to the totals and set the background image acordingly
    var currentCost = parseFloat(document.getElementById('groupCost' + index).innerHTML.replace("£", ""));
    var costToAddRem = parseFloat(cost);
    var newCost = 0.0;
    var cappedTotalText = "";
    var currTotal = parseInt(document.getElementById('totalKeyPhrases').innerHTML, 10);
    // if it's already selected, remove it
    if (elem.style.backgroundImage.indexOf('chosen') > -1) {
        elem.style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/available.gif')";
        elem.style.color = "#000000";
        newCost = Math.round((currentCost - costToAddRem) * 100) / 100;
        runningTotal = Math.round((runningTotal - costToAddRem) * 100) / 100;
        cappedTotalText = (Math.round((runningTotal * 0.25) * 100) / 100).toString();
        var newTotal = currTotal - 1;
        document.getElementById('totalKeyPhrases').innerHTML = newTotal;
    }
    // if it's available add it
    else {
        elem.style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/chosen.gif')";
        elem.style.color = "#929497";
        newCost = Math.round((currentCost + costToAddRem) * 100) / 100;
        runningTotal = Math.round((runningTotal + costToAddRem) * 100) / 100;
        cappedTotalText = (Math.round((runningTotal * 0.25) * 100) / 100).toString();
        var newTotal2 = currTotal + 1;
        document.getElementById('totalKeyPhrases').innerHTML = newTotal2;
    }
    // re calculate the totals
    document.getElementById('groupCost' + index).innerHTML = "£" + formatFloat(newCost.toString());
    document.getElementById('KeyPhrasesTotalCost').innerHTML = "£" + formatFloat(runningTotal.toString());
    document.getElementById('KeyPhrasesCost').innerHTML = "£" + formatFloat(cappedTotalText);

    document.getElementById('emailMaximumCost').innerHTML = "£" + formatFloat(runningTotal.toString());
    document.getElementById('emailTotalCost').innerHTML = "£" + formatFloat(cappedTotalText);
}

function removeGroup(elem, groupTotalCost, location, keyword) {
    // to remove a major group when clicked
    var tempSelected = 3;
    var locFound = false;
    var keyFound = false;
    var mainGroup = elem.childNodes[4];
    // get the total number of sub groups that have been selected for this group
    for (var i = 0; i < 3; i++) {
        if (mainGroup.childNodes[i].childNodes[0].style.backgroundImage.indexOf("available") > -1) {
            tempSelected--;
        }
    }
    // reset the totals according to the number of subgroups being removed
    var currentSelectedTotal = parseInt(document.getElementById('totalKeyPhrases').innerHTML, 10);
    var currentGeneratedTotal = parseInt(document.getElementById('totalKeyPhrasesGenerated').innerHTML.replace("/", ""), 10);
    document.getElementById('totalKeyPhrases').innerHTML = currentSelectedTotal - tempSelected;
    document.getElementById('totalKeyPhrasesGenerated').innerHTML = "/" + (currentGeneratedTotal - 3).toString();
    // recalculate the totals
    runningTotal = runningTotal - (parseFloat(groupTotalCost, 10) / 3) * tempSelected;
    var runningTotalText = (Math.round(runningTotal * 100) / 100).toString();
    runningTotalText = formatFloat(runningTotalText);
    var cappedTotalText = (Math.round((runningTotal * 0.25) * 100) / 100).toString();
    cappedTotalText = formatFloat(cappedTotalText);
    document.getElementById('KeyPhrasesTotalCost').innerHTML = "£" + runningTotalText;
    document.getElementById('KeyPhrasesCost').innerHTML = "£" + cappedTotalText;
    document.getElementById('emailMaximumCost').innerHTML = "£" + runningTotalText;
    document.getElementById('emailTotalCost').innerHTML = "£" + cappedTotalText;
    // remove the group
    elem.parentNode.removeChild(elem);
    // firat we need to search the remaining panels and see if there are any using the keypharse or location that we have just removed
    var mainPanel = document.getElementById('combinationResults');
    for (var i2 = 0; i2 < mainPanel.childNodes.length; i2++) {
        if (mainPanel.childNodes[i2].childNodes[2].innerHTML.indexOf(location) > -1) {
            locFound = true;
        }
        if (mainPanel.childNodes[i2].childNodes[2].innerHTML.indexOf(keyword) > -1) {
            keyFound = true;
        }
    }
    // if there are no more elements using the location we can deselect the loaction in the locations panel
    if (!locFound) {
        var locationPanel = document.getElementById('locationsResults');
        for (var i6 = 0; i6 < locationPanel.childNodes.length; i6++) {
            // first we search through the major locations for matches
            if (locationPanel.childNodes[i6].className.indexOf("locDivBig") == 0) {
                if (locationPanel.childNodes[i6].childNodes[0].innerHTML.split(" ")[0] == location) {
                    var searchLocation = document.getElementById('locationSearchInput').value.split(",")[0];
                    if (location != searchLocation) {
                        locationPanel.childNodes[i6].childNodes[0].style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/available.gif')";
                        locationPanel.childNodes[i6].childNodes[0].style.color = "#929497";
                        for (var i8 = 0; i8 < clickedKeywords.length; i8++) {
                            if (clickedLocations[i8].split(",")[1] == location) {
                                if (clickedLocations[i8].split(",")[1] == location) {
                                    clickedLocations.splice(i8, 1);
                                    document.getElementById('selectedLocations').innerHTML = clickedLocations.length;
                                }
                            }
                        }
                    }
                }
            }
            // then we search through the minor locations for matches
            if (locationPanel.childNodes[i6].className.indexOf("subDivMinors") == 0) {
                for (var i7 = 0; i7 < locationPanel.childNodes[i6].childNodes.length; i7++) {
                    var locationsCont = locationPanel.childNodes[i6].childNodes[i7];
                    if (locationsCont.innerHTML == location) {
                        locationsCont.style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/available.gif')";
                        locationsCont.style.color = "#929497";
                        for (var i9 = 0; i9 < clickedKeywords.length; i9++) {
                            if (clickedLocations[i9].split(",")[1] == location) {
                                if (clickedLocations[i9].split(",")[1] == location) {
                                    clickedLocations.splice(i9, 1);
                                    document.getElementById('selectedLocations').innerHTML = clickedLocations.length;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    // if we have not found any matching keyphrase we can set the keyphrase as unselected
    if (!keyFound) {
        var keywordPanel = document.getElementById('keywordsResults');
        for (var i3 = 0; i3 < keywordPanel.childNodes.length; i3++) {
            if (keywordPanel.childNodes[i3].className == "keyPhrasesContainer") {
                var keywordsCont = keywordPanel.childNodes[i3];
                for (var i4 = 0; i4 < keywordsCont.childNodes.length; i4++) {
                    if (keywordsCont.childNodes[i4].innerHTML == keyword) {
                        keywordsCont.childNodes[i4].style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/available.gif')";
                        keywordsCont.childNodes[i4].style.color = "#929497";
                        for (var i5 = 0; i5 < clickedKeywords.length; i5++) {
                            if (clickedKeywords[i5].split(",")[1] == keyword) {
                                clickedKeywords.splice(i5, 1);
                                document.getElementById('selectedKeywords').innerHTML = clickedKeywords.length;
                            }
                        }
                    }
                }
            }
        }
    }
}

/*---------------------------------------------------------------------------------------------------------
Email
---------------------------------------------------------------------------------------------------------*/

function sendEmail() {
    document.getElementById('errorMessage').innerHTML = "";
    document.getElementById('errorMessage').style.color = "#ef3fa8";
    if (document.getElementById('totalKeyPhrases').innerHTML != "0") {
        var name = document.getElementById('emailNameInput').value;
        if (name != "" && name != "Your name here") {
            var address = document.getElementById('emailAddressInput').value;
            if (address != "" && address != "Your email address here" && address.indexOf('@') > -1) {
                var strURL = userDomain + "/emailValidation.ashx";
                $.post(strURL, {
                    domain: address.split("@")[1]
                }, function (data) {
                    if (data == "success") {
                        var text = buildDataToStore();
                        var empRef = "";
                        var empMessage = "";
                        if (document.getElementById('referrerCodeInput').value != "Sales ref") {
                            empRef = document.getElementById('referrerCodeInput').value;
                        }
                        if (document.getElementById('referrerMessageInput').value != "Sales message") {
                            empMessage = document.getElementById('referrerMessageInput').value;
                        }
                        var strURL2 = userDomain + "/sendEmail.ashx";
                        $.post(strURL2, {
                            toName: name,
                            toAddress: address,
                            qutRef: quoteRef,
                            refCode: empRef,
                            refMessage: empMessage,
                            dataToSave: text
                        }, function (data) {
                            if (data == "success") {
                                document.getElementById('errorMessage').style.color = "#8bc53e";
                                if (isUpdate) {
                                    document.getElementById('errorMessage').innerHTML = "Your quote has been updated";
                                }
                                else {
                                    document.getElementById('errorMessage').innerHTML = "Your email has been sent";
                                    document.getElementById('emailNameInput').value = "Your name here";
                                    document.getElementById('emailAddressInput').value = "Your email address here";
                                    document.getElementById('referrerCodeInput').value = "Sales ref";
                                    document.getElementById('referrerMessageInput').value = "Sales message";
                                }
                            }
                            else {
                                document.getElementById('errorMessage').innerHTML = "Failed to send, please contact 01524 230250 or support@locallinkup.com!";
                            }
                        });
                    }
                    else {
                        document.getElementById('errorMessage').innerHTML = "Please enter a valid email address!";
                    }
                });
            }
            else {
                document.getElementById('errorMessage').innerHTML = "Please enter a valid email address!";
            }
        }
        else {
            document.getElementById('errorMessage').innerHTML = "Please enter your name!";
        }
    }
    else {
        document.getElementById('errorMessage').innerHTML = "Please complete the demo first!";
    }
}

function buildDataToStore() {
    //id=\"" + locID+ "^^" + PhraseIS + "^^" + mastLocID + "^^" + mastPrsID + "^^" + range"\"
    // ref, phraseID, placeID, phrase text, indi price, time, mastLoc, mastPhrs, range
    // phraseID + "," + phrase + "," + price + "," + masterID
    // locID + "," + loc + "," + price + "," + parentID + "," + range
    var text = "";
    var mainPanel = document.getElementById('combinationResults');
    for (var i = 0; i < mainPanel.childNodes.length; i++) {
        var groupPanel = mainPanel.childNodes[i];
        var locID = groupPanel.id.split("^^")[0];
        var phraseID = groupPanel.id.split("^^")[1];
        var masterLocID = groupPanel.id.split("^^")[2];
        var masterPhraseID = groupPanel.id.split("^^")[3];
        var range = groupPanel.id.split("^^")[4];
        var subGroupPanel = groupPanel.childNodes[4];
        for (var j = 0; j < subGroupPanel.childNodes.length; j++) {
            var phraseText = subGroupPanel.childNodes[j].childNodes[1].innerHTML;
            var phraseCost = subGroupPanel.childNodes[j].childNodes[2].innerHTML.replace("£", "");
            if (subGroupPanel.childNodes[j].childNodes[0].style.backgroundImage.indexOf("chosen") > -1) {
                var phrasePrice;
                var locMulti;
                for (var k = 0; k < clickedKeywords.length; k++) {
                    if (clickedKeywords[k].split(",")[0] == phraseID) {
                        phrasePrice = clickedKeywords[k].split(",")[2];
                    }
                }
                for (var l = 0; l < clickedLocations.length; l++) {
                    if (clickedLocations[l].split(",")[0] == locID) {
                        locMulti = clickedLocations[l].split(",")[2];
                    }
                }
                text += phraseID + "~" + locID + "~" + phraseText + "~" + phrasePrice + "~" + locMulti + "~" + masterPhraseID + "~" + masterLocID + "~" + range + "^^";
            }
        }
    }
    return text;
}

/*---------------------------------------------------------------------------------------------------------
Ancilliaries
---------------------------------------------------------------------------------------------------------*/

function showHelp(id) {
    if (currHelp != id) {
        currHelp = id;
        var searchHelp = document.getElementById('searchHelpPanel');
        if (searchHelp.offsetHeight > 40) {
            document.getElementById('searchHelpText').style.color = "#929497";
            $(searchHelp).animate({ height: "23px" }, 500);
        }
        var resultsHelp = document.getElementById('resultsHelpPanel');
        if (resultsHelp.offsetHeight > 40) {
            document.getElementById('resultsHelpText').style.color = "#929497";
            $(resultsHelp).animate({ height: "23px" }, 500);
        }
        var keyphrasesHelp = document.getElementById('keyphraseHelpPanel');
        if (keyphrasesHelp.offsetHeight > 40) {
            document.getElementById('keyphraseHelpText').style.color = "#929497";
            $(keyphrasesHelp).animate({ height: "23px" }, 500);
        }
        if (id == 1) {
            $(searchHelp).animate({ height: "200px" }, 500);
            document.getElementById('searchHelpText').style.color = "#25a9ff";
        }
        else if (id == 2) {
            $(resultsHelp).animate({ height: "200px" }, 500);
            document.getElementById('resultsHelpText').style.color = "#25a9ff";
        }
        else {
            $(keyphrasesHelp).animate({ height: "200px" }, 500);
            document.getElementById('keyphraseHelpText').style.color = "#25a9ff";
        }
    }
}

function resetAll() {
    // show the appropriate help text
    showHelp(1);
    selectedLocationID = "";
    selectedKeywordID = "";
    selectedDistance = "10";
    lastDistance = "10";
    clickedLocations = new Array();
    clickedKeywords = new Array();
    submittedLocations = new Array();
    submittedKeywords = new Array();
    runningTotal = 0.0;
    currHelp = 1;
    lastKeywordSearch = "";
    lastLocationSearch = "";
    totalKeyphrases = 0;
    totalLocations = 0
    document.getElementById('keyphraseSearchInput').value = "";
    document.getElementById('locationSearchInput').value = "";
    // hide the top key panel
    document.getElementById('keywordsResults').innerHTML = "";
    document.getElementById('locationsResults').innerHTML = "";
    document.getElementById('combinationResults').innerHTML = "";
    document.getElementById('phraseResultsKeyPanel').style.display = "none";
    document.getElementById('phraseResultsPanelMainLabel').style.color = "#929497";
    $('html, body').animate({ scrollTop: "0px" }, 1000);
    document.getElementById("resultsBackgroundPanel1").style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/greypanel1.png')";
    document.getElementById("resultsBackgroundPanel2").style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/greypanel2.png')";
    document.getElementById("combinationResultsOuterPanel").style.backgroundImage = "url('http://image.locallinkup.com/keyPhraseSampler/greypanel3.png')";
    document.getElementById('selectedKeywords').innerHTML = "0";
    document.getElementById('generatedKeywords').innerHTML = "/0";
    document.getElementById('selectedLocations').innerHTML = "0";
    document.getElementById('generatedLocations').innerHTML = "/0";
    document.getElementById('totalKeyPhrases').innerHTML = "0";
    document.getElementById('totalKeyPhrasesGenerated').innerHTML = "/0";
    document.getElementById('KeyPhrasesTotalCost').innerHTML = "£0.00";
    document.getElementById('KeyPhrasesCost').innerHTML = "£0.00";
    document.getElementById('emailMaximumCost').innerHTML = "£0.00";
    document.getElementById('emailTotalCost').innerHTML = "£0.00";
    document.getElementById('emailNameInput').value = 'Your name here';
    document.getElementById('emailAddressInput').value = 'Your email address here';
    document.getElementById('referrerCodeInput').value = 'Sales ref';
    document.getElementById('referrerMessageInput').value = 'Sales message';
    document.getElementById('rangeInput').value = "5";
    lastRange = "5";
    currentRange = "5";
    lastLocationID = "";
    currentLocationID = "";
}

function GetHeight() {
    var y = 0;
    if (self.innerHeight) {
        y = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) {
        y = document.documentElement.clientHeight;
    }
    else if (document.body) {
        y = document.body.clientHeight;
    }
    return y;
}

function GetWidth() {
    var x = 0;
    if (self.clientWidth) {
        x = self.clientWidth;
    }
    else if (document.documentElement && document.documentElement.clientWidth) {
        x = document.documentElement.clientWidth;
    }
    else if (document.body) {
        x = document.body.clientWidth;
    }
    return x;
}

function formatFloat(num) {
    if (num.indexOf(".") > -1) {
        if (num.split(".")[1].length == 1) {
            num += "0";
        }
        if (num.split(".")[1].length == 0) {
            num += "00";
        }
    }
    else {
        num += ".00";
    }
    return num;
}

function checkInput(elem) {
    // check that the value passed in is a number and then store it locally
    // if not restore the previous value
    if (IsNumeric(elem.value)) {
        selectedDistance = elem.value;
    }
    else {
        elem.value = selectedDistance;
    }
}

function IsNumeric(sText) {
    // this is the numeric validator function, returns true if it's a valid number
    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}


// Handles the default text in the main question text area
function setTextArea(elem, type) {
    if (type == "clear") {
        if (document.getElementById('referrerMessageInput').value == "Sales message") {
            document.getElementById('referrerMessageInput').value = "";
        }
    }
    else {
        if (document.getElementById('referrerMessageInput').value == "") {
            document.getElementById('referrerMessageInput').value = "Sales message";
        }
    }
}

// Handles the default text in the name and contact text fields
function setTextBox(elem, type) {
    if (type == "clear") {
        var tempText = elem.value;
        if (tempText == "Your name here" || tempText == "Your email address here" || tempText == "Sales ref") {
            elem.value = "";
        }
    }
    else {
        if (elem.value == "") {
            elem.value = type;
        }
    }
}

function checkKeys(e) {
    if (e.keyCode == 13) {
        // Enter
        try { e.preventDefault(); } catch (err) { }
        try { e.returnValue = false; } catch (err) { }
    }
}
