var steps = ['contact', 'screening', 'targets'];
var currentStep = 0;

function changeClass() {
    if (currentStep != 0){
        $('quickquote_progress_filters').show();
    }
    var select = $('quickquote_filter_target_type');
    var options = select.options;
    optionId = select.selectedIndex >= 0 ? select.options[select.selectedIndex].id : undefined; 
    if (optionId) {
        key = optionId.split('-')[0];
        value = optionId.split('-')[1];
    }
    addParams('adjclear', 'true', true);
    var ajaxUrl = $('quickquote_ajax_url').value; 
    var params = $('quickquote_params').value; 
    new Ajax.Request(ajaxUrl + '?' + params, {
        method: 'get', 
        onComplete: function() {
                        showLayer();
                        setClass(key, value);
                    }
        });
}

function setClass(key, value) {
    clearParams();
    addParams(key, value, true);
    getLayer();
}

function getLayer() {
    if (currentStep != 0){
        $('quickquote_progress_filters').show();
    }
    
    var ajaxUrl = $('quickquote_ajax_url').value; 
    var params = $('quickquote_params').value; 
    new Ajax.Request(ajaxUrl + '?' + params, {method: 'get', onSuccess: showLayer});
}

function getSubtypes() {
    if (currentStep != 0){
        $('quickquote_progress_filters').show();
    }
    var ajaxUrl = '/quickquote/ajax/subtypes/';
    var params = $('quickquote_params').value; 
    new Ajax.Request(ajaxUrl + '?' + params, {method: 'get', onSuccess: showSubtypes});
}


function showLayer(transport) {
    var resp = {} ;
    if (transport && transport.responseText){
        try {
            var resp = eval('(' + transport.responseText + ')');
            $('quickquote_targets').update(resp.layer + resp.subtypes);
            quickQuoteInit();
        }
        catch (e) {
            resp = {};
        }
    }
    
    getTargetSelections();
    toggleTargetTypes();
    
    $('quickquote_progress_filters').hide();
    if($('quickquote_filter_target_type')){
        var select = $('quickquote_filter_target_type');
        var options = select.options;
        if (select.options[select.selectedIndex].id != "target_type-"){
           $$('.child-filters').first().show();
        }
    }
}

function showSubtypes(transport) {
    var resp = {} ;
    if (transport && transport.responseText){
        try {
            var resp = eval('(' + transport.responseText + ')');
            $('quickquote_subtypes').replace(resp.subtypes);
            quickQuoteInit();
        }
        catch (e) {
            resp = {};
        }
    }
    
    getTargetSelections();
    toggleTargetTypes();
    
    $('quickquote_progress_filters').hide();
}

//Initialize Listeners
function quickQuoteInit() {
    var items = $('quickquote_filters').select('a');
    var i, n = items.length;
    for (i=0; i<n; ++i){
        Event.observe(items[i], 'click', clickListener);
    }
    
    var subtypes = $('quickquote_subtypes').select('a');
    var i, n = subtypes.length;
    for (i=0; i<n; ++i){
        Event.observe(subtypes[i], 'click', selectTarget);
    }
    
    var nextButtons = $$('.qq-next-section');
    var i, n = nextButtons.length;
    for (i=0; i<n; ++i){
        Event.observe(nextButtons[i], 'click', nextStep);
    }
    
    var previousButtons = $$('.qq-prev-section');
    var i, n = previousButtons.length;
    for (i=0; i<n; ++i){
        Event.observe(previousButtons[i], 'click', previousStep);
    }
    
    var removeSelected = $$('.qq-remove-target');
    var i, n = removeSelected.length;
    for (i=0; i<n; ++i){
        Event.observe(removeSelected[i], 'click', removeSelectedListener);
    }
    
    
    // NEW CODE - JP
    Event.observe($('quickquote_clear_targets'), 'click', clearSelectedTargets);
    Event.observe($('quickquote_filter_target_type'), 'change', changeListener);
    setMatchingTargets();
    $('quickquote_selected_targets').update("");
    updateSelectedTargets();
    //END NEW CODE - JP
}

function checkSubmit(evt) {
    if (!form.validator.validate() || currentStep != 2){
        Event.stop(evt);
        return;
    }
}

// NEW CODE - JP
function removeSelectedListener(evt){
    var link = Event.findElement(evt, 'A');
    Event.stop(evt);
    var listItem = link.up();
    removeSelectedTarget(listItem, listItem.className.split(" ")[0]);
    getMatchingTargets();
}


function changeListener(evt) {
    clearFilters();
    clearParams();
    var select = $('quickquote_filter_target_type');
    var options = select.options;
    optionId = select.selectedIndex >= 0 ? select.options[select.selectedIndex].id : undefined; 
    if (optionId) {
        key = optionId.split('-')[0];
        value = optionId.split('-')[1];
        changeClass();
    } else {
        clearParams();  
    }
}
//END NEW CODE - JP

function clickListener(evt) {
    addParams('p', 'clear', 1);
    updateLinks(evt, 0);
    getSubtypes();
    selectFilter(evt);
    if (evt) {
        Event.stop(evt); 
    }
}

function selectFilter(evt){
    var link = Event.findElement(evt, 'A');
    if (link.hasClassName('quickquote-attribute-selected')) {
        link.removeClassName('quickquote-attribute-selected');
    } else {
        link.addClassName('quickquote-attribute-selected');  
    }   
    Event.stop(evt);
}

function selectTarget(evt){
    var link = Event.findElement(evt, 'A');
    if (link.hasClassName('quickquote-attribute-selected')) {
        removeSelectedTarget(link);
        link.removeClassName('quickquote-attribute-selected');
    } else {
        link.addClassName('quickquote-attribute-selected');  
        addSelectedTarget(link.innerHTML);
        $$('.qq-selections-none').first().hide();
    }   
    getMatchingTargets();
    Event.stop(evt);
}

function addSelectedTarget(itemLabel) {
    currentSelections = $('quickquote_selected_targets').innerHTML; 
    itemClass = itemLabel.stripTags();
    //Replace spaces with hyphens
    itemClass = itemClass.gsub(/\s+/,'-');
    //Remove parenthesis
    itemClass = itemClass.gsub(/\W/,'');
    targetHtml = "<li class='qq-selected-target-"+itemClass+" qq-selected-last'><span>"+itemLabel+"</span> <p class='qq-comma'>,</p><a class='qq-remove-target' href='#'>&nbsp;</a></li>";
    $('quickquote_selected_targets').update(currentSelections + targetHtml);
    if ($$('#quickquote_selected_targets li').last().previous()){
        $$('#quickquote_selected_targets li').last().previous().removeClassName('qq-selected-last');
    }
    
    //Add listeners for Remove links    
    var removeSelected = $$('.qq-remove-target');
    var i, n = removeSelected.length;
    for (i=0; i<n; ++i){
        Event.observe(removeSelected[i], 'click', removeSelectedListener);
    }
    
    getMatchingTargets();
}

function removeSelectedTarget(item, itemClass) {
    itemText = "";
    if (!itemClass) {
        itemText = item.innerHTML;
        itemClass = itemText.stripTags();
        //Replace spaces with hyphens
        itemClass = itemClass.gsub(/\s+/,'-');
        //Remove parenthesis
        itemClass = itemClass.gsub(/\W/,'');
        className = '.qq-selected-target-'+itemClass;
    } else {
        itemText = item.innerHTML.replace('<p class="qq-comma">,</p><a class="qq-remove-target" href="#">&nbsp;</a>', "");
        itemText = itemText.replace('<P class=qq-comma>,</P><A class=qq-remove-target href="#">&nbsp;</A>', "");
        itemText = itemText.replace('<span>', "");
        itemText = itemText.replace('<SPAN>', "");
        itemText = itemText.replace('</span>', "");
        itemText = itemText.replace('</SPAN>', "");
        itemText = itemText.strip();
        className = '.' + itemClass;        
    }
    removeMatchingTarget(itemText);
    $$(className).first().remove();
    
    if ($('quickquote_selected_targets').childElements().length == 0) {
        $$('.qq-selections-none').first().show();
    }
    getMatchingTargets();
    if ($$('#quickquote_selected_targets li').last()){
        $$('#quickquote_selected_targets li').last().addClassName('qq-selected-last');
    }
}

function createRequest(href) {
    var pos = href.indexOf('?');
    if (pos > -1){
        $('quickquote_params').value = href.substring(pos+1, href.length);
    }
    getLayer();
}

function updateLinks(evt, isSingleVal) {
    var link = Event.findElement(evt, 'A');
    addParams(link.id.split('-')[0], link.id.split('-')[1], isSingleVal);

    Event.stop(evt);
}

function updateSelectedTargets() {
    items = new Array();
    matchingTargets = $("quickquote_matching_targets").value;
    matchingTargets.scan(/<li>([\S\W]*)<\/li>/, function(matches) {
        items = matches[1].split('</li><li>');
    });
    
    if (items.length > 0) {
        for(i=0; i < items.length; i++) {
            if (items[i]) {
                addSelectedTarget(items[i]);
            }
        }
        $$('.qq-selections-none').first().hide();
    }
}

function clearFilters(){
    $$('#quickquote_filters ol li a').each(function(elmt) {
        if(elmt.hasClassName('quickquote-attribute-selected')){
            elmt.removeClassName('quickquote-attribute-selected');
        }
    });
}

function clearSelectedTargets() {
    $$('#quickquote_selected_targets li').each(function(elmt) {
        removeSelectedTarget(elmt, elmt.className.split(" ")[0]);
    });
    $$('.qq-selections-none').first().show();
}

function addParams(k, v, isSingleVal)
{
    var el = $('quickquote_params');
    var params = el.value.parseQuery();

    var strVal = params[k];
    if (typeof strVal == 'undefined' || !strVal.length){
        params[k] = v;
    }
    else if('clear' == v ){
        params[k] = 'clear';
    }
    else {
        var values = strVal.split('-');
        if (-1 == values.indexOf(v)){
            if (isSingleVal)
                values = [v];
            else 
                values.push(v);
        } 
        else {
            values = values.without(v);
        }

        params[k] = values.join('-');
    } 
    el.value = Object.toQueryString(params).gsub('%2B', '+');
}

function clearParams() {
    var el = $('quickquote_params');
    el.value = "";
}

function nextStep(evt) {
    if (!form.validator.validate()){
        Event.stop(evt);
        return;
    }
    $('quickquote_' + steps[currentStep]).hide();
    currentStep++;
    if (steps[currentStep] == 'targets') {
        var select = $('quickquote_filter_target_type');
        var options = select.options;
        var optionId = options[0].id;
        $(optionId).selected = true;
        //reset the form
        changeClass();        
    }
    $('quickquote_' + steps[currentStep]).show();
    updatePager('next');
}

function previousStep() {
    $('quickquote_' + steps[currentStep]).hide();
    currentStep--;
    $('quickquote_' + steps[currentStep]).show();
    updatePager('previous');
}

function updatePager(direction) {
    var currentlySelected;
    
    if (direction == 'next'){
        $$('.paging-context td.c').each(function(elmt) {

            if(elmt.hasClassName('selected')) {
                currentlySelected = elmt;
                if (elmt != $$('.paging-context td.c').last()){
                    elmt.removeClassName('selected');
                    elmt.addClassName('done');
                }
            }       
        });
        if (currentlySelected.next('td.c')){
            currentlySelected.next('td.c').addClassName('selected');  
        }
    } else {
        $$('.paging-context td.c').each(function(elmt) {

            if(elmt.hasClassName('selected')) {
                currentlySelected = elmt;
                if (elmt != $$('.paging-context td.c').first()){
                    elmt.removeClassName('selected');
                    elmt.removeClassName('done');
                }
            }       
        });
        if (currentlySelected.previous('td.c')){
            currentlySelected.previous('td.c').addClassName('selected');  
        }
    }
}

function getTargetSelections() {
    var selections = "";
    $$(".quickquote-attribute").each(function(elmt) { 
        filter = elmt.up('ol').previous('h4').innerHTML;
        selections = elmt.hasClassName("quickquote-attribute-selected") ? selections + "<li><strong>" + filter + ":</strong> " + elmt.innerHTML + "</li>" : selections; 
    });
    selections = '<ul>' + selections + '</ul>';
    $("quickquote_target_selections").value = selections;
}

function getMatchingTargets() {
    var targets = "";
    var currentTargets;
    var items = new Array(); 
    matchingTargets = $("quickquote_matching_targets").value;
    matchingTargets.scan(/<li>([\S\W]*)<\/li>/, function(matches) {
        items = matches[1].split('</li><li>');
    });
    
    $$(".quickquote-subtype").each(function(elmt) { 
        if (elmt.hasClassName("quickquote-attribute-selected")) {
            items.push(elmt.innerHTML);
        }
    });
    items = items.uniq();
    if (items.length > 0) {
        targets = '<ul><li>' + items.join("</li><li>") + '</li></ul>';    
    } else {
        targets = '';    
    }
    
    $("quickquote_matching_targets").value = targets;
}

function removeMatchingTarget(targetLabel) {
    var targets = "";
    var currentTargets;
    var items = new Array(); 
    matchingTargets = $("quickquote_matching_targets").value;
    matchingTargets.scan(/<li>([\S\W]*)<\/li>/, function(matches) {
        items = matches[1].split('</li><li>');

    });
    $$("#quickquote_subtypes ol li a").each(function(elmt) {
        if (elmt.innerHTML == targetLabel) {
            elmt.removeClassName('quickquote-attribute-selected');
        }
    });
    items = items.without(targetLabel);
    targets = (items.length > 0) ? '<ul><li>' + items.join("</li><li>") + '</li></ul>' : '';
    $("quickquote_matching_targets").value = targets;
}

function setMatchingTargets() {
    
    var items;  
    matchingTargets = $("quickquote_matching_targets").value;
    matchingTargets.scan(/<li>([\S\W]*)<\/li>/, function(matches) {
        items = matches[1].split('</li><li>');
    });
    
    $$("#quickquote_subtypes ol li a").each(function(elmt) {
        for (i=0; i < items.length; i++){
            if (elmt.innerHTML == items[i]) {
                elmt.addClassName('quickquote-attribute-selected');
            }
        }
    });
}


function hideFormOnSuccess() {
    if ($$('li.success-msg').first() && !$$('li.success-msg').first().empty()){
        $('quickquote_container').hide();
        $('quickquote_submit_success').show();
    } else {
     $('quickquote_container').show();   
    }
}

function toggleTargetTypes() {
    var itemSelected = false;
    $$('#quickquote_filter_target_type li a').each(function(item){
        if (item.hasClassName("quickquote-attribute-selected")) {
            itemSelected = true;
        }
    });
    
    if (itemSelected == true) {
        $$('#quickquote_filter_target_type li a').each(function(item){
            if (! item.hasClassName("quickquote-attribute-selected")) {
                item.addClassName('quickquote-attribute-disabled');
                Event.stopObserving(item, 'click');
                Event.observe(item, 'click', function(evt){Event.stop(evt);});
            }
        });
    }
}

document.observe("dom:loaded", function(){
    
    if($('quickquote_form')) {
        Event.observe('quickquote_form', 'submit', checkSubmit);
    
        hideFormOnSuccess();
    
        Calendar.setup({
            inputField     :    "qq_start_date",
            ifFormat       :    "%m/%d/%Y",
            weekNumbers    :    false,
            showsTime      :    false,
            button         :    "qq_start_picker",
            step           :    1
        });
    
        Calendar.setup({
            inputField     :    "qq_shipment_date",
            ifFormat       :    "%m/%d/%Y",
            weekNumbers    :    false,
            showsTime      :    false,
            button         :    "qq_shipment_picker",
            step           :    1
        });
    
        //Add email confirmation validation
        Validation.add('validate-cemail', 
                       'Please make sure your email addresses match.', 
                       function(v) {
                           var email = $('qq_email');
                           var conf = $('qq_email_confirm');
                           return (email.value == conf.value);
                       }
        );
    }
});



