function checkIsIntNumberCorrect(sNumber)
{
	var re = new RegExp("^(\\d)+$");
	var ares = re.exec(sNumber);
	if ( null == ares )
	{
		return false;
	}

	return true;
}

function isValidDate(dateStr) {
    var datePat = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) return false;

    year = matchArray[1]; // p@rse date into variables
    month = matchArray[3];
    day = matchArray[5];

    if (month < 1 || month > 12) return false;
    if (day < 1 || day > 31) return false;
    if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) return false;


    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day == 29 && !isleap)) return false;
    }

    return true; // date is valid
}

function isValidDateOfBirth(dateStr)
{
    if (!isValidDate(dateStr))
    {
        return false;
    } else {
        var now = new Date();
        var year = now.getFullYear();

        var sel = new Date(dateStr);
        var selYear = sel.getFullYear();
        if (selYear < 1900 || selYear > year)
        {
            return false;
        }
    }

    return true;
}

function ShowMessage(message, title, style)
{
    $.jGrowl(message, { header: title, theme:style, open: function(e,m,o){  } });
}

function saveJR(actionUrl,admin_redirect)
{
    var error = '';
    if (!trim($('#jr_name').val())) error += 'Enter "Job Title"\n';
    if ($('#client_id').size())
    {
        if ($('#client_id').val() <= 0) {
            error += "Enter 'Company Name'\n";
        }
    }
    if ($('#employment_type_id').val() <= 1) error += 'Select "Employment Type"\n';
    if ($('#job_category_id').val() <= 1 && $('#job_category_id').val() != -999) error += 'Select "Job Category"\n';
    if ($('#job_category_id').val() == -999 && $('#customer_category').val() <= 0) error += 'Enter "Category Name"\n';
    
//    if ($('#jr_type_id').val() <= 0) error += 'Select "Job Type"\n';
//    if (!trim($('#jr_description').val())) error += 'Enter "Description"\n';
    if (isNaN(parseInt($('#required_applicants_number').val()))  || parseInt($('#required_applicants_number').val()) <= 0 ) error += 'Select "Number of Staff"\n';

    if (error) {
        //alert(error);
        ShowMessage(error.split('\n').join('<br>'), 'Error', 'error');
        return false;
    } else {
        //GA track event
        if (!$('#client_id').size())
        {
            if (typeof(_gaq) != 'undefined') _gaq.push(['_trackEvent', 'Job Request', 'New', '']);
        }
        $.ajax({
            type: "POST",
            url: actionUrl,
            data: "ajax=1&"+$('#jr_form').serialize(),
            dataType: "json",
            complete: function(){},
            success: function(response){
                if (admin_redirect && admin_redirect == 1)
                {
                    window.location.href="/manager/dashboard/";
                } else {
                     window.location.href="/client/job_requests/";
                }

            },
            error: function()
            {
                alert('Save operation failed!');

            }
        });
        return true;
    }
}

function checkSelectedApplicants()
{
    if ($('.apl_id_chk:checked').size() <= 0)
    {
        alert('Check at least one Applicant');
        return false;
    } else {
        return $('.apl_id_chk:checked').size();
    }
}

function checkSelectedApplicantsFromData(selection)
{

    if (selection == 0) {
        if ($('.apl_id_chk:checked').size() <= 0) {
            alert('Check at least one Applicant');
            return false;
        } else {
            return $('.apl_id_chk:checked').size();
        }
    } else {

        if (typeof($('#apl_listing').data("apl_currentContent")) != 'undefined' && $('#apl_listing').data("apl_currentContent").length) {
            return $('#apl_listing').data("apl_currentContent").length;
        } else {
            alert('Check at least one Applicant');
            return false;
        }
    }
}

function getZipCodeInfo(zip, prefix) {

    if (zip.length != 5) return false;

    prefix = typeof(prefix) != 'undefined' ? prefix : '';

    $.ajax({
         type: "POST",
         url: "/ajax_functions/select_zip/",
         data:  'zip='+zip,
         dataType: "html",
         success: function(response){
             var data = $.evalJSON(response);
             if (data.city) $('#'+prefix+'city').val(data.city);
             if (data.state) $('#'+prefix+'state').ceSelect(data.state);
         }
    });
}
/*
* @thisJqElem - $(this) - jq object
* @wrapperSelector - [optional, default value is '.block-table-item'] - selector of wrapper element
* @citySelector - [optional, default value is '.input-autocomplete-city'] - selector of CITY input wrapper element
* @stateSelector - [optional, default value is '.select-autocomplete-state'] - selector of STATE select input wrapper element
* */
function getZipCodeInfoJQ(thisJqElem,wrapperSelector,citySelector, stateSelector){
   var testing = 0;
   zip = thisJqElem.val();
   if (zip.length != 5){
      testing && console && console.log('zip download false');
      return false;
   }else{
      testing && console && console.log('zip download go!');
      function initSelectorForZipAutocomplete(thisJqElem,inpObj){
         default_selectors = { wrapper : '.block-table-item', city : '.input-autocomplete-city', state : '.select-autocomplete-state'};

         for(field in inpObj){(!inpObj[field]) ? inpObj[field] = default_selectors[field] : null ;}
         var wr = thisJqElem.closest(inpObj.wrapper);

         testing && console && console.log('"'+inpObj.city+'" length is "'+wr.find(inpObj.city+' input').length +'"');
         testing && console && console.log('"'+inpObj.state+'" length is "'+wr.find(inpObj.state+' select').length +'"');

         return { city : wr.find(inpObj.city+' input') , state : wr.find(inpObj.state+' select') };
      }

      var jq_obj = initSelectorForZipAutocomplete(thisJqElem,{wrapper:wrapperSelector,city:citySelector, state:stateSelector});

      $.ajax({
         type: "POST",
         url: "/ajax_functions/select_zip/",
         data:  'zip='+zip,
         dataType: "html",
         success: function(response){
            var data = $.evalJSON(response);
            data.city && jq_obj.city.val(data.city);
            data.state && jq_obj.state.ceSelect(data.state);
         }
      });
   }
}
function liveDataPickerInit(selector){
   var testing = 0;
   $(selector+' input').live('focus',function(){
      if (!$(this).data('dataPicker')) {
         $(this).datepicker({
            dateFormat: 'mm/dd/yy',
            changeMonth: true,
            changeYear: true,
            minDate: '-20y',
            maxDate: '+5y'
         });
         testing && console && console.log('dp - bind');
         $(this).data('dataPicker',true);
         $(this).trigger('focus');
      }
   });
}
function primaryCopyToBilling()
{
    $("#billing_firstname").val($("#firstname").val());
    $("#billing_lastname").val($("#lastname").val());
    $("#billing_address").val($("#address").val());
    $("#billing_city").val($("#city").val());
    $('#billing_state').ceSelect($("#state").val());
    $("#billing_zip").val($("#zip").val());
    $("#billing_phone").val($("#phone").val());

    $("#phone-billing_phone-1").val($("#phone-phone-1").val());
    $("#phone-billing_phone-2").val($("#phone-phone-2").val());
    $("#phone-billing_phone-3").val($("#phone-phone-3").val());

    $("#billing_alt_phone").val($("#alt_phone").val());
    $("#billing_fax").val($("#fax").val());
    $("#billing_email").val($("#email").val());
}

function validateClientDataForm() {
    var errorPrimary = '';
    var errorBilling = '';
    var error = '';

    if ($('#user_email').size() && !trim($('#user_email').val())) error += '- Fill "Email" field\n';
    if ($('#user_password').size() && !trim($('#user_password').val())) error += '- Fill "Password" field\n';

    if ($('#user_password').size() && ($("#user_password").val().length < 6 || $("#user_password").val().length > 18))
    {
        error += '- Your password must be 6 to 18 characters long with no spaces.\n';
    }

    if (!trim($('#company_name').val())) error += '- Fill "Company Name" field\n';

    if (!$("#firstname").val()) errorPrimary += '- Fill "First Name" field\n';
    if (!$("#lastname").val()) errorPrimary += '- Fill "Last Name" field\n';
    if (!$("#address").val()) errorPrimary += '- Fill "Address" field\n';
    if (!$("#zip").val()) errorPrimary += '- Fill "Zip Code" field\n';
    if ($("#state").val() == 'State') errorPrimary += '- Select "State" field\n';
    if (!$("#city").val()) errorPrimary += '- Fill "City" field\n';
    if (!$("#phone").val()) errorPrimary += '- Fill "Phone" field\n';
    if ($("#email").val() && !checkEmail($("#email").val())) errorPrimary += '- Fill correct "Email" field\n';
    if (!$("#billing_firstname").val()) errorBilling += '- Fill "First Name" field\n';
    if (!$("#billing_lastname").val()) errorBilling += '- Fill "Last Name" field\n';
    if (!$("#billing_address").val()) errorBilling += '- Fill "Address" field\n';
    if (!$("#billing_zip").val()) errorBilling += '- Fill "Zip Code" field\n';
    if ($("#billing_state").val() == 'State') errorBilling += '- Select "State" field\n';
    if (!$("#billing_city").val()) errorBilling += '- Fill "City" field\n';
    if (!$("#billing_phone").val()) errorBilling += '- Fill "Phone" field\n';
    if ($("#billingEmail").val() && !checkEmail($("#billingEmail").val())) errorBilling += '- Fill correct "Email" field\n';

    if (errorPrimary) {
        error += 'PRIMARY INFO: \n\n';
        error += errorPrimary;
    }

    if (errorBilling) {
        if (errorPrimary) error += '\n\n';
        error += 'BILLING INFO: \n\n';
        error += errorBilling;
    }

    if (error) {
        //alert(error);
        ShowMessage(error.split('\n').join('<br>'), 'Error', 'error');
        return false;
    } else {
        return true;
    }
}

function clearAllFields(elem)
{
    $(elem+' input').val('');
}

function showPopup2(nWidth, data)
{
    $('#modalContent').html("");
    $('#modalPreloader').css('display', 'block');

    if (nWidth > 0)
    {
        //block screen
        $('#body').block({
            message: $('#modalWindow'),
            centerY: false,
            css:
            {
                top: getBodyScrollTop() + 40,
                left: ($(window).width() - nWidth) /2 + 'px',
                width: nWidth + 'px'
            }
        });
    }

    var url = data.split('?');

    //get contents
    $.ajax({
        type: "POST",
        url: url[0],
        data: url[1] + '&ajax=1',
        dataType: "html",
        complete: function(){},
        success: function(response)
        {
            ce();
            ceTimePicker();
            $('#modalPreloader').css('display', 'none');
            $('#modalContent').html(response);
        },
        complete: function()
        {
            $(".blockOverlay").css('height',$(document).height());
        }
    });
}

function hidePopup()
{
	$('#modalContent').hide();
	$('#body').unblock({ });
}

function closePopup()
{
	$('#modalContent').html("");
    $('#modalContent').show();
	$('#body').unblock({ });
}

/* Timers */
jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});


jQuery.extend({timer:{guid:1,global:{},regex:/^([0-9]+)\s*(.*s)?$/,powers:{ms:1,cs:10,ds:100,s:1e3,das:1e4,hs:1e5,ks:1e6},timeParse:function(a){if(a==undefined||a==null)return null;var b=this.regex.exec(jQuery.trim(a.toString()));if(b[2]){var c=parseInt(b[1],10);var d=this.powers[b[2]]||1;return c*d}else{return a}},add:function(a,b,c,d,e,f){var g=0;if(jQuery.isFunction(c)){if(!e)e=d;d=c;c=b}b=jQuery.timer.timeParse(b);if(typeof b!="number"||isNaN(b)||b<=0)return;if(e&&e.constructor!=Number){f=!!e;e=0}e=e||0;f=f||false;if(!a.$timers)a.$timers={};if(!a.$timers[c])a.$timers[c]={};d.$timerID=d.$timerID||this.guid++;var h=function(){if(f&&this.inProgress)return;this.inProgress=true;if(++g>e&&e!==0||d.call(a,g)===false)jQuery.timer.remove(a,c,d);this.inProgress=false};h.$timerID=d.$timerID;if(!a.$timers[c][d.$timerID])a.$timers[c][d.$timerID]=window.setInterval(h,b);if(!this.global[c])this.global[c]=[];this.global[c].push(a)},remove:function(a,b,c){var d=a.$timers,e;if(d){if(!b){for(b in d)this.remove(a,b,c)}else if(d[b]){if(c){if(c.$timerID){window.clearInterval(d[b][c.$timerID]);delete d[b][c.$timerID]}}else{for(var c in d[b]){window.clearInterval(d[b][c]);delete d[b][c]}}for(e in d[b])break;if(!e){e=null;delete d[b]}}for(e in d)break;if(!e)a.$timers=null}}}})
