// This whole thing should be an object to avoid globals, but for now it'll do

var globalRequest_url = '/agreements/ajax_searchresultcount';
if (/therapywatch/.test(location.href)) {
    globalRequest_url = '/therapywatch/ajax_searchresultcount';
}

var globalRequest = new Request({
    url:        globalRequest_url,
    method:     'post',
    onComplete: function(response) { $('currentDealCount').innerHTML = response },
    onFailure:  genericOnFailure.pass('Deal number update failed, Operation either timed out or could not connect to remote server.')
});
var globalTimer = 0;

//
// Set the name of the search parameters in the case where
// we are editing an existing search it does a rename otherwise
// it sets the name.
// It then reloads the page to ensure the search counter and select list is updated
//
function setParamSetName(paramSetID,originalName) {
    var paramSetName;
    paramSetName = originalName;

    if (paramSetName == '' || paramSetName == null) {
        paramSetName = prompt("Please enter a name for this search:");
    }
    else {
        paramSetName = prompt("Rename and save this search:", paramSetName);
    }

    if (paramSetName != '' && paramSetName != null) {
        // make ajax call to set the name for this parameter set
        var url;
        url = "/agreements/ajax_setSearchParameterSetName?paramSetID=" + paramSetID + "&paramSetName=" + paramSetName;
        new Request({url: url,
            method: 'get',
            onComplete: function(response) { window.location.reload(); }
        }).send();
    }
}

function updateResultCount(longWait) {
        //wait for a bit sec before sending
        $('currentDealCount').innerHTML = '<img src="http://images.pharmaventures.com/pharmadeals/web2_load.gif" style="float:left; margin: 5px 15px;">';
        if (globalTimer)
        {
            $clear(globalTimer);
        }
        globalTimer = function(url,form){
            globalRequest.cancel();
            if (window.trees)
            {
                trees.each(function(tree){
                    tree.makeFormElements('dealsearchform');
                });
            }
            var formData =  $('dealsearchform').toQueryString();
            globalRequest.send({data: formData})
        }.delay(longWait);
}

function toggleCheckButtons(form, value) {
 for (var i=0; i < form.elements.length; i++) {
   var e = form.elements[i];
   if (e.name == 'coreDealID' || e.name == 'allSelector' )
     e.checked = value;
   }
}

function updateNumberWatchlistDeals(form) {
    var url;
    url = "/agreements/ajax_updateWatchlistDeals";
    new Request({url:url,
        method: 'post',
        update: $("numberWatchlistDeals"),
        onComplete: function(response)  {  $('numberWatchlistDeals').innerHTML = response }
    }).post(url,form);
}

function updateStack(action,source,form) {
    var url;
    url = "/agreements/ajax_updateStack/" + action + '/' + source;

    if (source=='selection') {
        // count the number of selected boxes
        var checked = 0;
        for (var i=0; i < form.elements.length; i++) {
            var e = form.elements[i];
            if (e.name == 'coreDealID' && e.checked) {
                checked = checked + 1;
            }
        }
        if (checked==0) {
            alert("You must select at least one deal");
            return;
        }
    }
    var data = form;
    switch($type(data)){
        case 'element': data = $(data).toQueryString(); break;
        case 'object': data = Object.toQueryString(data);
    }
    $('deal_stack_link_' + action + '_' + source).setStyle('background-color', '#ff9999').blur();
    setStackIndicator(source,'#ff9999');

    new Request({url:url,
        method: 'post',
        onSuccess: updateStackOnComplete,
        onFailure: genericOnFailure.pass('Stack Update Failed, Operation either timed out or could not connect to remote server.')
    }).post(url,data);
}

function setStackIndicator(source,colour)
{
    var si = $('stackIndicator_' + source);
    switch(source){
        case 'set':
            si.setStyles({'border-right-color': colour, 'border-bottom-color': colour});
            break;
        case 'selection':
            si.setStyles({'border-left-color': colour, 'border-bottom-color': colour});
    }
}

function updateStackOnComplete(txt,xml) {
    var data = JSON.decode(txt,1);

    $$('.deal_stack_link').setStyle('background-color', 'transparent');
    setStackIndicator('set','#EBE5F6');
    setStackIndicator('selection','#EBE5F6');

    // try to update the total number of stacks
    $$('.dealStackCount').set({html: data.length});

    // try to update the stack dropdown
    $$('option','dealStackSelect').dispose();

    //first element is the NEW DEAL STACK
    var initialOpt  = new Element('option',{value: '_new_'}).set('text','**Create New Deal Stack**');
    initialOpt.inject($('dealStackSelect'));

    //Loop all JSON option field for the deal stack option element.
    for (var element in data) {
        if (data[element].id && data[element].val) {
            var newOpt  = new Element('option',{value: data[element].id}).set('text',data[element].val);
            newOpt.inject($('dealStackSelect'));
        }
    }

    //var initialOpt  = new Element('option',{value: '_new_'}).set('text','**Create New Deal Stack**');
    //initialOpt.injectInside($$('option','dealStackSelect'));
    //if (data.length)
    //{
    //  dealStackSelect.selectedIndex = $$('option','dealStackSelect').length-1;
    //  }
}

function genericOnFailure(text) {
    $$('a.deal_stack_link').each(function(el){
        el.setStyle('background-color', 'transparent');
    });
    setStackIndicator('set','#EBE5F6');
    setStackIndicator('selection','#EBE5F6');
    alert(text);
}

function updateLinkedIndicationSelectbox(selectboxID, currentSelectbox, uri) {
    var url;
    var currentItem;
    currentItem = currentSelectbox.options[currentSelectbox.selectedIndex].value;
    url = uri + "/" + currentItem;
    new Request({ url: url,
        method: 'get',
        update: $(selectboxID),
        onComplete: function(response)  {  $(selectboxID).innerHTML = response }
    }).send();
}
