var msg_confirm_del = 'Вы на самом деле хотите удалить?';

var last_submenu = 'advertise';

function showSubMenu(li, sub) {
    if( document.getElementById('sub-menu-'+sub) ) {

        $("#menu-container > li").removeClass('active');

        document.getElementById('sub-menu-'+last_submenu).style.display = 'none';
        document.getElementById('sub-menu-'+sub).style.display = 'block';
        last_submenu = sub;
    }
}

function confirmDelete() {
    if ( confirm( msg_confirm_del ) ) {
        return true;
    } else {
        return false;
    }
}

function finewebEqualBlockHeight() {
    var newsList = $('#div-news-block').height() - 76;
    var projectList = $('#table-projects-list').height() - 76;

    if (newsList > projectList) {
        $('#table-projects-list').height(newsList);
    }

    if (newsList < projectList) {
        $('#div-news-block').height(projectList);
    }
}

function bar2pie() {

    data.elements[0]['type'] = 'pie';
    data.elements[0]['tip'] = data.elements[0]['tip']+' #percent#';
    data.elements[0]['animate'] = true;
    data.elements[0]['gradient-fill'] = true;
    data.elements[0]['no-labels'] = false;
    data.elements[0]['highlight'] = "alpha";
    data.elements[0]['radius'] = 130;
    data.elements[0]['colours'] = ["#ff0000","#00ff00","#0000ff","#ff9900","#ff00ff","#FFFF00","#6699FF","#339933"];

    var elementsValues = new Array;
    for ( var i in data.elements[0]['values'] )
    {
        elementsValues[i] = {'value':data.elements[0]['values'][i], 'label':data.x_axis.labels.labels[i], 'text':data.x_axis.labels.labels[i]}
    }
    delete(data.x_axis);
    delete(data.y_axis);
    delete(data.y_legend);
    delete(data.menu);
    data.elements[0]['values'] = elementsValues;
    swfobject.embedSWF(staticUrl+"js/open-flash-chart.swf", "my_chart", "100%", "100%", "9.0.0");
}


function campaignTxtAreaResizer() {
    $('#geo_targeting').TextAreaResizer();
    $('#time_targeting').TextAreaResizer();
    $('#action_targeting').TextAreaResizer();
    $('#bonus_shows').TextAreaResizer();
}

function bindConfirmDelete() {
    $('a.delete').click(function() {
        return confirmDelete();
    });
}


function campaignTypeClick(what) {
    if(what.value == 'nonstndrt') {
        $("#type_comment").show();
        $("#project_properties").hide();
        $("#type_comment").attr('disabled', '');

        $("#targeting_table_body").hide();
        $("#targeting_table_body input").attr('disabled','disabled');

    } else {
        $("#type_comment").hide();
        $("#type_comment").attr('disabled', 'disabled');
    }
}


function campaignTargetTypeClick(what) {
    if(what.value == 'site') {
        $("#tr_sites").show();
        $("#tr_packets").hide();
    }

    if(what.value == 'packet') {
        $("#tr_sites").hide();
        $("#tr_packets").show();
    }
}


function campaignAccomodationTypeClick(what) {
    if(what.value == 'b' || what.value == 'c') {
        $("#accommodation_type_comment").hide();
        $("#accommodation_type_comment").attr('disabled', 'disabled');
    }

    if(what.value == 's') {
        $("#accommodation_type_comment").show();
        $("#accommodation_type_comment").attr('disabled', '');
    }
}


function bindActionTriggers() {

    $('#who_pay').click(function() {
        if ($(this).attr('checked')) {
            $("#who_request").html('');
            $("#who_request_workers").html('');
            FormControl.addActionAgency('who_request', 1);
        } else {
            $("#who_request").html('');
            $("#who_request_workers").html('');
        }
    });

    $('#who_pay2').click(function() {
        if ($(this).attr('checked')) {
            $("#who_direct_client_type_input").show();
            $("#who_direct_client_type_input input").attr('disabled','');
            $("#who_request2").html('');
            $("#who_request_workers2").html('');
        } else {
            $("#who_direct_client_type_input input").attr('disabled','disabled');
            $("#who_direct_client_type_input input").attr('checked','');
            $("#who_direct_client_type_input").hide();
            $("#who_request2").html('');
            $("#who_request_workers2").html('');
        }
    });

    $('#who_pay_client_type_b').click(function() {
        FormControl.addActionBrand('who_request2',1)
    });

    $('#who_pay_client_type_o').click(function() {
        FormControl.addActionAdvertiser('who_request2',1)
    });
}


function bindCampaignTriggers() {

    $('#project_id').change(function() {

        var project_id = document.getElementById('project_id').value;
        var type_d = $('#type_d').attr('checked');
        var type_p = $('#type_p').attr('checked');

        if (0 < project_id) {

            $('#type_p').attr('disabled','');

            if (type_d) {
                FormControl.dynamicCampaign(project_id);
            }
            if (type_p) {
                FormControl.PayMaterialCampaign(project_id);
            }

            document.getElementById('packet_id').value = 0;
            $("#final_divide_summ").html('');
            $("#final_divide_btw_sts").hide();
        }

    });

    $('#packet_id').change(function() {

        var selected = document.getElementById('packet_id').value;

        if (0 < selected) {
            $('#type_d').attr('checked','checked');
            $('#type_p').attr('disabled','disabled');
            document.getElementById('project_id').value = 0;

            FormControl.dynamicCampaign();
            FormControl.getPackSites(selected);
        }
    });

    $('#auto_calc').click(function() {
        FormControl.autoCalc();
    });

    $('#type_d').click(function() {
        var project_id = document.getElementById('project_id').value;
        return FormControl.dynamicCampaign(project_id);
    });

    $('#type_p').click(function() {
        var project_id = document.getElementById('project_id').value;
        return FormControl.PayMaterialCampaign(project_id);
    });

    $('#who_pay').click(function() {
        $("#who_direct_client_type_input").hide();
        $("#who_direct_client_type_input input").attr('disabled','disabled');
        $("#who_direct_client_type_input input").attr('checked','');
        $("#who_request").html('');
        $("#who_request_workers").html('');
        FormControl.addSelectAgency('who_request', 1);
    });

    $('#who_pay2').click(function() {
        $("#who_direct_client_type_input").show();
        $("#who_direct_client_type_input input").attr('disabled','');
        $("#who_request").html('');
        $("#who_request_workers").html('');
        FormControl.discount = 0;
        $("#discount").val(0);
    });

    $('#who_pay_client_type_b').click(function() {
        FormControl.addSelectBrand('who_request',1)
    });

    $('#who_pay_client_type_o').click(function() {
        FormControl.addSelectAdvertiser('who_request',1)
    });
}


function datePicker(selector) {
    $(selector).datePicker({ chooseDateText: '<img src="'+baseUrl+'/images/icons/calendar.gif" alt="" border="0" />', startDate: '1990-01-01' });
}

FormControl = {};

FormControl.selectId = '';
FormControl.agencyDOMid = '';
FormControl.typeCounter = new Array();
FormControl.advPlatform = new Array();
FormControl.advMaterial = new Array();
FormControl.advPacketsCpm  = new Array();
FormControl.discount = 0;
FormControl.campaignSelector = 0;
FormControl.preActionCounter = 0;
FormControl.postActionCounter = 0;
FormControl.cpm = 0;
FormControl.i = 0;
FormControl.tmp = '';
FormControl.generalPlanSumm = 0;
FormControl.errors = '';

FormControl.planSumm = function() {

    FormControl.generalPlanSumm = 0;

    $("#departments input").each(function (i) {
        var sum = parseInt(this.value);
        if (sum) FormControl.generalPlanSumm = FormControl.generalPlanSumm + sum;
    });

    $("#summ").val(FormControl.generalPlanSumm);
}

FormControl.toggleAdress = function(checkbox) {

    if(checkbox.value == 'meet') {
        $("#adress").attr('disabled','');
        $("#adress").show();
        $("#div_adress").show();
        return;
    }

    if(checkbox.value != 'meet') {
        $("#adress").attr('disabled','disabled');
        $("#adress").hide();
        $("#div_adress").hide();
        return;
    }
}

FormControl.toggleResult = function(checkbox) {

    if(checkbox.value == 'done') {
        $("#results").attr('disabled','');
        $("#results").show();
        $("#div_results").show();
        return;
    }

    if(checkbox.value != 'done') {
        $("#results").attr('disabled','disabled');
        $("#results").hide();
        $("#results").val('');
        $("#div_results").hide();
        return;
    }
}

FormControl.getDiscount = function() {
    FormControl.discount = $("#discount").val();
}

FormControl.autoCalc = function() {

    FormControl.getDiscount();
    var showsCount = $("#shows").val();
    var project_id = document.getElementById('project_id').value;
    var markup_percent = document.getElementById('markup_percent').value;
    var cpm_finded = 0;
    var priceWithoutDiscount = 0;
    var summ = 0;

    if (document.getElementById('packet_id') != 'undefined') {
        var packet_id = document.getElementById('packet_id').value;
    } else {
        var packet_id = 0;
    }


    //If it Project Campaign
    if (0 < project_id) {
        if (document.getElementById('material_id')) {
            material_id = document.getElementById('material_id').value;

            $.each(FormControl.advMaterial[project_id], function(i,item) {
                if (item.id == material_id) {
                    FormControl.cpm = item.cpm;
                    cpm_finded = 1;
                }
                if (cpm_finded == 0){
                    FormControl.cpm = 0;
                }
            });

            priceWithoutDiscount = FormControl.cpm;
        }

        if (document.getElementById('platform')) {
            platform = document.getElementById('platform').value;

            $.each(FormControl.advPlatform[project_id], function(i,item) {
                if (item.title == platform) {
                    FormControl.cpm = item.cpm;
                    cpm_finded = 1;
                }
                if (cpm_finded == 0){
                    FormControl.cpm = 0;
                }
            });

            priceWithoutDiscount = showsCount * FormControl.cpm / 1000;

        }
    }

    //If it Packet Campaign
    if (0 < packet_id) {
        FormControl.cpm = FormControl.advPacketsCpm[packet_id];
        priceWithoutDiscount = showsCount * FormControl.cpm / 1000;
    }

    $("#price_before").val(priceWithoutDiscount);
    if (0 < FormControl.discount) {
        summ = priceWithoutDiscount * (1 - FormControl.discount / 100);
    } else {
        summ = priceWithoutDiscount;
    }
    if (0 < markup_percent) {
        summ = summ * (1 + markup_percent / 100);
    }

    $("#summ").val(summ);

    return true;
}


FormControl.updateCampaignStatus = function(id, checkbox) {

    var callBackError = function(data) {
        alert('Ajax error');
        return;
    }

    var callBack = function( data ) {
        if(data.success) {
            if (status == 1) {
                checkbox.checked = true;
            } else {
                checkbox.checked = false;
            }
        } else {
            if (status == 1) {
                checkbox.checked = false;
            } else {
                checkbox.checked = true;
            }
        }
        return;
    }

    if (checkbox.checked == true) {
        status = 1;
    }

    if (checkbox.checked == false) {
        status = 0;
    }

    $.ajax({
        type: "POST",
        url: baseUrl+'admin/campaign/updatestatus/',
        data: {id:id, status:status},
        dataType: "json",
        success: callBack,
        error: callBackError
    });
}


FormControl.getSiteRubrics = function(dom) {

    var callBackError = function(data) {
        alert('Ajax error');
        return;
    }

    var callBack = function( data ) {
        var html = '<select name="rubric_id" id="rubric">';
        if(data.success) {
            for ( var i in data.data ) {
                html+='<option value="'+data.data[i]['id']+'">'+data.data[i]['name']+'</option>';
            }
        }
        html+='</select>';
        html+='<a onclick="return FormControl.addSiteRubric(\'rubric\');" title="Добавить рубрику" href="#"><img hspace="2" border="0" align="left" alt="Добавить рубрику" src="'+staticUrl+'images/icons/user_16_add.gif"/></a>';
        $("#rubric_select").html(html);
        return;
    }

    var id = dom.value;
    $("#rubric_select").html('');
    $.ajax({
        type: "POST",
        url: baseUrl+'admin/projects/rubric/?type=json&project_id='+id,
        data: {},
        dataType: "json",
        success: callBack,
        error: callBackError
    });

    return false;
}


FormControl.getPackSites = function(id) {

    var callBackError = function(data) {
        FormControl.errors += 'getPackSites error / ';
        return;
    }

    var callBack = function( data ) {
        if(data.success) {

            var html = '<table>';
            $.each(data.sites, function(i,item) {
                html += '<tr><td><label for="site_'+item.id+'">'+item.name+' </label></td><td>&nbsp;<input type="text" size="20" class="width_auto2" maxlenght="40" id="site_'+item.id+'" name="summ_divide['+item.id+']" value="" /></td></tr>';
            });
            html+='</table>';

            $("#final_divide_summ").html(html);
            $("#final_divide_btw_sts").show();
        }
        return;
    }

    $.ajax({
        type: "POST",
        url: baseUrl+'admin/pack/export/'+id,
        data: {},
        dataType: "json",
        success: callBack,
        error: callBackError
    });

    return false;
}

FormControl.dynamicCampaign = function(param, select) {
    var project_id = param;
    if (project_id =='undefined') {
        project_id = document.getElementById('project_id').value;
    }

    if (select == 'undefined') {
        var select = '';
    }

    if (0 < project_id) {
        $.getJSON(baseUrl+"admin/projects/platform/"+project_id,
        function(data) {
            FormControl.advPlatform[project_id] = data;
            var html = '<label class="small">'+adv_platform+' <select name="platform" id="platform">';
            html = html + '<option value=""> '+msg_choose+' </option>';
            $.each(data, function(i,item) {
                if (select !='' && item.title == select) {
                    html = html + '<option value="'+item.title+'" selected="selected">'+item.title+'</option>';
                } else {
                    html = html + '<option value="'+item.title+'">'+item.title+'</option>';
                }
            });
            html = html + "</select></label>";
            $("#project_properties").html(html);
            $("#project_properties").show();

        });
    } else {
        $("#project_properties").html('');
        $("#project_properties").hide();
    }

    $("#targeting_table_body").show();
    $("#targeting_table_body input").attr('disabled','');
}

FormControl.PayMaterialCampaign = function(param, select) {

    var project_id = param;
    if (project_id =='undefined') {
        project_id = document.getElementById('project_id').value;
    }

    if (select == 'undefined') {
        var select = '';
    }

    if (0 < project_id) {
        $.getJSON(baseUrl+"admin/projects/materials/"+project_id,
        function(data) {
            FormControl.advMaterial[project_id] = data;
            var html = '<label class="small">'+adv_mat_type+' <select name="f_material_id" id="material_id">';
            html = html + '<option value=""> '+msg_choose+' </option>';
            $.each(data, function(i,item) {
                if (select !='' && item.id == select) {
                    html = html + '<option value="'+item.id+'" selected="selected">'+item.title+'</option>';
                } else {
                    html = html + '<option value="'+item.id+'">'+item.title+'</option>';
                }
            });
            html = html + "</select></label>";
            $("#project_properties").html(html);
            $("#project_properties").show();

        });
    } else {
        $("#project_properties").html('');
        $("#project_properties").hide();
    }

    $("#targeting_table_body").hide();
    $("#targeting_table_body input").attr('disabled','disabled');
}

FormControl.setTypeCounter = function(name, value) {
    FormControl.typeCounter[name] = value;
}


FormControl.addSelectBrand = function(name, value) {

    if (!FormControl.typeCounter[name] && !value) {
        FormControl.setTypeCounter(name, 2);
    } else {
        if (!FormControl.typeCounter[name] && value) {
            FormControl.setTypeCounter(name, value+1);
        } else {
            FormControl.typeCounter[name]++;
        }
    }

    FormControl.discount = 0;
    $("#discount").val(0);

    var htmlSelect = ''
    $.get(baseUrl+"map/brand/export/?type=htmlselect&select_name=who_f_brand_id&getPeople=1&counter="+FormControl.typeCounter[name], function(data) {
        data+='<a href="#" title="Создать бренд" onclick="return FormControl.addBrand(\'brand-'+FormControl.typeCounter[name]+'\');"><img src="'+baseUrl+'images/icons/user_16_add.gif" alt="Создать бренд" border="0" align="left" hspace="2" /></a>';
        $('#'+name).html(data);
    });
}

/**
*
* Actions
* Section
*
*/


FormControl.fromParentToChildrenSelects = function(parent, current) {
    if (!parent) return false;

    var selectedArray = new Array();
    for (var i = 0; i < parent.options.length; i++) {
        if (parent.options[i].selected == true) selectedArray.push(parent.options[i].value);
    }

    for (var i = 0; i < current.options.length; i++) {
        current.options[i].selected = false;
        if (jQuery.inArray(current.options[i].value, selectedArray) !== -1) {
            current.options[i].selected = true;
        }
    }
}


FormControl.addActionParentProperties = function() {

    var parentSelect = window.opener.document.getElementById('profile_id');
    var currentSelect = document.getElementById('profile_id');
    FormControl.fromParentToChildrenSelects(parentSelect, currentSelect);


    var parentTouchingBO = window.opener.document.getElementById('touching_brand_owner');
    var currentTouchingBO = document.getElementById('touching_brand_owner');
    FormControl.fromParentToChildrenSelects(parentTouchingBO, currentTouchingBO);


    var parentTouchingBrand = window.opener.document.getElementById('touching_brand');
    var currentTouchingBrand = document.getElementById('touching_brand');
    FormControl.fromParentToChildrenSelects(parentTouchingBrand, currentTouchingBrand);

    var parentWhoPay = window.opener.document.getElementById('who_pay');
    var currentWhoPay = document.getElementById('who_pay');
    if (parentWhoPay.checked == true) {
        currentWhoPay.checked = true;

        $(document.getElementById('who_request')).html($(window.opener.document.getElementById('who_request')).html());


        if (typeof(window.opener.document.getElementById('who_agency')) != 'undefined' || typeof(document.getElementById('who_agency')) != 'undefined') {
            var parentAgency = window.opener.document.getElementById('who_agency');
            var currentAgency = document.getElementById('who_agency');
            FormControl.fromParentToChildrenSelects(parentAgency, currentAgency);
            $("#who_agency").change();
        }

        if (typeof(window.opener.document.getElementById('who_person_id')) != 'undefined' || typeof(document.getElementById('who_person_id')) != 'undefined') {
            var parentPerson = window.opener.document.getElementById('who_person_id');
            var currentPerson = document.getElementById('who_person_id');
            FormControl.fromParentToChildrenSelects(parentPerson, currentPerson);
        }
    }

    if (window.opener.document.getElementById('who_pay2').checked == true) {
        document.getElementById('who_pay2').checked = true;
        $("#who_direct_client_type_input").show();

        if (window.opener.document.getElementById('who_pay_client_type_b').checked == true) {
            document.getElementById('who_pay_client_type_b').checked = true
        }

        if (window.opener.document.getElementById('who_pay_client_type_o').checked == true) {
            document.getElementById('who_pay_client_type_o').checked = true
        }

        $(document.getElementById('who_request2')).html($(window.opener.document.getElementById('who_request2')).html());

        if (document.getElementById('who_brand_owner')) {

            var parent = window.opener.document.getElementById('who_brand_owner');
            var current = document.getElementById('who_brand_owner');
            FormControl.fromParentToChildrenSelects(parent, current);

            $(document.getElementById('who_brand_owner')).change();

            if (typeof(window.opener.document.getElementById('who_person_id2')) != 'undefined' || typeof(document.getElementById('who_person_id2')) != 'undefined') {
                var parentPerson = window.opener.document.getElementById('who_person_id2');
                var currentPerson = document.getElementById('who_person_id2');
                FormControl.fromParentToChildrenSelects(parentPerson, currentPerson);
            }

        }

        if (document.getElementById('who_brand')) {

            var parent = window.opener.document.getElementById('who_brand');
            var current = document.getElementById('who_brand');
            FormControl.fromParentToChildrenSelects(parent, current);

            $(document.getElementById('who_brand')).change();

            if (typeof(window.opener.document.getElementById('who_person_id2')) != 'undefined' || typeof(document.getElementById('who_person_id2')) != 'undefined') {
                var parentPerson = window.opener.document.getElementById('who_person_id2');
                var currentPerson = document.getElementById('who_person_id2');
                FormControl.fromParentToChildrenSelects(parentPerson, currentPerson);
            }

        }
    }
}

FormControl.addAction = function(id) {
    FormControl.selectId = id;
    var d = new Date();

    window.open(baseUrl+'admin/actions/add/?from_window=1','people'+d.getTime(),'width=1000,height=700,resizable=yes,status=yes,toolbar=no,location=no,menubar=no,scrollbars=yes');
    return false;
}


FormControl.addActionOption = function(name, value) {
    var id = FormControl.selectId;
    var html = '<option value="'+value+'" selected="selected">'+name+'</option>';
    $("#"+id+' option:selected').attr('selected','');
    $("#"+id+' ').append(html);

    return false;
}


FormControl.addActionSelector = function(counter, type) {

    var domID = '';
    var html = '';

    if (!counter || typeof(counter) == 'undefined') counter = 0;

    if ( 0 < counter) {
        if (type == 'pre') {
            FormControl.preActionCounter+=counter;
        }

        if (type == 'post') {
            FormControl.postActionCounter+=counter;
        }
    } else {
        if (type == 'pre') {
            FormControl.preActionCounter+=1;
        }
        if (type == 'post') {
            FormControl.postActionCounter+=1;
        }
    }

    if (type == 'pre') {
        domID = 'pre_actions';

        html += '<table width="100%" border="0" cellpadding="2" cellspacing="2"><tr>';
        html += '<td width="15%" align="center"><input type="text" name="pre_actions_date" id="pre_actions_date" value="" size="10" class="width_auto" onchange="FormControl.getActions(this, '+FormControl.preActionCounter+',\'pre\');" /></td>';
        html += '<td width="85%"><span id="pre_actions_'+FormControl.preActionCounter+'"><select id="sel_pre_actions_'+FormControl.preActionCounter+'" name="preactions[]"><option value="0">'+msg_actions_index+'</option></select><a href="#" onclick="return FormControl.addAction(\'sel_pre_actions_'+FormControl.preActionCounter+'\');"><img src="'+staticUrl+'images/icons/user_16_add.gif" alt="" border="0" align="left" hspace="2" /></a></span></td>';
        html += '</tr></table>';
    }

    if (type == 'post') {
        domID = 'post_actions';

        html += '<table width="100%" border="0" cellpadding="2" cellspacing="2"><tr>';
        html += '<td width="15%" align="center"><input type="text" name="post_actions_date" id="post_actions_date" value="" size="10" class="width_auto" onchange="FormControl.getActions(this, '+FormControl.postActionCounter+', \'post\');" /></td>';
        html += '<td width="85%"><span id="post_actions_'+FormControl.postActionCounter+'"><select id="sel_post_actions_'+FormControl.postActionCounter+'" name="postactions[]"><option value="0">'+msg_actions_index+'</option></select><a href="#" onclick="return FormControl.addAction(\'sel_post_actions_'+FormControl.postActionCounter+'\');"><img src="'+staticUrl+'images/icons/user_16_add.gif" alt="" border="0" align="left" hspace="2" /></a></span></td>';
        html += '</tr></table>';
    }

    if (html != '') {
        var ul = document.getElementById(domID);
        var li = document.createElement('li');
        li.innerHTML = html;
        ul.appendChild(li);
        datePicker('input.width_auto');
    }
}


FormControl.getActions = function(dom, counter, type) {

    var domID = '';
    var selectName = '';
    if (type == 'pre') {
        domID = 'pre_actions_'+counter;
        selectName = 'preactions[]';
    }

    if (type == 'post') {
        domID = 'post_actions_'+counter;
        selectName = 'postactions[]';
    }

    var callBackError = function(data) {
        $('#'+domID).html('');
        return;
    }

    var callBack = function(data) {
        $('#'+domID).html('');
        var html = '<select name="'+selectName+'" id="sel_'+domID+'">';
        html+='<option value="">'+msg_actions_index+'</option>';

        if(data.success) {
            for ( var i in data.data ) {
                html += '<option value="'+data.data[i]['id']+'">'+data.data[i]['title']+'</option>';
            }
        }

        html += '</select>';
        html += '<a href="#" onclick="return FormControl.addAction(\'sel_'+domID+'\');"><img src="'+staticUrl+'images/icons/user_16_add.gif" alt="" border="0" align="left" hspace="2" /></a>';
        $('#'+domID).html(html);

        return;
    }

    $.ajax({
        type: "GET",
        url: baseUrl+"admin/actions/?json=1&date="+dom.value,
        data: {},
        dataType: "json",
        success: callBack,
        error: callBackError
    });

}


FormControl.addActionBrand = function(name, value) {

    if (!FormControl.typeCounter[name] && !value) {
        FormControl.setTypeCounter(name, 2);
    } else {
        if (!FormControl.typeCounter[name] && value) {
            FormControl.setTypeCounter(name, value+1);
        } else {
            FormControl.typeCounter[name]++;
        }
    }

    var callBackError = function(data) {
        return;
    }

    var callBack = function(data) {
        var html = '<select name="brand_id[]" id="who_brand" size="5" multiple="multiple" onchange="FormControl.getPeople(this, \'brand\');FormControl.getAdress(this, \'brand\');">';
        if(data.success) {
            for ( var i in data.data ) {
                html += '<option value="'+data.data[i]['id']+'">'+data.data[i]['name']+'</option>';
            }
        }
        html += '</select>';
        html += '<a href="#" onclick="return FormControl.addBrand(\'who_brand\');"><img src="'+baseUrl+'images/icons/user_16_add.gif" alt="" border="0" align="left" hspace="2" /></a>';
        $('#'+name).html(html);
        return;
    }

    $.ajax({
        type: "GET",
        url: baseUrl+"map/brand/export/?type=json&select_name=who_f_brand_id&getPeople=1&counter="+FormControl.typeCounter[name],
        data: {},
        dataType: "json",
        success: callBack,
        error: callBackError
    });

}

FormControl.addSelectAdvertiser = function(name, value) {

    if (!FormControl.typeCounter[name] && !value) {
        FormControl.setTypeCounter(name, 2);
    } else {
        if (!FormControl.typeCounter[name] && value) {
            FormControl.setTypeCounter(name, value+1);
        } else {
            FormControl.typeCounter[name]++;
        }
    }

    FormControl.discount = 0;
    $("#discount").val(0);

    var htmlSelect = ''
    $.get(baseUrl+"map/advertisers/export/?type=htmlselect&select_name=who_f_advertiser_id&getPeople=1&counter="+FormControl.typeCounter[name], function(data) {
        data+='<a href="#" title="Создать владельца бренда" onclick="return FormControl.addAdvertiser(\'advertisers-'+FormControl.typeCounter[name]+'\');"><img src="'+baseUrl+'images/icons/user_16_add.gif" alt="Создать владельца бренда" border="0" align="left" hspace="2" /></a>';
        $('#'+name).html(data);
    });
}

FormControl.addActionAdvertiser = function(name, value) {

    if (!FormControl.typeCounter[name] && !value) {
        FormControl.setTypeCounter(name, 2);
    } else {
        if (!FormControl.typeCounter[name] && value) {
            FormControl.setTypeCounter(name, value+1);
        } else {
            FormControl.typeCounter[name]++;
        }
    }

    var callBackError = function(data) {
        return;
    }

    var callBack = function(data) {
        var html = '<select name="brand_owner_id[]" id="who_brand_owner" size="5" multiple="multiple" onchange="FormControl.getPeople(this, \'brand_owner\');FormControl.getAdress(this, \'brand_owner\');">';
        if(data.success) {
            for ( var i in data.data ) {
                html += '<option value="'+data.data[i]['id']+'">'+data.data[i]['name']+'</option>';
            }
        }
        html += '</select>';
        html += '<a href="#" onclick="return FormControl.addAdvertiser(\'who_brand_owner\');"><img src="'+baseUrl+'images/icons/user_16_add.gif" alt="" border="0" align="left" hspace="2" /></a>';
        $('#'+name).html(html);

        return;
    }

    $.ajax({
        type: "GET",
        url: baseUrl+"map/advertisers/export/?type=json&select_name=who_f_advertiser_id&getPeople=1&counter="+FormControl.typeCounter[name],
        data: {},
        dataType: "json",
        success: callBack,
        error: callBackError
    });
}


FormControl.addSelectAgency = function(name, value) {

    if (!FormControl.typeCounter[name] && !value) {
        FormControl.setTypeCounter(name, 2);
    } else {
        if (!FormControl.typeCounter[name] && value) {
            FormControl.setTypeCounter(name, value+1);
        } else {
            FormControl.typeCounter[name]++;
        }
    }
    FormControl.agencyDOMid = 'agency-'+FormControl.typeCounter[name];
    var htmlSelect = ''
    $.get(baseUrl+"map/agency/export/?type=htmlselect&select_name=who_f_agency_id&counter="+FormControl.typeCounter[name]+"&getPeople=1", function(data) {
        data += '<a href="#" title="Создать агенцию" onclick="return FormControl.addAgency(\'agency-'+FormControl.typeCounter[name]+'\');"><img src="'+baseUrl+'images/icons/user_16_add.gif" alt="Создать агенцию" border="0" align="left" hspace="2" /></a>';
        $('#'+name).html(data);
    });
}


FormControl.addActionAgency = function(name, value) {

    if (!FormControl.typeCounter[name] && !value) {
        FormControl.setTypeCounter(name, 2);
    } else {
        if (!FormControl.typeCounter[name] && value) {
            FormControl.setTypeCounter(name, value+1);
        } else {
            FormControl.typeCounter[name]++;
        }
    }
    FormControl.agencyDOMid = 'agency-'+FormControl.typeCounter[name];

    var callBackError = function(data) {
        return;
    }

    var callBack = function(data) {
        var html = '<select name="agency_id[]" id="who_agency" size="5" multiple="multiple" onchange="FormControl.getPeople(this, \'agency\');FormControl.getAdress(this, \'agency\');">';
        if(data.success) {
            for ( var i in data.data ) {
                html += '<option value="'+data.data[i]['id']+'">'+data.data[i]['name']+'</option>';
            }
        }
        html += '</select>';
        html += '<a href="#" onclick="return FormControl.addAgency(\'who_agency\');"><img src="'+baseUrl+'images/icons/user_16_add.gif" alt="" border="0" align="left" hspace="2" /></a>';
        $('#'+name).html(html);
        return;
    }

    $.ajax({
        type: "GET",
        url: baseUrl+"map/agency/export/?type=json&select_name=who_f_agency_id&counter="+FormControl.typeCounter[name]+"&getPeople=1",
        data: {},
        dataType: "json",
        success: callBack,
        error: callBackError
    });
}


FormControl.getPeople = function(domSelect, type) {
    var gotWorkers = 0;
    var id = domSelect.id;
    var domID = 'who_request_workers';
    var url = '';
    var html = '<select name="person_id[]" id="who_person_id" size="5" multiple="multiple">';
    FormControl.tmp = '';
    FormControl.i = 0;

    var personsArray = new Array();
    if (type == 'brand') {
        url = baseUrl+"map/people/export/?type=json&brand=";
        domID = 'who_request_workers2';
        html = '<select name="person_id[]" id="who_person_id2" size="5" multiple="multiple">';
    }

    if (type == 'brand_owner') {
        url = baseUrl+"map/people/export/?type=json&brand_owner=";
        domID = 'who_request_workers2';
        html = '<select name="person_id[]" id="who_person_id2" size="5" multiple="multiple">';
    }

    if (type == 'agency') {
        url = baseUrl+"map/people/export/?type=json&agency=";
    }

    $('#'+id+" option:selected").each(function () {
        var callBackError = function(data) {
            return;
        }

        var callBack = function(data) {
            if(data.success) {
                FormControl.i++;
                for ( var i in data.data ) {
                    FormControl.tmp += '<option value="'+data.data[i]['id']+'">'+data.data[i]['name']+'</option>';
                }
            }
            return;
        }

        $.ajax({
            type: "GET",
            url: url + $(this).val(),
            data: {},
            async: false,
            dataType: "json",
            success: callBack,
            error: callBackError
        });
    });

    if (0 < FormControl.i) {
        html += FormControl.tmp;
        html += '</select>';
        $('#'+domID).html(html);
    } else {
        $('#'+domID).html('');
    }
}

FormControl.getAdress = function(domSelect, type) {

    if ($("#type_meet").attr('checked') == false ) return false;
    if ($("#adress").val() != '' ) return false;

    var url = '';

    if (type == 'brand') {
        url = baseUrl+"map/brand/view/"+domSelect.value+"/?type=json&property=address";
    }

    if (type == 'brand_owner') {
        url = baseUrl+"map/advertisers/view/"+domSelect.value+"/?type=json&property=address";
    }

    if (type == 'agency') {
        url = baseUrl+"map/agency/view/"+domSelect.value+"/?type=json&property=address";
    }

    var callBackError = function(data) {
        return;
    }

    var callBack = function(data) {
        if(data.success) {
            $("#adress").val(data.data);
        } else {
            $("#adress").val('');
        }
        return;
    }

    $.ajax({
        type: "GET",
        url: url,
        data: {},
        async: false,
        dataType: "json",
        success: callBack,
        error: callBackError
    });
}

FormControl.changeAgencyPeople = function(name, value, agencyID) {

    if (!FormControl.typeCounter[name] && !value) {
        FormControl.setTypeCounter(name, 2);
    } else {
        if (!FormControl.typeCounter[name] && value) {
            FormControl.setTypeCounter(name, value+1);
        } else {
            FormControl.typeCounter[name]++;
        }
    }

    var htmlSelect = ''
    $.get(baseUrl+"map/people/export/?type=htmlselect&agency="+agencyID+"&select_name=who_f_person_id&counter="+FormControl.typeCounter[name], function(data) {
        data += '<a href="#" title="Создать человека" onclick="return FormControl.addPeople(\'people-'+FormControl.typeCounter[name]+'\');"><img src="'+baseUrl+'images/icons/user_16_add.gif" alt="Создать человека" border="0" align="left" hspace="2" /></a>';
        $('#who_request_workers').html(data);
    });

    var callBackError = function(data) {
        FormControl.discount = 0;
        $("#discount").val(0);
        return;
    }
    var callBack = function(data) {
        if (data.success == 1) {
            FormControl.discount = data.discount;
            $("#discount").val(data.discount);
        } else {
            FormControl.discount = 0;
            $("#discount").val(0);
        }
        return;
    }
    $.ajax({
        type: "GET",
        url: baseUrl+"admin/campaign/agency-discount/"+agencyID,
        data: {},
        dataType: "json",
        success: callBack,
        error: callBackError
    });
}

FormControl.getBrandPeople = function(name, value, brandID) {

    if (!FormControl.typeCounter[name] && !value) {
        FormControl.setTypeCounter(name, 2);
    } else {
        if (!FormControl.typeCounter[name] && value) {
            FormControl.setTypeCounter(name, value+1);
        } else {
            FormControl.typeCounter[name]++;
        }
    }

    var htmlSelect = ''
    $.get(baseUrl+"map/people/export/?type=htmlselect&brand="+brandID+"&select_name=who_f_person_id&counter="+FormControl.typeCounter[name], function(data) {
        $('#who_request_workers').html(data);
    });
}

FormControl.getBrandOwnerPeople = function(name, value, brandOwnerID) {

    if (!FormControl.typeCounter[name] && !value) {
        FormControl.setTypeCounter(name, 2);
    } else {
        if (!FormControl.typeCounter[name] && value) {
            FormControl.setTypeCounter(name, value+1);
        } else {
            FormControl.typeCounter[name]++;
        }
    }

    var htmlSelect = ''
    $.get(baseUrl+"map/people/export/?type=htmlselect&brand_owner="+brandOwnerID+"&select_name=who_f_person_id&counter="+FormControl.typeCounter[name], function(data) {
        $('#who_request_workers').html(data);
    });
}


FormControl.addCampaignSelector = function(counter) {

    if (!counter || typeof(counter) == 'undefined') counter = 0;

    if ( 0 < counter) {
        FormControl.campaignSelector += counter;
    } else {
        FormControl.campaignSelector += 1;
    }


    var ul = document.getElementById('campaign_container');
    var li = document.createElement('li');
    var html = '<select id=attachDateYear'+FormControl.campaignSelector+'>'+$('#attachDateYear').html()+'</select>';
    html += '<select id=attachDateMonth'+FormControl.campaignSelector+'>'+$('#attachDateMonth').html()+'</select>';
    html += '<select name="project_id'+FormControl.campaignSelector+'" id=project_id'+FormControl.campaignSelector+' onchange="FormControl.getCampaigns('+FormControl.campaignSelector+');">'+$('#project_id').html()+'</select>';
    html += '<span id="block_campaigns'+FormControl.campaignSelector+'"></span>';
    li.innerHTML = html;
    ul.appendChild(li);
}


FormControl.getCampaigns = function(counter) {
    FormControl.tmp = '';
    if (!counter || typeof(counter) == 'undefined') counter = 0;

    if (counter == 0) {
        var domProjectSelect = document.getElementById('project_id');
        var domMonthSelect = document.getElementById('attachDateMonth');
        var domYearSelect = document.getElementById('attachDateYear');
    }

    if (0 < counter) {
        var domProjectSelect = document.getElementById('project_id'+counter);
        var domMonthSelect = document.getElementById('attachDateMonth'+counter);
        var domYearSelect = document.getElementById('attachDateYear'+counter);
    }

    var qryString = '?submit=submit&json=1';

    if (domProjectSelect) {
        qryString+="&f_project_id="+domProjectSelect.value;
    }

    if (domYearSelect) {
        qryString+="&Date_Year="+domYearSelect.value;
    }

    if (domMonthSelect) {
        qryString+="&Date_Month="+domMonthSelect.value;
    }

    var callBackError = function(data) {
        return;
    }

    var callBack = function(data) {

        if (counter == 0) {
            $("#block_campaigns").html('');
            if (data.success == 1) {
                FormControl.tmp = '<select name="campaign_id[]" size="5" multiple="multiple">';
                for ( var i in data.data ) {
                    FormControl.tmp += '<option value="'+data.data[i]['id']+'">'+data.data[i]['brand']+' - '+data.data[i]['summ']+msg_currency_grn+'</option>';
                }
                FormControl.tmp += '</select>';

                $("#block_campaigns").html(FormControl.tmp);
            }
        }

        if (0 < counter) {
            $("#block_campaigns"+counter).html('');
            if (data.success == 1) {
                FormControl.tmp = '<select name="campaign_id[]" size="5" multiple="multiple">';
                for ( var i in data.data ) {
                    FormControl.tmp += '<option value="'+data.data[i]['id']+'">'+data.data[i]['brand']+' - '+data.data[i]['summ']+msg_currency_grn+'</option>';
                }
                FormControl.tmp += '</select>';

                $("#block_campaigns"+counter).html(FormControl.tmp);
            }
        }

        return;
    }

    $.ajax({
        type: "GET",
        url: baseUrl+"admin/campaign/"+qryString,
        data: {},
        dataType: "json",
        success: callBack,
        error: callBackError
    });


}

FormControl.checkCampaignForm = function() {

    var error = 0;

    if ($('#attach_year').val() == ''|| $('#attach_year').val() == 0) {
        error = 1;
    }

    if ($('#attach_month').val() == '' || $('#attach_month').val() == 0) {
        error = 1;
    }

    if ($('#f_user_id').val() == '' || $('#f_user_id').val() == 0) {
        error = 1;
    }

    if ($('#project_id').val() == 0 && $('#packet_id').val() == 0) {
        error = 1;
    }

    if (error == 1) {
        alert(msg_campaign);
        return false;
    }

    if (!error) $("#submit").attr('disabled','disabled');

    return true;
}

FormControl.getFilterData = function(domSelect, selected) {

    var type = domSelect.value;
    var url = '';

    $("#type_selector").html('');
    if (type == '' ) return false;

    if (type == 'brand') {
        url = baseUrl+"map/brand/export/?type=json";
    }

    if (type == 'brand-owner') {
        url = baseUrl+"map/advertisers/export/?type=json";
    }

    if (type == 'people') {
        url = baseUrl+"map/people/export/?type=json";
    }

    if (type == 'agency') {
        url = baseUrl+"map/agency/export/?type=json";
    }

    var callBackError = function(data) {
        return;
    }

    var callBack = function(data) {
        var html = '<select name="object_id">';
        if(data.success) {
            for ( var i in data.data ) {
                if (selected != 'undefined' && data.data[i]['id']==selected) {
                    html += '<option value="'+data.data[i]['id']+'" selected="selected">'+data.data[i]['name']+'</option>';
                } else {
                    html += '<option value="'+data.data[i]['id']+'">'+data.data[i]['name']+'</option>';
                }
            }
        } else {
            $("#adress").val('');
        }
        html += '</select>';
        $("#type_selector").html(html);
        return;
    }

    $.ajax({
        type: "GET",
        url: url,
        data: {},
        async: false,
        dataType: "json",
        success: callBack,
        error: callBackError
    });
}


FormControl.getWeeksData = function() {

    if (0 < document.getElementById('filter_month').value && 0 < document.getElementById('filter_year').value) {
        var qryString  = "?year="+document.getElementById('filter_year').value+"&month="+document.getElementById('filter_month').value;
    } else {
        return false;
    }

    var callBackError = function(data) {
        return;
    }

    var callBack = function(data) {
        var html = '<select name="weeks" id="weeks">';
        html += '<option value="">'+msg_all_weeks+'</option>';
        if(data.success) {
            for ( var i in data.data ) {
                html += '<option value="'+data.data[i]+'">'+data.data[i]+'</option>';
            }
        } else {
            $("#weeks-container").html('');
        }
        html += '</select>';
        $("#weeks-container").html(html);
        return;
    }

    $.ajax({
        type: "GET",
        url: baseUrl+"admin/campaign/weeks/"+qryString,
        data: {},
        async: false,
        dataType: "json",
        success: callBack,
        error: callBackError
    });
}


FormControl.getProjectPlatforms = function(project_id) {

    if (0 < project_id) {
        $.getJSON(baseUrl+"admin/projects/platform/"+project_id,
        function(data) {
            var html = '<select name="platform" id="platform">';
            html = html + '<option value=""> '+msg_choose+' </option>';
            $.each(data, function(i,item) {
                html = html + '<option value="'+item.title+'">'+item.title+'</option>';
            });
            html = html + "</select>";
            $("#project_platforms").html(html);
        });
    }
}


FormControl.addCPM = function() {

    var tr, td;

    var tableRef = document.getElementById('cpm_table');
    var tbody = document.getElementById('cpm_table_body');

    tr = tbody.insertRow(tbody.rows.length);
    var i = tbody.rows.length - 1;
    td = tr.insertCell(tr.cells.length);
    td.style.width = '20%';
    td.innerHTML = '<label for="place_title'+i+'">Название</label>';

    td = tr.insertCell(tr.cells.length);
    td.style.width = '80%';
    td.innerHTML = '<input type="text" value="" name="place_title[]" id="place_title'+i+'" class="width_auto2" size="10" />';

    tr = tbody.insertRow(tbody.rows.length);
    var i = tbody.rows.length - 1;
    td = tr.insertCell(tr.cells.length);
    td.style.width = '20%';
    td.innerHTML = '<label for="scroll'+i+'">Очередность</label>';

    td = tr.insertCell(tr.cells.length);
    td.style.width = '80%';
    td.innerHTML = '<input type="text" value="" name="scroll[]" id="scroll'+i+'" class="width_auto2" size="10" />';

    tr = tbody.insertRow(tbody.rows.length);
    var i = tbody.rows.length - 1;
    td = tr.insertCell(tr.cells.length);
    td.style.width = '20%';
    td.innerHTML = '<label for="cpm'+i+'">CPM (грн)</label>';

    td = tr.insertCell(tr.cells.length);
    td.style.width = '80%';
    td.innerHTML = '<input type="text" value="" name="cpm[]" id="cpm'+i+'" class="width_auto2" size="10" />';

    //переключалка редактора і текстове поле
    tr = tbody.insertRow(tbody.rows.length);
    var i = tbody.rows.length - 1;
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = '';
    var txtID = i+1;
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = '<ul class="plan_rich_text"><li id="tab-html" class="on"><a href="javascript:void(0);" onclick="return ToggleEditors.usePlainText(\'place_dscr'+txtID+'\');"">Обычный текст</a></li><li id="tab-rich-text"><a href="javascript:void(0);" onclick="return ToggleEditors.useRichText(\'place_dscr'+txtID+'\');">Визуальный редактор</a></li></ul>';

    tr = tbody.insertRow(tbody.rows.length);
    tr.className = 'double_bottom_border';
    var i = tbody.rows.length - 1;
    td = tr.insertCell(tr.cells.length);
    td.style.width = '20%';
    td.innerHTML = '<label for="place_dscr'+i+'">Описание</label>';

    td = tr.insertCell(tr.cells.length);
    td.style.width = '80%';
    td.innerHTML = '<textarea name="place_dscr[]" id="place_dscr'+i+'" style="height:100px;"></textarea>';
    ToggleEditors.init('place_dscr'+i, '600px', '100px', 1);

    return false;
}

FormControl.toggleTable = function(id) {
    $("#"+id).toggle();
}

FormControl.addMaterial = function() {

    var tr, td;

    var tableRef = document.getElementById('advm_table');
    var tbody = document.getElementById('advm_body');

    tr = tbody.insertRow(tbody.rows.length);
    var i = tbody.rows.length - 1;
    td = tr.insertCell(tr.cells.length);
    td.style.width = '20%';
    td.innerHTML = '<label for="adv_title_'+i+'">Название</label>';

    td = tr.insertCell(tr.cells.length);
    td.style.width = '80%';
    td.innerHTML = '<input type="text" value="" name="adv_title[]" id="adv_title_'+i+'" class="width_auto2" size="40" />';

    tr = tbody.insertRow(tbody.rows.length);
    var i = tbody.rows.length - 1;
    td = tr.insertCell(tr.cells.length);
    td.style.width = '20%';
    td.innerHTML = '<label for="adv_cpm_'+i+'">Стоимость (грн)</label>';

    td = tr.insertCell(tr.cells.length);
    td.style.width = '80%';
    td.innerHTML = '<input type="text" value="" name="adv_cpm[]" id="adv_cpm_'+i+'" class="width_auto2" size="10" />';

    //переключалка редактора і текстове поле
    tr = tbody.insertRow(tbody.rows.length);
    var i = tbody.rows.length - 1;
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = '';
    var txtID = i+1;
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = '<ul class="plan_rich_text"><li id="tab-html" class="on"><a href="javascript:void(0);" onclick="return ToggleEditors.usePlainText(\'adv_dscr_'+txtID+'\');"">Обычный текст</a></li><li id="tab-rich-text"><a href="javascript:void(0);" onclick="return ToggleEditors.useRichText(\'adv_dscr_'+txtID+'\');">Визуальный редактор</a></li></ul>';

    tr = tbody.insertRow(tbody.rows.length);
    var i = tbody.rows.length - 1;
    td = tr.insertCell(tr.cells.length);
    td.style.width = '20%';
    td.innerHTML = '<label for="adv_dscr_'+i+'">Описание</label>';

    td = tr.insertCell(tr.cells.length);
    td.style.width = '80%';
    td.innerHTML = '<textarea name="adv_dscr[]" id="adv_dscr_'+i+'" style="height:100px;"></textarea>';
    ToggleEditors.init('adv_dscr_'+i, '600px', '200px', 1);

    return false;
}

FormControl.addInput = function(name, type, className) {

    if(!type) type = 'text';
    if(!className) className = '';

    if (!FormControl.typeCounter[name]) FormControl.typeCounter[name] = 1;
    else {
        FormControl.typeCounter[name]++;
    }

    //Create an input type dynamically.
    var elementBR = document.createElement("br");
    var element = document.createElement("input");

    //Assign different attributes to the element.
    elementBR.setAttribute('clear', 'all');
    element.setAttribute('type', type);
    element.setAttribute('class', className);
    element.setAttribute('value', '');
    element.setAttribute("name", name+'[]');

    var after = document.getElementById('addfield-'+name);

    //Append the element in page.
    after.appendChild(element);
    after.appendChild(elementBR);
}


FormControl.addFile2Action = function(name, type, className) {

    if(!type) type = 'text';
    if(!className) className = '';

    if (!FormControl.typeCounter[name]) FormControl.typeCounter[name] = 1;
    else {
        FormControl.typeCounter[name]++;
    }

    //Create an input type dynamically.
    var elementBR = document.createElement("br");
    var element = document.createElement("input");
    var element2 = document.createElement("input");

    //Assign different attributes to the element.
    element2.setAttribute('type', 'text');
    element2.setAttribute('class', 'padding_margin_zero');
    element2.setAttribute('value', '');
    element2.setAttribute('name', 'file_description[]');
    element2.setAttribute('size', '40');

    elementBR.setAttribute('clear', 'all');
    element.setAttribute('type', type);
    element.setAttribute('class', className);
    element.setAttribute('value', '');
    element.setAttribute('name', name+'[]');

    var after = document.getElementById('addfield-'+name);

    //Append the element in page.
    after.appendChild(element2);
    after.appendChild(element);
    after.appendChild(elementBR);
}


FormControl.addCategory = function(title, id) {

    var value = window.prompt(title);

    if (value == null) return false;

    var callBackError = function(data) {
        alert('Ajax error');
        return;
    }

    var callBack = function( data ) {
        if(data.success) {
            var html = '<option value="'+data.message+'" selected="selected">'+value+'</option>';
            $("#"+id+' option:selected').attr('selected','');
            $("#"+id+' optgroup').append(html);
        } else {
            alert(data.message);
        }

        return;
    }

    $.ajax({
        type: "POST",
        url: baseUrl+'admin/project-category/insert/',
        data: {name:value, from_ajax:1},
        dataType: "json",
        success: callBack,
        error: callBackError
    });

    return false;
}

FormControl.addBrand = function(id) {
    FormControl.selectId = id;
    var d = new Date();

    window.open(baseUrl+'map/brand/add/?from_window=1','brand'+d.getTime(),'width=1000,height=700,resizable=yes,status=yes,toolbar=no,location=no,menubar=no,scrollbars=yes');
    return false;

}

FormControl.addAgency = function(id) {
    FormControl.selectId = id;
    var d = new Date();

    window.open(baseUrl+'map/agency/add/?from_window=1','agency'+d.getTime(),'width=1000,height=700,resizable=yes,status=yes,toolbar=no,location=no,menubar=no,scrollbars=yes');
    return false;

}


FormControl.addAdvertiser = function(id) {
    FormControl.selectId = id;
    var d = new Date();

    window.open(baseUrl+'map/advertisers/add/?from_window=1','advertisers'+d.getTime(),'width=1000,height=700,resizable=yes,status=yes,toolbar=no,location=no,menubar=no,scrollbars=yes');
    return false;

}


FormControl.addProject = function(id) {
    FormControl.selectId = id;
    var d = new Date();

    window.open(baseUrl+'admin/projects/add/?from_window=1','projects'+d.getTime(),'width=1000,height=700,resizable=yes,status=yes,toolbar=no,location=no,menubar=no,scrollbars=yes');
    return false;
}


FormControl.addPacket = function(id) {
    FormControl.selectId = id;
    var d = new Date();

    window.open(baseUrl+'admin/pack/add/?from_window=1','pack'+d.getTime(),'width=1000,height=700,resizable=yes,status=yes,toolbar=no,location=no,menubar=no,scrollbars=yes');
    return false;
}


FormControl.addPeople = function(id) {
    FormControl.selectId = id;
    var d = new Date();

    window.open(baseUrl+'map/people/add/?from_window=1','people'+d.getTime(),'width=1000,height=700,resizable=yes,status=yes,toolbar=no,location=no,menubar=no,scrollbars=yes');
    return false;

}


FormControl.addSiteRubric = function(id) {
    FormControl.selectId = id;
    var d = new Date();
    var projectID = document.getElementById('projects').value;
    window.open(baseUrl+'admin/projects/rubric/add/?from_window=1&project_id='+projectID,'rubric'+d.getTime(),'width=1000,height=700,resizable=yes,status=yes,toolbar=no,location=no,menubar=no,scrollbars=yes');
    return false;

}


FormControl.addOption = function(name, value) {

    var id = FormControl.selectId;
    var html = '<option value="'+value+'" selected="selected">'+name+'</option>';
    $("#"+id+' option:selected').attr('selected','');
    $("#"+id+' ').append(html);

    return false;
}

FormControl.filterIdArray = new Array();

FormControl.toggleActionListCheckbox = function() {
    $("#action-list-form input:checkbox").each(function() {
        if (this.checked == true) this.checked = false;
        else this.checked = true;
    });
}

FormControl.toggleActionTypeFilter = function(value) {

    var id = 'type_filter';
    if (typeof(FormControl.filterIdArray[id]) == 'undefined') FormControl.filterIdArray[id] = value;

    if (FormControl.filterIdArray[id] == 'show') {
        $("#"+id).show();
        $("#id_object_type").attr('disabled','');
//
//        $("#date").attr('disabled','disabled');
//        $("#profile_id").attr('disabled','disabled');

        FormControl.filterIdArray[id] = 'hide';
        $("#direction_arrow").html('&darr;');
        return;
    }

    if(FormControl.filterIdArray[id] == 'hide') {
        $("#"+id).hide();
        $("#id_object_type").attr('disabled','disabled');
//
//        $("#date").attr('disabled','');
//        $("#profile_id").attr('disabled','');

        FormControl.filterIdArray[id] = 'show';
        $("#direction_arrow").html('&uarr;');
        return;
    }
}

FormControl.checkSpecialForm = function(msg, actionType) {
    var status = true;

    if ( $("#name").val() == '') status = false;
    if ( $("#lead").val() == '') status = false;
    if ( document.getElementById('projects').value == 0) status = false;
    if (typeof(FCKeditorAPI) != 'undefined') {
        var instance = FCKeditorAPI.GetInstance('description');
        var html = instance.GetXHTML(false);
        if (html == '' || html == '<p></p>') status = false;
    } else {
        if ($("#description").val() == '') status = false;
    }

    if (actionType == 'add') {
        if ( $("#photo").val() == '') status = false;
    }

    if(status == false) alert(msg);

    return status;
}

ToggleEditors = {};

ToggleEditors.eWidth = '100%';
ToggleEditors.eHeight = '400px';
ToggleEditors.switched_rte_on = new Array();
ToggleEditors.textArea = 'content';
ToggleEditors.oEditor = new Array();

ToggleEditors.init = function(textArea, w,h, defaultRte) {
    ToggleEditors.textArea = textArea;
    if(w) ToggleEditors.eWidth = w;
    if(h) ToggleEditors.eHeight = h;

    var rte = new FCKeditor();
    var t = rte._IsCompatibleBrowser();

    if (!t || !defaultRte) {
        ToggleEditors.usePlainText(textArea);
    } else {
        ToggleEditors.useRichText(textArea);
    }
}

ToggleEditors.useRichText = function(textArea) {
    statPrefix = sBasePath
    if ( ToggleEditors.switched_rte_on[textArea] == 1 ) return;

    var rte = new FCKeditor();
    var t = rte._IsCompatibleBrowser();
    if (!t) return;

    var entry_html = $("#"+textArea).val();

    var editor_frame = document.getElementById(textArea + '___Frame');

    // Check for RTE already existing.  IE will show multiple iframes otherwise.
    if (!editor_frame) {

        $("#"+textArea).val(entry_html);
        ToggleEditors.oEditor[textArea] = new FCKeditor(textArea);
        ToggleEditors.oEditor[textArea].BasePath = statPrefix;
        ToggleEditors.oEditor[textArea].Width = ToggleEditors.eWidth;
        ToggleEditors.oEditor[textArea].Height = ToggleEditors.eHeight;
        ToggleEditors.oEditor[textArea].ToolbarSet = "Basic";
        ToggleEditors.oEditor[textArea].ReplaceTextarea();

    } else {
        if (typeof(FCKeditorAPI) == 'undefined') return;
        ToggleEditors.oEditor[textArea] = FCKeditorAPI.GetInstance(textArea);
        editor_frame.style.display = "block";
        $("#"+textArea).hide();
        ToggleEditors.oEditor[textArea].SetData(entry_html);

        ToggleEditors.oEditor[textArea].Focus();
    }

    if ($("#tab-html")) $("#tab-html").removeClass();
    if ($("#tab-rich-text")) $("#tab-rich-text").addClass('on');
    if ($("#tab-img")) $("#tab-img").hide();

    ToggleEditors.switched_rte_on[textArea] = 1;

    return false; // do not follow link
}

ToggleEditors.usePlainText = function(textArea) {
    if (ToggleEditors.switched_rte_on[textArea] == 0) return;

    if (typeof(FCKeditorAPI) == 'undefined') return;
    ToggleEditors.oEditor[textArea] = FCKeditorAPI.GetInstance(textArea);
    if (!ToggleEditors.oEditor[textArea]) return;
    var editor_frame = document.getElementById(textArea + '___Frame');

    var html = ToggleEditors.oEditor[textArea].GetXHTML(false);

    html = html.replace(/&nbsp;/g, ' ');

    $("#"+textArea).val(html);

    if ($("#tab-html")) $("#tab-html").addClass('on');
    if ($("#tab-rich-text")) $("#tab-rich-text").removeClass();
    if ($("#tab-img")) $("#tab-img").show();

    $('#'+textArea + '___Frame').hide();
    $("#"+textArea).show();
    $("#"+textArea).focus();

    ToggleEditors.switched_rte_on[textArea] = 0;

    return false;
}

/*
* Date prototype extensions. Doesn't depend on any
* other code. Doens't overwrite existing methods.
*
* Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear,
* isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear,
* setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods
*
* Copyright (c) 2006 JУЖrn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
*
* Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString -
* I've added my name to these methods so you know who to blame if they are broken!
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
*/

/**
* An Array of day names starting with Sunday.
*
* @example dayNames[0]
* @result 'Sunday'
*
* @name dayNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.dayNames = ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Субота'];

/**
* An Array of abbreviated day names starting with Sun.
*
* @example abbrDayNames[0]
* @result 'Sun'
*
* @name abbrDayNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.abbrDayNames = ['Вск', 'Пон', 'Втр', 'Срд', 'Чтв', 'Птн', 'Суб'];

/**
* An Array of month names starting with Janurary.
*
* @example monthNames[0]
* @result 'January'
*
* @name monthNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.monthNames = ['Январь', 'Февраль', 'Март', 'Апрель', 'Мая', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'];

/**
* An Array of abbreviated month names starting with Jan.
*
* @example abbrMonthNames[0]
* @result 'Jan'
*
* @name monthNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.abbrMonthNames = ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июл', 'Июн', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'];

/**
* The first day of the week for this locale.
*
* @name firstDayOfWeek
* @type Number
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.firstDayOfWeek = 1;

/**
* The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc).
*
* @name format
* @type String
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.format = 'yyyy-mm-dd';
//Date.format = 'mm/dd/yyyy';
//Date.format = 'yyyy-mm-dd';
//Date.format = 'dd mmm yy';

/**
* The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear
* only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes.
*
* @name format
* @type String
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.fullYearStart = '20';

(function() {

    /**
    * Adds a given method under the given name
    * to the Date prototype if it doesn't
    * currently exist.
    *
    * @private
    */
    function add(name, method) {
        if( !Date.prototype[name] ) {
            Date.prototype[name] = method;
        }
    };

    /**
    * Checks if the year is a leap year.
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.isLeapYear();
    * @result true
    *
    * @name isLeapYear
    * @type Boolean
    * @cat Plugins/Methods/Date
    */
    add("isLeapYear", function() {
        var y = this.getFullYear();
        return (y%4==0 && y%100!=0) || y%400==0;
    });

    /**
    * Checks if the day is a weekend day (Sat or Sun).
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.isWeekend();
    * @result false
    *
    * @name isWeekend
    * @type Boolean
    * @cat Plugins/Methods/Date
    */
    add("isWeekend", function() {
        return this.getDay()==0 || this.getDay()==6;
    });

    /**
    * Check if the day is a day of the week (Mon-Fri)
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.isWeekDay();
    * @result false
    *
    * @name isWeekDay
    * @type Boolean
    * @cat Plugins/Methods/Date
    */
    add("isWeekDay", function() {
        return !this.isWeekend();
    });

    /**
    * Gets the number of days in the month.
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.getDaysInMonth();
    * @result 31
    *
    * @name getDaysInMonth
    * @type Number
    * @cat Plugins/Methods/Date
    */
    add("getDaysInMonth", function() {
        return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];
    });

    /**
    * Gets the name of the day.
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.getDayName();
    * @result 'Saturday'
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.getDayName(true);
    * @result 'Sat'
    *
    * @param abbreviated Boolean When set to true the name will be abbreviated.
    * @name getDayName
    * @type String
    * @cat Plugins/Methods/Date
    */
    add("getDayName", function(abbreviated) {
        return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()];
    });

    /**
    * Gets the name of the month.
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.getMonthName();
    * @result 'Janurary'
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.getMonthName(true);
    * @result 'Jan'
    *
    * @param abbreviated Boolean When set to true the name will be abbreviated.
    * @name getDayName
    * @type String
    * @cat Plugins/Methods/Date
    */
    add("getMonthName", function(abbreviated) {
        return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()];
    });

    /**
    * Get the number of the day of the year.
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.getDayOfYear();
    * @result 11
    *
    * @name getDayOfYear
    * @type Number
    * @cat Plugins/Methods/Date
    */
    add("getDayOfYear", function() {
        var tmpdtm = new Date("1/1/" + this.getFullYear());
        return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000);
    });

    /**
    * Get the number of the week of the year.
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.getWeekOfYear();
    * @result 2
    *
    * @name getWeekOfYear
    * @type Number
    * @cat Plugins/Methods/Date
    */
    add("getWeekOfYear", function() {
        return Math.ceil(this.getDayOfYear() / 7);
    });

    /**
    * Set the day of the year.
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.setDayOfYear(1);
    * dtm.toString();
    * @result 'Tue Jan 01 2008 00:00:00'
    *
    * @name setDayOfYear
    * @type Date
    * @cat Plugins/Methods/Date
    */
    add("setDayOfYear", function(day) {
        this.setMonth(0);
        this.setDate(day);
        return this;
    });

    /**
    * Add a number of years to the date object.
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.addYears(1);
    * dtm.toString();
    * @result 'Mon Jan 12 2009 00:00:00'
    *
    * @name addYears
    * @type Date
    * @cat Plugins/Methods/Date
    */
    add("addYears", function(num) {
        this.setFullYear(this.getFullYear() + num);
        return this;
    });

    /**
    * Add a number of months to the date object.
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.addMonths(1);
    * dtm.toString();
    * @result 'Tue Feb 12 2008 00:00:00'
    *
    * @name addMonths
    * @type Date
    * @cat Plugins/Methods/Date
    */
    add("addMonths", function(num) {
        var tmpdtm = this.getDate();

        this.setMonth(this.getMonth() + num);

        if (tmpdtm > this.getDate())
        this.addDays(-this.getDate());

        return this;
    });

    /**
    * Add a number of days to the date object.
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.addDays(1);
    * dtm.toString();
    * @result 'Sun Jan 13 2008 00:00:00'
    *
    * @name addDays
    * @type Date
    * @cat Plugins/Methods/Date
    */
    add("addDays", function(num) {
        this.setDate(this.getDate() + num);
        return this;
    });

    /**
    * Add a number of hours to the date object.
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.addHours(24);
    * dtm.toString();
    * @result 'Sun Jan 13 2008 00:00:00'
    *
    * @name addHours
    * @type Date
    * @cat Plugins/Methods/Date
    */
    add("addHours", function(num) {
        this.setHours(this.getHours() + num);
        return this;
    });

    /**
    * Add a number of minutes to the date object.
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.addMinutes(60);
    * dtm.toString();
    * @result 'Sat Jan 12 2008 01:00:00'
    *
    * @name addMinutes
    * @type Date
    * @cat Plugins/Methods/Date
    */
    add("addMinutes", function(num) {
        this.setMinutes(this.getMinutes() + num);
        return this;
    });

    /**
    * Add a number of seconds to the date object.
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.addSeconds(60);
    * dtm.toString();
    * @result 'Sat Jan 12 2008 00:01:00'
    *
    * @name addSeconds
    * @type Date
    * @cat Plugins/Methods/Date
    */
    add("addSeconds", function(num) {
        this.setSeconds(this.getSeconds() + num);
        return this;
    });

    /**
    * Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant.
    *
    * @example var dtm = new Date();
    * dtm.zeroTime();
    * dtm.toString();
    * @result 'Sat Jan 12 2008 00:01:00'
    *
    * @name zeroTime
    * @type Date
    * @cat Plugins/Methods/Date
    * @author Kelvin Luck
    */
    add("zeroTime", function() {
        this.setMilliseconds(0);
        this.setSeconds(0);
        this.setMinutes(0);
        this.setHours(0);
        return this;
    });

    /**
    * Returns a string representation of the date object according to Date.format.
    * (Date.toString may be used in other places so I purposefully didn't overwrite it)
    *
    * @example var dtm = new Date("01/12/2008");
    * dtm.asString();
    * @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy'
    *
    * @name asString
    * @type Date
    * @cat Plugins/Methods/Date
    * @author Kelvin Luck
    */
    add("asString", function(format) {
        var r = format || Date.format;
        return r
        .split('yyyy').join(this.getFullYear())
        .split('yy').join((this.getFullYear() + '').substring(2))
        .split('mmmm').join(this.getMonthName(false))
        .split('mmm').join(this.getMonthName(true))
        .split('mm').join(_zeroPad(this.getMonth()+1))
        .split('dd').join(_zeroPad(this.getDate()));
    });

    /**
    * Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object
    * (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere)
    *
    * @example var dtm = Date.fromString("12/01/2008");
    * dtm.toString();
    * @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy'
    *
    * @name fromString
    * @type Date
    * @cat Plugins/Methods/Date
    * @author Kelvin Luck
    */
    Date.fromString = function(s)
    {
        var f = Date.format;
        var d = new Date('01/01/1977');

        var mLength = 0;

        var iM = f.indexOf('mmmm');
        if (iM > -1) {
            for (var i=0; i<Date.monthNames.length; i++) {
                var mStr = s.substr(iM, Date.monthNames[i].length);
                if (Date.monthNames[i] == mStr) {
                    mLength = Date.monthNames[i].length - 4;
                    break;
                }
            }
            d.setMonth(i);
        } else {
            iM = f.indexOf('mmm');
            if (iM > -1) {
                var mStr = s.substr(iM, 3);
                for (var i=0; i<Date.abbrMonthNames.length; i++) {
                    if (Date.abbrMonthNames[i] == mStr) break;
                }
                d.setMonth(i);
            } else {
                d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1);
            }
        }

        var iY = f.indexOf('yyyy');

        if (iY > -1) {
            if (iM < iY)
            {
                iY += mLength;
            }
            d.setFullYear(Number(s.substr(iY, 4)));
        } else {
            if (iM < iY)
            {
                iY += mLength;
            }
            // TODO - this doesn't work very well - are there any rules for what is meant by a two digit year?
            d.setFullYear(Number(Date.fullYearStart + s.substr(f.indexOf('yy'), 2)));
        }
        var iD = f.indexOf('dd');
        if (iM < iD)
        {
            iD += mLength;
        }
        d.setDate(Number(s.substr(iD, 2)));
        if (isNaN(d.getTime())) {
            return false;
        }
        return d;
    };

    // utility method
    var _zeroPad = function(num) {
        var s = '0'+num;
        return s.substring(s.length-2)
        //return ('0'+num).substring(-2); // doesn't work on IE :(
    };

})();


/*
jQuery TextAreaResizer plugin
Created on 17th January 2008 by Ryan O'Dell
Version 1.0.4

Converted from Drupal -> textarea.js
Found source: http://plugins.jquery.com/misc/textarea.js
$Id: textarea.js,v 1.11.2.1 2007/04/18 02:41:19 drumm Exp $
*/
(function($){var textarea,staticOffset;var iLastMousePos=0;var iMin=32;var grip;$.fn.TextAreaResizer=function(){return this.each(function(){textarea=$(this).addClass('processed'),staticOffset=null;$(this).wrap('<div class="resizable-textarea"><span></span></div>').parent().append($('<div class="grippie"></div>').bind("mousedown",{el:this},startDrag));var grippie=$('div.grippie',$(this).parent())[0];grippie.style.marginRight=(grippie.offsetWidth-$(this)[0].offsetWidth)+'px'})};function startDrag(e){textarea=$(e.data.el);textarea.blur();iLastMousePos=mousePosition(e).y;staticOffset=textarea.height()-iLastMousePos;textarea.css('opacity',0.25);$(document).mousemove(performDrag).mouseup(endDrag);return false}function performDrag(e){var iThisMousePos=mousePosition(e).y;var iMousePos=staticOffset+iThisMousePos;if(iLastMousePos>=(iThisMousePos)){iMousePos-=5}iLastMousePos=iThisMousePos;iMousePos=Math.max(iMin,iMousePos);textarea.height(iMousePos+'px');if(iMousePos<iMin){endDrag(e)}return false}function endDrag(e){$(document).unbind('mousemove',performDrag).unbind('mouseup',endDrag);textarea.css('opacity',1);textarea.focus();textarea=null;staticOffset=null;iLastMousePos=0}function mousePosition(e){return{x:e.clientX+document.documentElement.scrollLeft,y:e.clientY+document.documentElement.scrollTop}}})(jQuery);


/************************************************************************************************************
*	DHTML modal dialog box
*
*	Created:						August, 26th, 2006
*	@class Purpose of class:		Display a modal dialog box on the screen.
*
*	Css files used by this script:	modal-message.css
*
*	Demos of this class:			demo-modal-message-1.html
*
* 	Update log:
*
************************************************************************************************************/


/**
* @constructor
*/

DHTML_modalMessage = function()
{
    var url;								// url of modal message
    var htmlOfModalMessage;					// html of modal message

    var divs_transparentDiv;				// Transparent div covering page content
    var divs_content;						// Modal message div.
    var iframe;								// Iframe used in ie
    var layoutCss;							// Name of css file;
    var width;								// Width of message box
    var height;								// Height of message box

    var existingBodyOverFlowStyle;			// Existing body overflow css
    var dynContentObj;						// Reference to dynamic content object
    var cssClassOfMessageBox;				// Alternative css class of message box - in case you want a different appearance on one of them
    var shadowDivVisible;					// Shadow div visible ?
    var shadowOffset; 						// X and Y offset of shadow(pixels from content box)
    var MSIE;

    this.url = '';							// Default url is blank
    this.htmlOfModalMessage = '';			// Default message is blank
    this.layoutCss = 'modal-message.css';	// Default CSS file
    this.height = 200;						// Default height of modal message
    this.width = 400;						// Default width of modal message
    this.cssClassOfMessageBox = false;		// Default alternative css class for the message box
    this.shadowDivVisible = true;			// Shadow div is visible by default
    this.shadowOffset = 5;					// Default shadow offset.
    this.MSIE = false;
    if(navigator.userAgent.indexOf('MSIE')>=0) this.MSIE = true;


}

DHTML_modalMessage.prototype = {
    // {{{ setSource(urlOfSource)
    /**
    *	Set source of the modal dialog box
    *
    *
    * @public
    */
    setSource : function(urlOfSource)
    {
        this.url = urlOfSource;

    }
    // }}}
    ,
    // {{{ setHtmlContent(newHtmlContent)
    /**
    *	Setting static HTML content for the modal dialog box.
    *
    *	@param String newHtmlContent = Static HTML content of box
    *
    * @public
    */
    setHtmlContent : function(newHtmlContent)
    {
        this.htmlOfModalMessage = newHtmlContent;

    }
    // }}}
    ,
    // {{{ setSize(width,height)
    /**
    *	Set the size of the modal dialog box
    *
    *	@param int width = width of box
    *	@param int height = height of box
    *
    * @public
    */
    setSize : function(width,height)
    {
        if(width)this.width = width;
        if(height)this.height = height;
    }
    // }}}
    ,
    // {{{ setCssClassMessageBox(newCssClass)
    /**
    *	Assign the message box to a new css class.(in case you wants a different appearance on one of them)
    *
    *	@param String newCssClass = Name of new css class (Pass false if you want to change back to default)
    *
    * @public
    */
    setCssClassMessageBox : function(newCssClass)
    {
        this.cssClassOfMessageBox = newCssClass;
        if(this.divs_content){
            if(this.cssClassOfMessageBox)
            this.divs_content.className=this.cssClassOfMessageBox;
            else
            this.divs_content.className='modalDialog_contentDiv';
        }

    }
    // }}}
    ,
    // {{{ setShadowOffset(newShadowOffset)
    /**
    *	Specify the size of shadow
    *
    *	@param Int newShadowOffset = Offset of shadow div(in pixels from message box - x and y)
    *
    * @public
    */
    setShadowOffset : function(newShadowOffset)
    {
        this.shadowOffset = newShadowOffset

    }
    // }}}
    ,
    // {{{ display()
    /**
    *	Display the modal dialog box
    *
    *
    * @public
    */
    display : function()
    {
        if(!this.divs_transparentDiv){
            this.__createDivs();
        }

        // Redisplaying divs
        this.divs_transparentDiv.style.display='block';
        this.divs_content.style.display='block';
        this.divs_shadow.style.display='block';
        if(this.MSIE)this.iframe.style.display='block';
        this.__resizeDivs();

        /* Call the __resizeDivs method twice in case the css file has changed. The first execution of this method may not catch these changes */
        window.refToThisModalBoxObj = this;
        setTimeout('window.refToThisModalBoxObj.__resizeDivs()',150);

        this.__insertContent();	// Calling method which inserts content into the message div.
    }
    // }}}
    ,
    // {{{ ()
    /**
    *	Display the modal dialog box
    *
    *
    * @public
    */
    setShadowDivVisible : function(visible)
    {
        this.shadowDivVisible = visible;
    }
    // }}}
    ,
    // {{{ close()
    /**
    *	Close the modal dialog box
    *
    *
    * @public
    */
    close : function()
    {
        //document.documentElement.style.overflow = '';	// Setting the CSS overflow attribute of the <html> tag back to default.

        /* Hiding divs */
        this.divs_transparentDiv.style.display='none';
        this.divs_content.style.display='none';
        this.divs_shadow.style.display='none';
        if(this.MSIE)this.iframe.style.display='none';

    }
    // }}}
    ,
    // {{{ __addEvent()
    /**
    *	Add event
    *
    *
    * @private
    */
    addEvent : function(whichObject,eventType,functionName,suffix)
    {
        if(!suffix)suffix = '';
        if(whichObject.attachEvent){
            whichObject['e'+eventType+functionName+suffix] = functionName;
            whichObject[eventType+functionName+suffix] = function(){whichObject['e'+eventType+functionName+suffix]( window.event );}
            whichObject.attachEvent( 'on'+eventType, whichObject[eventType+functionName+suffix] );
        } else
        whichObject.addEventListener(eventType,functionName,false);
    }
    // }}}
    ,
    // {{{ __createDivs()
    /**
    *	Create the divs for the modal dialog box
    *
    *
    * @private
    */
    __createDivs : function()
    {
        // Creating transparent div
        this.divs_transparentDiv = document.createElement('DIV');
        this.divs_transparentDiv.className='modalDialog_transparentDivs';
        this.divs_transparentDiv.style.left = '0px';
        this.divs_transparentDiv.style.top = '0px';

        document.body.appendChild(this.divs_transparentDiv);
        // Creating content div
        this.divs_content = document.createElement('DIV');
        this.divs_content.className = 'modalDialog_contentDiv';
        this.divs_content.id = 'DHTMLSuite_modalBox_contentDiv';
        this.divs_content.style.zIndex = 100000;

        if(this.MSIE){
            this.iframe = document.createElement('<IFRAME src="about:blank" frameborder=0>');
            this.iframe.style.zIndex = 90000;
            this.iframe.style.position = 'absolute';
            document.body.appendChild(this.iframe);
        }

        document.body.appendChild(this.divs_content);
        // Creating shadow div
        this.divs_shadow = document.createElement('DIV');
        this.divs_shadow.className = 'modalDialog_contentDiv_shadow';
        this.divs_shadow.style.zIndex = 95000;
        document.body.appendChild(this.divs_shadow);
        window.refToModMessage = this;
        this.addEvent(window,'scroll',function(e){ window.refToModMessage.__repositionTransparentDiv() });
        this.addEvent(window,'resize',function(e){ window.refToModMessage.__repositionTransparentDiv() });


    }
    // }}}
    ,
    // {{{ __getBrowserSize()
    /**
    *	Get browser size
    *
    *
    * @private
    */
    __getBrowserSize : function()
    {
        var bodyWidth = document.documentElement.clientWidth;
        var bodyHeight = document.documentElement.clientHeight;

        var bodyWidth, bodyHeight;
        if (self.innerHeight){ // all except Explorer

            bodyWidth = self.innerWidth;
            bodyHeight = self.innerHeight;
        }  else if (document.documentElement && document.documentElement.clientHeight) {
            // Explorer 6 Strict Mode
            bodyWidth = document.documentElement.clientWidth;
            bodyHeight = document.documentElement.clientHeight;
        } else if (document.body) {// other Explorers
            bodyWidth = document.body.clientWidth;
            bodyHeight = document.body.clientHeight;
        }
        return [bodyWidth,bodyHeight];

    }
    // }}}
    ,
    // {{{ __resizeDivs()
    /**
    *	Resize the message divs
    *
    *
    * @private
    */
    __resizeDivs : function()
    {

        var topOffset = Math.max(document.body.scrollTop,document.documentElement.scrollTop);

        if(this.cssClassOfMessageBox)
        this.divs_content.className=this.cssClassOfMessageBox;
        else
        this.divs_content.className='modalDialog_contentDiv';

        if(!this.divs_transparentDiv)return;

        // Preserve scroll position
        var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
        var sl = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);

        window.scrollTo(sl,st);
        setTimeout('window.scrollTo(' + sl + ',' + st + ');',10);

        this.__repositionTransparentDiv();


        var brSize = this.__getBrowserSize();
        var bodyWidth = brSize[0];
        var bodyHeight = brSize[1];

        // Setting width and height of content div
        this.divs_content.style.width = this.width + 'px';
        this.divs_content.style.height= this.height + 'px';

        // Creating temporary width variables since the actual width of the content div could be larger than this.width and this.height(i.e. padding and border)
        var tmpWidth = this.divs_content.offsetWidth;
        var tmpHeight = this.divs_content.offsetHeight;


        // Setting width and height of left transparent div






        this.divs_content.style.left = Math.ceil((bodyWidth - tmpWidth) / 2) + 'px';;
        this.divs_content.style.top = (Math.ceil((bodyHeight - tmpHeight) / 2) +  topOffset) + 'px';

        if(this.MSIE){
            this.iframe.style.left = this.divs_content.style.left;
            this.iframe.style.top = this.divs_content.style.top;
            this.iframe.style.width = this.divs_content.style.width;
            this.iframe.style.height = this.divs_content.style.height;
        }

        this.divs_shadow.style.left = (this.divs_content.style.left.replace('px','')/1 + this.shadowOffset) + 'px';
        this.divs_shadow.style.top = (this.divs_content.style.top.replace('px','')/1 + this.shadowOffset) + 'px';
        this.divs_shadow.style.height = tmpHeight + 'px';
        this.divs_shadow.style.width = tmpWidth + 'px';



        if(!this.shadowDivVisible)this.divs_shadow.style.display='none';	// Hiding shadow if it has been disabled


    }
    // }}}
    ,
    // {{{ __insertContent()
    /**
    *	Insert content into the content div
    *
    *
    * @private
    */
    __repositionTransparentDiv : function()
    {
        this.divs_transparentDiv.style.top = Math.max(document.body.scrollTop,document.documentElement.scrollTop) + 'px';
        this.divs_transparentDiv.style.left = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft) + 'px';
        var brSize = this.__getBrowserSize();
        var bodyWidth = brSize[0];
        var bodyHeight = brSize[1];
        this.divs_transparentDiv.style.width = bodyWidth + 'px';
        this.divs_transparentDiv.style.height = bodyHeight + 'px';

    }
    // }}}
    ,
    // {{{ __insertContent()
    /**
    *	Insert content into the content div
    *
    *
    * @private
    */
    __insertContent : function()
    {
        if(this.url){	// url specified - load content dynamically
            ajax_loadContent('DHTMLSuite_modalBox_contentDiv',this.url);
        }else{	// no url set, put static content inside the message box
            this.divs_content.innerHTML = '';
            this.divs_content.innerHTML = this.htmlOfModalMessage;
        }
    }
}


function showModal(content, w, h) {

    var img = "<img src='"+content+"' border='0' class='close' onclick='messageObj.close();' alt='' />"

    messageObj = new DHTML_modalMessage();
    messageObj.setHtmlContent(img);
    messageObj.setSize(w,h);
    messageObj.display();

    return false;
}


function subscribe() {
    //onsubmit="return submitSubscribe();"
    var html = '<div align="right"><a href="#" onclick="messageObj.close();"><img src="/images/theme/close-icon.jpg" border=0 alt="Закрыть" /></a></div><div id="subscribe"><form action="/subscribe/" method="post" onsubmit="return submitSubscribe();"><h1>Подписаться на рассылку новостей</h1><p>Вы можете получать новости с нашего ресурса на свой имейл.</p><p>В будущем вы легко сможете отписаться от нашей рассылки в любой момент.</p><label>Ваш email:<input type="text" name="email" id="subscribe_email" size="25" value="" class="sub_email" /></label><input type="submit" name="submit"  value="Подписаться" class="js_submit_sub" /></form></div>';

    messageObj = new DHTML_modalMessage();
    messageObj.setHtmlContent(html);
    messageObj.setSize(500,200);
    messageObj.display();

    return false;
}


function submitSubscribe() {

    var email = $("#subscribe_email").val();

    var callBackError = function(data) {
        alert("ajax error");
        messageObj.close();
        return;
    }

    var callBack = function(data) {
        if (data.success && data.message == 'subscribed') {
            messageObj.setHtmlContent('<div align="right"><a href="#" onclick="messageObj.close();"><img src="/images/theme/close-icon.jpg" border=0 alt="Закрыть" /></a></div><div id="subscribe"><p>Вы успешно подписались на рассылку</p></div>');
        }

        if (data.success && data.message == 'unsubscribed') {
            messageObj.setHtmlContent('<div align="right"><a href="#" onclick="messageObj.close();"><img src="/images/theme/close-icon.jpg" border=0 alt="Закрыть" /></a></div><div id="subscribe"><p>Вы успешно отписались от рассылки</p></div>');
        }

        if (!data.success) {
            messageObj.setHtmlContent('<div align="right"><a href="#" onclick="messageObj.close();"><img src="/images/theme/close-icon.jpg" border=0 alt="Закрыть" /></a></div><div id="subscribe"><p>Ошибка</p></div>');
        }
        messageObj.display();
        return;
    }

    $.ajax({
        type: "POST",
        url: baseUrl+'subscribe/',
        data: {email:email,ajax:1},
        dataType: "json",
        success: callBack,
        error: callBackError
    });

    return false;
}

/**
*
* Comments
*
*/

var Comments = new Object;

Comments.last_button_click = 0;
Comments.timeBeetweenClicks = 5000;
Comments.saveCommentUrl = '';

Comments.comment = function(parent_id) {

    $("#id_parent_id").val(parent_id);
    var comm_text = $('#commentbody'+parent_id).html();

    if( $('#id_comment_text') ) {
        $('#id_comment_text').css({ backgroundColor:"#ECECEC", color:"Black",margin:"0px", padding:"px" });
        $('#id_comment_text').html(comm_text);
    }

    window.location = "#add_comment_form";
}


Comments.checkform = function () {
    if ($('#operation').val() != '') {
        return true;
    } else {
        alert('Choose operation');
        return false
    }
}


Comments.verifyDelete = function () {
    if ( confirm( msg_confirm_del ) ) {
        return true;
    } else {
        return false;
    }
}


Comments.getTime = function () {
    var date = new Date();
    return date.getTime();
}


Comments.sendComm = function(formDOM) {
    Comments.saveCommentUrl = formDOM.action;
    $('#id_button_submit_comm').attr("disabled", "disabled");

    var currTime = Comments.getTime();

    if ( 0 < Comments.last_button_click ) {
        if ( (Comments.timeBeetweenClicks + Comments.last_button_click) >  currTime ) { $('#id_button_submit_comm').attr("disabled", ""); return false; }
    }

    Comments.last_button_click = Comments.getTime();

    var parent_id = 0;
    var article_id = 0;
    var title = '';
    var content = '';

    if ( typeof(FCKeditorAPI) == 'undefined' ) {
        content = $('#tekstovepolekometaria').val();
        var oEditor = false;
    } else {
        var oFCK = FCKeditorAPI.GetInstance('tekstovepolekometaria');
        content = oFCK.GetXHTML(false);
    }

    if ($('#id_article_id')) article_id = $('#id_article_id').val();
    if ($('#id_parent_id')) parent_id = $('#id_parent_id').val();

    var postArr = {parent_id:parent_id, object_id:article_id, tekstovepolekometaria: content, ajax:1}
    Comments.sendIt( postArr );
    $('#id_button_submit_comm').attr("disabled", "");
    return false;

}

Comments.sendIt = function(poststr) {

    var gotError = function(data) {
        $('#id_cmnt_senind_msg').html(msg_cmnt_not_posted);
        return;
    }

    var gotInfo = function(data) {
        if (data.success == 0) {
            $('#id_comments_here').html(data.data);
            $('#id_cmnt_senind_msg').html(msg_cmnt_not_posted);
        }
        if( data.success == 1 ) {

            $('#id_comments_here').html(data.data);

            $('#id_parent_id').val(0);
            $('#id_comment_text').html('');
            $('#id_comment_text').toggleClass('id_comment_text_no');
            $('#id_cmnt_senind_msg').html('');

            if ( typeof(FCKeditorAPI) == 'undefined' ) {
                $('#tekstovepolekometaria').val('');
            } else {
                var oEditor = FCKeditorAPI.GetInstance('tekstovepolekometaria') ;
                oEditor.SetHTML('');
            }

            window.location.href = "#cmnt" + data.commentID;
        }
        return;
    }

    $('#id_comments_here').html('<img src="/images/progress.gif" alt="" border="0">');
    $('#id_cmnt_senind_msg').html(msg_cmnt_post);

    $.ajax({
        type: "POST",
        url: Comments.saveCommentUrl,
        data: poststr,
        dataType: "json",
        success: gotInfo,
        error: gotError
    });
    return false;
}

$.fn.insertAtCaret = function (myValue) {
    return this.each(function(){
        //IE support
        if (document.selection) {
            this.focus();
            sel = document.selection.createRange();
            sel.text = myValue;
            this.focus();
        }
        //MOZILLA/NETSCAPE support
        else if (this.selectionStart || this.selectionStart == '0') {
            var startPos = this.selectionStart;
            var endPos = this.selectionEnd;
            var scrollTop = this.scrollTop;
            this.value = this.value.substring(0, startPos)
            + myValue
            + this.value.substring(endPos,this.value.length);
            this.focus();
            this.selectionStart = startPos + myValue.length;
            this.selectionEnd = startPos + myValue.length;
            this.scrollTop = scrollTop;
        } else {
            this.value += myValue;
            this.focus();
        }
    });

};

function toggleSmiles() {
    $("#post-smiles").toggle();
}

function addSmile(what) {

    var smile = "<img src='"+what.src+"' alt='' border='0' />";

    if(ToggleEditors.switched_rte_on) {

        var oEditor = FCKeditorAPI.GetInstance(ToggleEditors.textArea);
        oEditor.InsertHtml(smile);

    } else {
        $("#"+ToggleEditors.textArea).insertAtCaret(smile);
    }
}

var lastKeyPress='';

function keyChangeDay(e)
{
    var date = new Date();
    var currKeyPress = date.getHours()+date.getMinutes()+date.getSeconds();
    if( 0 < lastKeyPress ) lastKeyPress += 30;
    if( lastKeyPress < currKeyPress ) {
        if (!e) e = window.event;
        var k = e.keyCode;
        var d = 0;
        var start_count = false;

        if (e.ctrlKey) {
            if (k == 39) window.location.href = next_url;
            if (k == 37) window.location.href = prev_url;
        }
    }
}
function keyPress()
{
    var date = new Date();
    lastKeyPress = date.getHours()+date.getMinutes()+date.getSeconds();
}