function loadURL(sUrl, sData)
{
   var sData;
   if (null == sData || undefined == sData) sData = {};  

   $.ajax({
      type: "POST",
      url: sUrl,
      data : sData,
      dataType: "html",
      timeout: 30000,
      success: function(data){ 
         window.location.reload();
      },
      error: function()
      {
         alert(sOutput + ': Load data failed!');
      }
   });
}  


function checkSignUpForm()
{

    var error = '';
    var focus = '';

    $('.is_required').each(function(i,elem) {
        if ($(elem).val() == "")
        {
            var label_id = "required_"+($(elem).attr('id'));
            //alert($("#"+label_id).text());
            error += $("#"+label_id).text()+"\n";
            if (!focus) focus = $(elem).attr('id');

        }
    });

    if (error)
    {
        alert(error);
        if (focus) setFocus(focus);
        return false;
    }

    if ($("#user_email").val() != "" && !checkEmail($("#user_email").val()))
    {
        alert("Please, enter valid email address.");
        setFocus("user_email");
        return false;
    }
/*
    if ($("#user_email").val() != $("#user_email_confirm").val())
    {
        alert("Please verify your email - the email you entered in both fields does not match.");
        setFocus("user_email_confirm");
        return false;
    }
*/
    if ($("#user_password").val().length < 6 || $("#user_password").val().length > 18)
    {
        alert("Your password must be 6 to 18 characters long with no spaces.");
        setFocus("user_password");
        return false;
    }

    if ($("#user_password").val() != $("#user_password2").val())
    {
        alert("Please verify your password - the password you entered in both fields does not match.");
        setFocus("user_password2");
        return false;
    }

    return true;
//    if (error)
//    {
//        alert(error);
//        return false;
//    } else {
//
//        return true;
//    }
}

function checkProfileForm(profile_type)
{
    if (!profile_type || profile_type == "")
    {
        alert ("Profile type not set!");
        return;
    }
    var error = '';
    var focus = '';

    $('.is_required').each(function(i,elem) {
        if ($(elem).val() == "")
        {
            var label_id = "required_"+($(elem).attr('id'));
            //alert($("#"+label_id).text());
            error += $("#"+label_id).text()+"\n";
            if (!focus) focus = $(elem).attr('id');

        }
    });

    if ($('#new_password').val() != $('#new_password2').val()) error += 'Enter correct "New Password" and "Confirm New Password"\n';
    else if ($('#new_password').val() && ($('#new_password').val().length < 6 || $("#new_password").val().length > 18)) error += 'Your password must be 6 to 18 characters long with no spaces.\n';

    if (error)
    {
        alert(error);
        if (focus) setFocus(focus);
        return false;
    } else {
        $.ajax({
                type: "POST",
                dataType: "html",
                url: "/"+profile_type+"/profile/",
                data: $('#profile_form').serialize(),
                success: function (response)
                {
                    //clean password fields
                    $('#current_password').val('');
                    $('#new_password').val('');
                    $('#new_password2').val('');

                    var data = $.evalJSON(response);

                    if (data['error'])
                    {
                        alert(data['error']);
                        return false;
                    }

                    if (data['success'])
                    {
                        alert(data['success']);
                        return false;
                    }
                }
        });
    }
}

function checkEmployeeForm()
{
    //check fields
    var dob = $('#date_dob_y').val() + '-' + $('#date_dob_m').val() + '-' + $('#date_dob_d').val();
    if (!isValidDateOfBirth(dob))
    {
        ShowMessage('Select correct date of bitrh', 'Error', 'error');
        $('#date_dob_m').focus();
        return false;
    }

    var ssn = trim($('#ssn_1').val()) + trim($('#ssn_2').val()) + trim($('#ssn_3').val());
    if (ssn.length > 0 && (ssn.length !=9 || !checkIsIntNumberCorrect(ssn)))
    {
        ShowMessage('Incorrect SSN', 'Error', 'error');
        $('#ssn_1').focus();
        return false;
    }

    $.ajax({
            type: "POST",
            dataType: "html",
            url: "/applicant/employee/",
            data: $('#employee_form').serialize(),
            success: function (response)
            {
                var data = $.evalJSON(response);

                if (data['error'])
                {
                    alert(data['error']);
                    return false;
                }

                if (data['success'])
                {
                    //GA track event
                    if ($('#applicant_id').val() <= 0)
                    {
                        _gaq.push(['_trackEvent', 'Completed Form', 'Applicant Personal Info', '']);
                    }

                    alert(data['success']);

                    if ($('#applicant_id').val() <= 0)
                    {
                        window.location.href = "/applicant/application/";
                    }else{
                        window.location.reload();
                    }
                    return false;
                }
            }
    });
}

function checkApplicationForm()
{
        $.ajax({
                type: "POST",
                dataType: "html",
                url: "/applicant/application/",
                data: $('#application_form').serialize(),
                success: function (response)
                {
                    var data = $.evalJSON(response);

                    if (data['error'])
                    {
                        alert(data['error']);
                        return false;
                    }

                    if (data['success'])
                    {
                        //GA track event
                        if ($('#application_id').val() <=0 )
                        {
                            _gaq.push(['_trackEvent', 'Completed Form', 'Applicant Application', '']);
                        }
                        
                        $('.school_id').each(function(i,o){
                            if (data['property_ids']['school_ids'])
                            $(o).val(data['property_ids']['school_ids'][i]);
                        });
                        
                        $('.work_exp_id').each(function(i,o){
                            if (data['property_ids']['work_exp_ids'])
                            $(o).val(data['property_ids']['work_exp_ids'][i]);
                        });
                        
                        $('.convicted_id').each(function(i,o){
                            if (data['property_ids']['convicted_ids'])
                            $(o).val(data['property_ids']['convicted_ids'][i]);
                        });
                        
                        if (data['help_popup'] == true)
                        {
                            showPopup2(400,'/applicant/help_popup/');
                        } else {
                            alert(data['success']);
                            window.location.reload();
                        }
                        return false;
                    }


                }
        });
}

function checkClientForm()
{
    if (validateClientDataForm())
    {
        //GA track event
        if ($('#client_id').val() <= 0)
        {
            _gaq.push(['_trackEvent', 'Completed Form', 'Client Company Info', '']);
        }

        $.ajax({
                type: "POST",
                dataType: "html",
                url: "/client/data/",
                data: $('#client_form').serialize(),
                success: function (response)
                {
                    var data = $.evalJSON(response);

                    if (data['error'])
                    {
                        alert(data['error']);
                        return false;
                    }

                    if (data['success'])
                    {
                        alert(data['success']);
                        //ShowMessage(data['success'], 'Success', 'success');
                        window.location.reload();
                        return false;
                    }
                }
        });
    }
}


function checkJRForm()
{
        $.ajax({
                type: "POST",
                dataType: "html",
                url: "/client/job_requests/",
                data: $('#jr_form').serialize(),
                success: function (response)
                {
                    var data = $.evalJSON(response);

                    if (data['error'])
                    {
                        alert(data['error']);
                        return false;
                    }

                    if (data['success'])
                    {
                        alert(data['success']);
                        window.location.reload();
                        return false;
                    }
                }
        });
}

function checkEmploymentVerificationForm()
{
        $.ajax({
                type: "POST",
                dataType: "html",
                url: "/applicant/employment_verification/",
                data: $('#verification_form').serialize(),
                success: function (response)
                {
                    var data = $.evalJSON(response);

                    if (data['error'])
                    {
                        alert(data['error']);
                        return false;
                    }

                    if (data['success'])
                    {
                        alert(data['success']);
                        window.location.reload();
                        return false;
                    }
                }
        });
}

function checkWebAccountsForm()
{
        if ($("#new_web_account_email").val() != "" && !checkEmail($("#new_web_account_email").val()))
        {
            alert("Please, enter valid email address.");
            setFocus("new_web_account_email");
            return false;
        }
        $.ajax({
                type: "POST",
                dataType: "html",
                url: "/client/web_accounts/",
                data: $('#web_accounts_form').serialize(),
                success: function (response)
                {
                    var data = $.evalJSON(response);

                    if (data['error'])
                    {
                        alert(data['error']);
                        return false;
                    }

                    if (data['success'])
                    {
                        alert(data['success']);
                        window.location.reload();
                        return false;
                    }
                }
        });
}

function changeStatusHirings(jrId, status)
{
    if (checkSelectedApplicants())
    {
        $.ajax({
            type: "POST",
            url: '/client/job_requests/change_status/',
            data: $('#apl_listing_form').serialize() + '&id='+jrId+'&status_id='+status,
            dataType: "html",
            complete: function(){

            },
            success: function(response){
                if (trim(response))
                {
                    var data = $.evalJSON(response);
                    if (data['changed'])
                    {
                        $.each(data['changed'], function(k,v){
                            $('#hiring_status_id_'+k).text(v);
                        });
                        ShowMessage('Status was changed', 'Success', 'error');
                    }
                }
            },
            error: function()
            {
                alert('Export operation failed!');
            }
        });
    }
}

function checkSelectedJRs()
{
    if ($('.jr_cl_id_chk:checked').size() <= 0)
    {
        alert('Check at least one Job request');
        return false;
    } else {
        return true;
    }
}

function deleteJRs()
{
    if (checkSelectedJRs())
    {
        if (confirm_delete())
        {
            $.ajax({
                type: "POST",
                url: '/client/job_requests/delete/',
                data: $('#jr_cl_listing_form').serialize(),
                dataType: "html",
                complete: function(){},
                success: function(response){
                    window.location.reload();
                },
                error: function()
                {
                    alert('Export operation failed!');
                }
            });
        }
    }
}

function checkSelectedNotifications()
{
    if ($('.notif_id_chk:checked').size() <= 0)
    {
        alert('Check at least one Notification');
        return false;
    } else {
        return true;
    }
}

function deleteNotifications()//Was tested for applicant and client
{
    if (checkSelectedNotifications())
    {
        if (confirm_delete())
        {
            pos = window.location.href.indexOf('/notifications');
            newHref = window.location.href.substr(0,pos);
            $.ajax({
                type: "POST",
                url: newHref+'/notifications/delete/',
                data: $('#notif_listing_form').serialize(),
                dataType: "html",
                complete: function(){},
                success: function(response){
                    window.location.reload();
                },
                error: function()
                {
                    alert('Export operation failed!');
                }
            });
        }
    }
}

function confirm_delete() {
        if (confirm('Are you sure you want to remove?')) {
                return true;
        } else {
                return false;
        }
}
function c_ODTA () {//Object for data table
    this.BOX        = '.block-table-box';
    this.CART       = '.block-table-cart';
    this.ITEM       = '.block-table-item';
    this.PLACE      = '.block-table-place';
    this.ADD        = '.add-table-data';
    this.DEL        = '.delete-table-data';
    this.NUM        = '.block-table-data-num';
    this.NEWc       = 'block-table-item-new';
    this.ROW_LTc    = 'block-table-row-light';
    this.ROW_DKc    = 'block-table-row-dark';
    this.LAST_ITEMc = 'block-table-item-last';
    this.FIRST_ITEMc = 'block-table-item-first';
    var self = this;
    $(self.BOX).each(function(){
        self.refreshRows($(this));
        self.initItemBox($(this));
    });
    $(self.ADD).live('click',function(){self.add($(this))});
    $(self.DEL).live('click',function(){self.del($(this))});
}c_ODTA.prototype = {
    isTest   : 0,
    c        : function(message){this.isTest && console && console.log(message);},
    add      : function(clickElem){
        var self = this;
        var wrapper = clickElem.closest(this.BOX);
        var elem    = wrapper.find(this.CART+' '+this.ITEM);
        var elemTo  = wrapper.find(this.PLACE);
        _GLOBAL_F.addElemCloneTo(elem, elemTo, function(addedElem) {
            self.c('add '+addedElem.length+' new elem');
            addedElem.addClass(self.NEWc);
            self.refreshCE(addedElem);
        });
        self.refreshRows(clickElem.closest(self.BOX));
        self.initItemBox(wrapper);
    },
    del       : function(clickElem,flag){
        var self = this;
        if (!flag && this.confirmDEL()){
            var elem = clickElem.closest(self.ITEM);
            var wrapper = clickElem.closest(self.BOX);
            this.c('deleted ' + elem.length + ' items');
            elem.remove();
            self.refreshRows(wrapper);
            self.initItemBox(wrapper);
        }
    },
    refreshCE  : function(search_in){
        search_in.find('input').val('').ceInput();
        search_in.find('select').val(0);
        search_in.find('.ce-select').ceSelect();
        this.c('refresh CE');
        search_in.find('ce-input').ceInput();
    },
    confirmDEL : function(){
        var conf = confirm_delete();
        this.c('deltete is ' + (conf ? 'confirmed' : 'aborted'));
        return conf;
    },
    initItemBox : function(region){
        var self = this;
        if(!region.find(self.PLACE + ' ' + self.ITEM).length){
            region.find(self.PLACE).hide();
            region.find('thead').hide();
        }else{
            region.find(self.PLACE).show();
            region.find('thead').show();
        }
    },
    refreshRows : function(region) {
        this.c('refresh ROWs');
        var self = this;
        var item = region.find(self.PLACE + ' ' + self.ITEM);
        var len = item.length;
        item.each(function(i){
            $(this).removeClass(self.ROW_LTc + ' '+self.ROW_DKc);
            (i%2) ? $(this).addClass(self.ROW_LTc): $(this).addClass(self.ROW_DKc);
            (i == (len-1)) ? $(this).addClass(self.LAST_ITEMc) : $(this).removeClass(self.LAST_ITEMc);
            (i == 0) ? $(this).addClass(self.FIRST_ITEMc) : $(this).removeClass(self.FIRST_ITEMc);
            $(this).find(self.NUM).text((i + 1) + '.');
        });
    }
}
function set_middle_position_on_resize(elem){
    function top_marg (elem) {
        var h_body = $('body').height();
        var h_elem = elem.height();
        var t_body = 190;
        var b_body = 55;
        var min_marg = 10;
        var marg = (h_body - h_elem - 2*t_body - b_body)/2;
        elem.css({'margin-top':Math.ceil((marg > min_marg ) ? marg : min_marg)});
    }
    $(window).resize(function(){setTimeout(function(){top_marg(elem)},100);});
    top_marg(elem);
}

function sendPhoneConfirmation()
{
    $.ajax({
        type: "POST",
        url: '/ajax_functions/send_phone_confirmation/',
        dataType: "html",
        complete: function(){},
        success: function(response){

        }
    });
}
