
function getAnalysistValuesArray(element){
    return readDropdownValues(element)
}

function getAnalysistKeysArray(element){
    return readDropdownKeys(element)
}

function getAuthorsArray(element){
    return readDropdown(element)
}

// read all elements in a selection and return as a array
function readDropdownValues(dropd){
    var returnArray = new Array();
    var optsLength = dropd.options.length;
    //console.log(optsLength);
    for(var i=0;i<optsLength;i++){
        //console.log(dropd.options[i].value + " => " + dropd.options[i].text);
        if(dropd.options[i].value == ""){

            returnArray[0] = ""
        }else{
            returnArray[dropd.options[i].value] = dropd.options[i].text
        }

    }
    //console.log(returnArray);
    return returnArray; // undefined elemnt will be added to thsi array and need to be ignored them
}

function readDropdownKeys(dropd){
    var returnArray = new Array();
    var optsLength = dropd.options.length;
    //console.log(optsLength);
    for(var i=0;i<optsLength;i++){
        //console.log(dropd.options[i].value + " => " + dropd.options[i].text);
        if(dropd.options[i].value == ""){
            returnArray[0] = ""
        }else{
            returnArray[i] = dropd.options[i].value
        }

    }
    //console.log(returnArray);
    return returnArray; // undefined elemnt will be added to thsi array and need to be ignored them
}

function getSelectedOptions(selectedOpt){
    var returnArray = new Array();
    var optsLength = selectedOpt.options.length;
    //console.log(optsLength);
    for(var i=0;i<optsLength;i++){
        //console.log(selectedOpt.options[i].text);
        if(selectedOpt.options[i].selected)
            //console.log(selectedOpt.options[i].value);
            returnArray[i] = selectedOpt.options[i].value;
    }
    return returnArray;
}



function removeAllElements(selectedEle){

    var optsLength = selectedEle.options.length;

    for(var i=0;i<optsLength;i++){
        selectedEle.remove(selectedEle.options[i]);
    }
}

function isFoundInArray(i, arr){
    //console.log(i + " => " + arr);
    //console.log(arr);
    //console.log(i);
    //console.log(arr.indexOf( String(i) ));

    if(arr.indexOf(String(i)) == -1){
        return false;
    }
    return true;
}

function fillFormElement(element_name, elementSelectedArray, siblingsArray){
	
    //optionArray - full array of elements

    //console.log(analystsValueList);
    //console.log("All posible values => " + analystsValueList );
    //console.log("Option lkeys for values => " + analystsKeyList );
    //console.log(analystsKeyList);
    //elementSelectedArray= elementSelectedArray.unique();

    //console.log( "current elemnt selected array => " + elementSelectedArray);

    element = $(element_name);

    // get the current element selected values - this is the element gonna feed the new oprions

    // remove all elements in the current form object
    removeAllElements(element);

    var ignoreArray = new Array();
    //create ignore array - array contain all the elemnts alreay selected
    var sibOptLength = siblingsArray.length;
    //console.log(sibOptLength);

    ignoreArray = ignoreArray.concat(elementSelectedArray);
    //console.log(ignoreArray);
    //var isSiblingSelected = false;

    var siblingSelectedOptions = null;
    for(var j=0;j<sibOptLength;j++){

        ignoreArray = ignoreArray.concat(siblingsArray[j]['data']);
        // this will return the earlier selected values for the current sibling
        if(siblingsArray[j]['name']==element_name){
            siblingSelectedOptions = siblingsArray[j]['data'];
        }
    }

    // if none is selected  remore it from teh ignore array since it should be in the oprion always
    ignoreArray = ignoreArray.unique();
    ignoreArray.sort();
    if(isFoundInArray(0, ignoreArray)){
        ignoreArray.shift();
    }

    //console.log("innore array => " + ignoreArray);
    //console.log( element_name+" has already selected => " + siblingSelectedOptions);

    var optsLength = analystsKeyList.length;
    //console.log(optsLength);
    var filteredOptionValues = new Array();
    for(var i=0;i<optsLength;i++){
        //console.log(optionArray[i]);
        if(analystsKeyList[i] != undefined){
            if( !isFoundInArray( analystsKeyList[i], ignoreArray )){
                //console.log(optionArray[i]);
                // check whether others already selected this element
                filteredOptionValues[i] = parseInt(analystsKeyList[i]);
            }
        }
    //console.log(selectedOpt.options[i].value);
    }

    // add the current current siblings selected values in to the filtered array and select them
    //console.log(siblingSelectedOptions.length);
    filteredOptionValues = filteredOptionValues.concat(siblingSelectedOptions);
    filteredOptionValues = filteredOptionValues.unique();
    filteredOptionValues.sort();
    //console.log(element_name+" filtered array => " + filteredOptionValues);
    //console.log(filteredOptionValues);


    // make the selected values again as selected
    // fill the given option accordingly
    var filteredOptlength = filteredOptionValues.length;
    
    for(var i=0;i<filteredOptlength;i++){
        if(filteredOptionValues[i] != undefined){
            //console.log(filteredOptionValues[i]);
            element.add(new Option(analystsValueList[filteredOptionValues[i]], filteredOptionValues[i]), null);
            if(isFoundInArray(filteredOptionValues[i], siblingSelectedOptions)){
                //console.log(element_name + " should select => " + filteredOptionValues[i]);
                if(element.options[filteredOptionValues.indexOf(filteredOptionValues[i])] != undefined){
                    element.options[filteredOptionValues.indexOf(filteredOptionValues[i])].selected=true;
                }
            }
        // if the already selected array empty
        //console.log(analystsValueList[filteredOptionValues[i]]);
        }
    }
    

}

function DropdownManager(selectedEle, selEle){

    var currentSelectedArray = getSelectedOptions(selectedEle);
    var siblingsSelectedArray = new Array();

    // get repost anatyst selection
    var analystInfoAr = new Array();
    analystInfoAr['name'] = 'report_analyst';
    analystInfoAr['data'] = getSelectedOptions( $('report_analyst') );

    var otherauthorsInfoAr = new Array();
    otherauthorsInfoAr['name'] = 'report_otherauthors';
    otherauthorsInfoAr['data'] = getSelectedOptions( $('report_otherauthors') );

    var coauthorsInfoAr = new Array();
    coauthorsInfoAr['name'] = 'report_coauthor';
    coauthorsInfoAr['data'] = getSelectedOptions( $('report_coauthor') );

    switch(selEle){
        case 'report_analyst':
            // get siblings selections
            siblingsSelectedArray[0] = otherauthorsInfoAr;
            siblingsSelectedArray[1] = coauthorsInfoAr;
            //fillFormElement( $('report_analyst'), currentSelectedArray, siblingsSelectedArray, authorsList);
            fillFormElement( 'report_otherauthors', currentSelectedArray, siblingsSelectedArray);
            fillFormElement( 'report_coauthor', currentSelectedArray, siblingsSelectedArray);
            break;

        case 'report_otherauthors':
            siblingsSelectedArray[0] = analystInfoAr;
            siblingsSelectedArray[1] = coauthorsInfoAr;
            //fillFormElement( $('report_otherauthors'), currentSelectedArray, siblingsSelectedArray, authorsList);
            fillFormElement('report_analyst', currentSelectedArray, siblingsSelectedArray)
            fillFormElement('report_coauthor', currentSelectedArray, siblingsSelectedArray)
            break;

        case 'report_coauthor':
            siblingsSelectedArray[0] = otherauthorsInfoAr;
            siblingsSelectedArray[1] = analystInfoAr;
            //fillFormElement( $('report_coauthors'), currentSelectedArray, siblingsSelectedArray, authorsList);
            fillFormElement('report_otherauthors', currentSelectedArray, siblingsSelectedArray)
            fillFormElement('report_analyst', currentSelectedArray, siblingsSelectedArray)
            break;
    }
}


function calcRARPercTotal()
{
    var a = new Number($('report_bull_probability').value);
    var b = new Number($('report_neutral_probability').value);
    var c = new Number($('report_bear_probability').value);
    var total = a + b + c;
    //if($('toggle_neutral').innerHTML == 'deactivate') total += b;
    total = roundNumber(total, 3);

    if(!isNaN(total) && total!='' && total>0)
        $('perc_total').innerHTML = total + '%';
    else
        $('perc_total').innerHTML = '0%';

    if(total>100)
        $('perc_total').style.color = 'red';
    else
        $('perc_total').style.color = '';
}

function roundNumber(num, dec)
{
    var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
    return result;
}

function toggleNeutral()
{
    var link = $('toggle_neutral');
    var visState;
    if(link.innerHTML == 'activate')
    {
        visState = 'inline';
        link.innerHTML = 'deactivate';
        $('act_link2').innerHTML = $('act_link1').innerHTML;
        $('act_link1').innerHTML = '';
    }
    else
    {
        visState = 'none';
        link.innerHTML = 'activate';
        $('act_link1').innerHTML = $('act_link2').innerHTML;
        $('act_link2').innerHTML = '';
        $('report_neutral_probability').value = '';
        $('report_neutral_price').value = '';
        $('report_neutral_description').value = '';
    }

    $('td_neutral_probability').style.display = visState;
    $('td_neutral_price').style.display = visState;
    $('td_neutral_description').style.display = visState;
    $('counter_report_neutral_description').style.display = visState;
    calcRARPercTotal();
}

var formVals;
function formValues()
{
    formVals = '';
    var elem = $('frmdata').elements;
    for(var i = 0; i < elem.length; i++)
    {
        formVals += elem[i].value+'|';
    }
}

function checkFormValues()
{
    var initVals = formVals;
    formValues();
    if(initVals !== formVals)
    {
        $('is_updated').value = 1;
    }
    return true;
}


var eLArr = new Array();
function initCharCounters()
{
    eLArr = eL.split(',');
    for(i=0; i<eLArr.length; i++)
    {
        var elId = eLArr[i];
        if($(elId) == null || $('counter_'+elId) == null) continue;
        var charLimit = $(elId).maxLength;
        if(!charLimit) charLimit = $(elId).getAttribute("maxlength");
        var charCount = $(elId).value.length;
        var charsLeft = charLimit-charCount;
        $('counter_'+elId).innerHTML = "<strong>" + charsLeft + "</strong> chars left";
        if(charsLeft <= 0)
        {
            $('counter_'+elId).innerHTML = "<span style='color:red'>Char limit reached</span>";
            $(elId).value =  $(elId).value.substr(0, charLimit);
        }
    }
}

function populateTickerSymbol()
{
    var symbol = $('report_primary_ticker').options[$('report_primary_ticker').selectedIndex].text;
    if(symbol != '' && $('report_title').value.length < 10)
    {
        $('report_title').value = symbol + ': ';
    }
}

function populateUsernameFromEmail()
{
    $('user_username').value = $('user_profile_email').value;
}

function checkFileExtention(filename, exts)
{
    var extentions = exts.split(",");
    
    for(var i=0; i<extentions.length; i++)
    {
        if(filename.lastIndexOf(extentions[i])!=-1) return true;
    }
    return false;
}

function autopopulateFields(source, target, ignore_empty)
{
    s_value = $(source).value;
    t_value = $(target).value;

    if(ignore_empty){
        $(target).value = s_value;
        
    }
    else{
        if(t_value=="") $(target).value = s_value;
    }
    

}


function clearEventData(id){
	document.getElementById('report_event_date_'+id).value = "";
	document.getElementById('report_event_title_'+id).value = "";
	document.getElementById('report_event_url_'+id).value = "";
}

