/* Registration and member forms */

var callcount = 0;

$(document).ready(function(){


    $('.product_article_detail_button').click(function() {
        $('#product_article_detail_' + this.id).toggle();
      });

    // focus the first field on the main form if it exists
    try{ $('.form :input[type!=hidden]')[0].focus(); }
    catch(err) {}

    $('#product_monitor_change_profile').change(function(){
        $('#product_monitor_change_profile_form').submit();
        })

    // --------------------------------------------------------------------------------
    // MEMBER MANAGEMENT STUFF
    // --------------------------------------------------------------------------------
    // remove member
    function member_list_delete_handler(obj){
            if (confirm('Are you sure you wish to remove this member?')){
                $.post(MEMBER_LIST_DELETE_CALLBACK, {'member_id':obj.id,  'objid':$('#member_list_add_obj').val()},
                    function(data) {
                        $('#member_list_ajax').html(data);
                        $('.member_list_delete').click(function(){member_list_delete_handler(this)});
                });
            }
    }
    $('.member_list_delete').click(function(){member_list_delete_handler(this)});

    // add member
    $("#member_list_add").focus(function(){if(this.value == this.defaultValue){this.select();}}) // auto select text on focus
    $('#member_list_add_button').click(
            function(){
                $.post(MEMBER_LIST_ADD_CALLBACK, {'email':$('#member_list_add').val(), 'objid':$('#member_list_add_obj').val()},
                    function(data) {
                        $('#member_list_ajax').html(data);
                        $('.member_list_delete').click(function(){member_list_delete_handler(this)});
                });
            }
        );
    // --------------------------------------------------------------------------------



    // --------------------------------------------------------------------------------
    // SCOOP COMPANY MANAGEMENT STUFF
    // --------------------------------------------------------------------------------
    // scoop - remove company
    function scoop_company_delete_handler(obj){
            if (confirm('Are you sure you wish to remove this company?')){
                $.post(COMPANY_DELETE_CALLBACK, {'company_id':obj.id, 'profile_id':$('#product_scoop_company_profile').val()},
                    function(data) {
                        $('#product_scoop_company_ajax').html(data);
                        $('.product_scoop_company_delete').click(function(){scoop_company_delete_handler(this)});
                });
            }
    }
    $('.product_scoop_company_delete').click(function(){scoop_company_delete_handler(this)});

    // scoop - add company
    $("#product_scoop_company_add").focus(function(){if(this.value == this.defaultValue){this.select();}}) // auto select text on focus
    $('#product_scoop_company_add_button').click(
            function(){
                $.post(COMPANY_ADD_CALLBACK, {'company':$('#product_scoop_company_add').val(), 'profile_id':$('#product_scoop_company_profile').val()},
                    function(data) {
                        $('#product_scoop_company_ajax').html(data);
                        $('.product_scoop_company_delete').click(function(){scoop_company_delete_handler(this)});
                });
            }
        );
    // --------------------------------------------------------------------------------


    /* SCOOP AUTOCOMPLETE FOR ADDING COMPANIES */
    $("#product_scoop_company_add").autocomplete("/trader/codes/", {
        minChars:1,
        resultsClass:'product_scoop_company_add_suggestions',
        cacheLength :1,
        maxItemsToShow:15,
        delay:1,
        width:230,
        padCommas:true,
        autoFill:false,
        onItemSelect:function() { $("#product_scoop_company_add").focus();}
    });
    
    $("#product_scoop_company_add").keypress(function(e) {
        if (!((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))) {
            this.autocompleter.flushCache();
            AUTOCOMPLETE_COMMA_CACHE = $(this).val();
            return true;   
        }
    });

    // --------------------------------------------------------------------------------

    // Monitor form
    if ($('.member-monitor').length > 0) {
        $(".member-monitor .scrollable input").bind("click",(function(e) {
            update_recommend();
            update_industry_count();
        }));
        $("#id_companies, #id_people, #id_filter").keypress(function(e) {
            if (e.which != 44) return;
            update_recommend();
        });
        update_industry_count();
        update_recommend();
        get_article_count_update($('#id_company').val(),'',$('#company_count_id')[0]);
        get_article_count_update($('#id_companies').val(),'',$('#companies_count_id')[0]);
        get_article_count_update($('#id_filter').val(),'',$('#filter_count_id')[0]);
        get_article_count_update($('#id_people').val(),'',$('#people_count_id')[0]);
        get_article_count_update($('#id_products').val(),'',$('#products_count_id')[0]);
        get_article_count_update($('#id_interests').val(),'',$('#interests_count_id')[0]);
    }

    // Block form
    if ($('.member-block').length > 0) {
       $('.recommend-wrap a').click(add_recommend);
       $("#id_provider").autocomplete("/ajax/providers/", {
          minChars:1,
          resultsClass:'block_suggestions',
          maxItemsToShow:15,
          mustMatch: 1,
          onItemSelect: function (li) {
             value = li.innerHTML + '|' + li.extra;
             $('#add_provider').val(value);
          }
       });
       $('#add_provider').click(function() {
          if (this.value.length < 6) return;
          selected = this.value.split('|');
          label = selected[0];
          value = selected[1];
          existing = $(".providers li input[value='" + value + "']")[0]
          if (existing) {
             alert('existing');
             existing.focus();
          } else {
             // need to get the value
             html = '<li><label><input type="checkbox" value="' + value + '" name="block_providers" checked="checked" />' + label + '</label></li>'
             $('.providers ul').append(html);
          }
       });
    }

    // ASX portfolio form
    if ($('#id_portfolio').length > 0) {
        AUTOCOMPLETE_COMMA_CACHE = '';     /*global previous autocomplete string*/
        $("#id_portfolio").autocomplete("/trader/codes/", {
            minChars:1,
            resultsClass:'code_suggestions',
            cacheLength :1,
            maxItemsToShow:15,
            delay:1,
            width:230,
            padCommas:true,
            autoFill:false,
            onItemSelect:function() { $("#id_portfolio").focus();}
        });
        $("#id_portfolio").keypress(function(e){
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                asxann_search();
                return false;
            } else {
                $("#id_portfolio")[0].autocompleter.flushCache();
                AUTOCOMPLETE_COMMA_CACHE = $("#id_portfolio").val();
                return true;
            }
        });
    }

});

function add_recommend() {
    str = this.innerHTML;
    target = $('textarea', $(this).parents('.recommend-wrap'))[0];
    if(!target) {
        target = $('textarea', $(this).parents('.form-row').find('.recommend-wrap'))[0]
    }

    if (!target) return;
    if (target.value.indexOf(str) >= 0) return;
    if (target.value != '') {
        str = target.value + ', ' + str;
    }
    target.value = str;
    update_recommend();
}

function inject_recommend(j, d) {
    $('span',j).html(d);
    if (d != '' && d != undefined) {
        j.slideDown();
    } else {
        j.slideUp();
    }
    $('a',j).click(add_recommend);
}

function update_recommend() {
    // build string
    str = get_industries().join(', ')
    if ($("#id_companies").val() != '' && $("#id_companies").val() != undefined)
        str += $("#id_companies").val() + ', ';
    if ($("#id_people").val() != ''  && $("#id_people").val() != undefined)
        str += $("#id_people").val() + ', ';
    if ($("#id_filter").val() != '' && $("#id_filter").val() != undefined)
        str += $("#id_filter").val() + ', ';
    if (str == '') return;

    // ajax call
    callcount += 1;
    $.get('/profile/recommend/', {s:str, c:callcount}, function(data) {
        data = data.split('|');
        if (Number(data[0]) < callcount) return;
        inject_recommend($('#recommend_4'), data[2]);
        inject_recommend($('#recommend_2'), data[1]);
    });
}

function get_industries(){
    var vals = new Array()
    $('.industry input:checked').each(function(){
        vals.push(this.value);
    });
    return vals;
}

function clear_industries() {
    $('.industry input:checked').each(function(){
        this.checked = false;
    });
    update_recommend();
    update_industry_count();
}

function update_industry_count(){
    get_article_count_update("", get_industries(), $('#industry_count_id')[0]);
    get_total_article_count();
}

function get_total_article_count() {
    f =""
    if ($('#id_company').val()!=undefined){f += $('#id_company').val() + ","};
    if ($('#id_companies').val()!=undefined){f += $('#id_companies').val() + ","};
    if ($('#id_people').val()!=undefined){f += $('#id_people').val() + ","};
    if ($('#id_filter').val()!=undefined){f += $('#id_filter').val() + ","};
    if ($('#id_products').val()!=undefined){f += $('#id_products').val() + ","};
    if ($('#id_interests').val()!=undefined){f += $('#id_interests').val() + ","};
    if ($('#article_count_id').length > 0)
        get_article_count_update(f,get_industries(),$('#article_count_id')[0]);
}

function get_article_count(filter,eid){
    get_article_count_update(filter,"",eid);
    get_total_article_count();
}

function get_article_count_update(filter,ids,eid){
    if (!eid) return;
    var postData = "filter="+filter + "&industry_ids=" + ids + "&block=" + $("#id_stopwords").val();
    var handleSuccess = function(responseText ){
        if(responseText !== undefined){
            eid.innerHTML = responseText + " articles";
        }else{
            eid.innerHTML = "0 articles";
        }}
    jQuery.get( "/ajax/count/", postData, handleSuccess );
}

function clean_csv_input(field){
    var ctext=field.value;
    ctext=xReplace(ctext,"\r\n","\n")
    ctext=xReplace(ctext,"\n",", ")
    ctext=xReplace(ctext,",,",", ")
    ctext=xReplace(ctext,";",",")
    ctext=xReplace(ctext,"?","")
    if (Right(ctext,2)==", "){ctext=Left(ctext,Len(ctext)-2);}
    if (Right(ctext,1)==","){ctext=Left(ctext,Len(ctext)-1);}
    field.value=ctext;
}


/* UTIL STRING FUNCTIONS */
function xReplace(checkMe,toberep,repwith){
var temp = checkMe;
var i = temp.indexOf(toberep);
while(i > -1){
temp = temp.replace(toberep, repwith);
i = temp.indexOf(toberep);}
return temp;}
function Left(str, n){
if (n <= 0)
return "";
else if (n > String(str).length)
return str;
else
return String(str).substring(0,n);}
function Right(str, n){
if (n <= 0)
return "";
else if (n > String(str).length)
return str;
else {
var iLen = String(str).length;
return String(str).substring(iLen, iLen - n);
}}
function Len(str){return String(str).length;}
