function loadLocationData(cityId, outputId, country, state, city) {
    loadContent(outputId, 'leads/ajaxprocess.php', {cityId: cityId, type: 'location_option'}, '', true, function(data){
        jQuery('#' + outputId).hide();

        if (typeof(country) == 'undefined') country = 'country';
        if (typeof(state) == 'undefined') state = 'state';
        if (typeof(city) == 'undefined') city = 'city';

        jQuery('#' + country).val(data.countryId);
        jQuery('#' + state).html(data.states);
        jQuery('#' + city).html(data.cities);
        jQuery('#load-data').remove();
    }, 'isLoading', "json");
}

function testZip(zip, outputId, country, state, city) {

    loadContent(outputId, 'leads/ajaxprocess.php', {zipcode: zip.value, type: 'test_zip'}, '', true, function(date){
//            debugger;
            if (date.html == "") {
                jQuery('.dropdown').hide();    
            }

            jQuery('body').bind('click', function(event){
                jQuery('.dropdown').slideUp();
                jQuery('body').unbind('click');
            });

            jQuery('.item-dropdown').bind('click', function(event){                                                

                if (jQuery(this).attr('cityId') && jQuery(this).text()) {
                    zip.value = jQuery(this).text();
                    jQuery('.dropdown').slideUp();
                }
                jQuery('#' + outputId).html('');
                jQuery('#' + outputId).after('<div id="load-data" class="isLoading"></div>');
                loadLocationData(jQuery(this).attr('cityId'), outputId, country, state, city);
            });
        
    }, 'isLoading', "json");
}

function loadState(country, stateId, cityId) {
    jQuery('#' + cityId).html('');
    jQuery('#' + stateId).html('');
    loadContent(stateId, 'leads/ajaxprocess.php', {countryId: country.value, type: 'state_option'}, '', true, function(){}, 'none', "json");
}

function loadCity(state, cityId) {
    jQuery('#' + cityId).html('');
    loadContent(cityId, 'leads/ajaxprocess.php', {stateId: state.value, type: 'city_option'}, '', true, function(){}, 'none', "json");
}

function resizeBorder() {
    jQuery('.form_border_left, .form_border_right').css('height', jQuery('.form_window').height() - (jQuery('.form_caption').height() + jQuery('.form_footer').height()));
}

function submitFormSuccess(data, step) {

    var stepClass = '';

    if (step != undefined) {
        stepClass = 'form_step_' + step;
    }

    jQuery('.vendorfind_form_frame').remove();


    jQuery('.vendorfind_form_frame').append('' +
            '<div  class="form_window ' + stepClass + '">' +
                '<div class="form_caption">' +
                    '<div class="form_title">' + data.message + '</div><div class="form_close_btn"></div>' +
                '</div>' +
                '<div class="form_border_left"></div>' +
                '<div class="form_content" id="leads-form-content">' + data.content + '</div>' +
                '<div class="form_border_right"></div>' +
                '<div class="form_footer"></div>' +
            '</div>');


    var top = (jQuery(window).height() - jQuery('.form_window').height()) / 2;
    if (top < 0) top = 0;

    var left = (jQuery(window).width() - jQuery('.form_window').width()) / 2;
    if (left < 0) left = 0;

    jQuery('.form_window').css('left', left);
    jQuery('.form_window').css('top', top);
    resizeBorder();
    jQuery('.form_window').show();
}

function checkText(value) {
    if (!value.length) return "The field not allows be empty";
   // if (!checkRegexp( value, /^([0-9a-zA-Z,-.])+$/)) return "Text field only allow : a-z 0-9 and periods, dashes, commas";
    return true;
}

function checkEmail(value) {

    if (!value.length) return "The field not allows be empty";
    if (!checkRegexp( value, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i)) return "Incorrect email(email@vendofind.com)";
    return true; 
}

function checkZip(value) {
    if (!value.length) return "The field not allows be empty";
    if (!checkRegexp( value, /^([0-9])+$/)) return "Zip field only allows : 0-9";
    return true;
}

function checkPhone(value) {
    if (!value.length) return "The field not allows be empty";
    if (!checkRegexp( value, /^([0-9.-])+$/)) return "Phone field only allows : 0-9, periods, dashes";
    return true;
}
function checkRegexp( o, regexp) {
    if ( !( regexp.test( o ) ) ) {

        return false;
    } else {
        return true;
    }
}

function validValueField(value, type) {
    switch(type) {
        case 'text':
                return checkText(value);
        break;
        case 'email':
                return checkEmail(value);
        break;
        case 'zip':
                return checkZip(value);
        break;
        case 'phone':
                return checkPhone(value);
        break;
        default:
        if (value) return true;
    }
    return "This field is required!";
}

function validCheckBoxGroup(name) {
    var checked = false;
    jQuery('[id^=checkbox_'+name+']').each(function(){
        checked |= this.checked;
    });

    if (checked) return true;

    return "Please select an answer!"
}

function showErrorLeadsFieldMessage(destId, message) {
    //debugger;
   jQuery('.vendorfind_form_frame #' + destId).before('<div class="ui-state-error-field-message">' + message + '</div>');
    jQuery('.vendorfind_form_frame #' + destId).parent().addClass('ui-state-error-field');
}

function valid_required_field() {
    var valid = true;
    jQuery(".ui-state-error-field-message").remove();
    jQuery(".ui-state-error-field").removeClass('ui-state-error-field');
    var validGroup = new Array();
    jQuery('.required').each(function(){
         var name = this.name;
         if (this.name.indexOf('[]') > 0) {
            name = this.name.substr(0, this.name.indexOf('[]'));
         }

         var res_valid = true;

         var label_id = 'label_for_' + name;
         var errorId  = this.id;
         if (this.type == 'checkbox') {

             if (validGroup.indexOf(name)  == -1) {
                validGroup.push(name);

                res_valid = validCheckBoxGroup(name);
             }
             errorId = 'answer_option_' + name;
//             debugger;
         } else {

            res_valid = validValueField(this.value, jQuery(this).attr('valid_type'));
         }

         if (res_valid != true) {
            valid = false; 
            showErrorLeadsFieldMessage(errorId, res_valid);
         }

    });

    return valid;
}

function submitForm(formId, formStringId, errorsId, messagesId, test_next, step) {

    if (test_next()) {
        jQuery('#' + formStringId).submit();
    }
}

function nextStep(formId, formStringId, step, test_next) {

    if (test_next()) {
        jQuery('#' + formStringId).submit();
    }
}

function showLeadsForm(formId, step, params, addlead, cvfid) {
    
    jQuery('.vendorfind_form_frame').append('' +
            '<div  class="form_window form_step_' + step + '">' +
                '<div class="form_caption">' +
                    '<div class="form_title">' + jQuery('#campaign_title').html() +'</div><div class="form_close_btn"></div>' +
                '</div>' +
                '<div class="form_border_left"></div>' +
                '<div class="form_content" id="leads-form-content"></div>' +
                '<div class="form_border_right"></div>' +
                '<div class="form_footer"><div class="form_step_number">' +
                '<span class="text_step">Step</span>' +
                '<img alt="" src="assets/components/call/images/leads_form_number_step_' + step + '.gif"/>' +
                '<span class="text_of">of</span>' +
                '<img alt="" src="assets/components/call/images/leads_form_number_step_count.gif"/>' +
                '</div></div>' +
            '</div>');


    jQuery(window).resize(function(event){

        if (!jQuery('.form_window')[0]) return 0;

        var top = (jQuery(window).height() - jQuery('.form_window').height()) / 2;
        if (top < 0) top = 0;

        var left = (jQuery(window).width() - jQuery('.form_window').width()) / 2;
        if (left < 0) left = 0;

        jQuery('.form_window').css('left', left);
        jQuery('.form_window').css('top', top);
    });

    jQuery('.form_frame').addClass('isLoading');

    if (typeof(params) == 'undefined') params = {};

    params['campaign'] =  formId;
    params['step'] =  step;

    var url = 'leads/ajaxshowform.php';
    
    if (addlead) {
        params['cvfid'] =  cvfid;
        url = 'leads/ajaxaddlead.php';
    }

    loadContent('leads-form-content', url, params, 'leads-form-content', true, function(){

        var top = (jQuery(window).height() - jQuery('.form_window').height()) / 2;
        if (top < 0) top = 0;

        var left = (jQuery(window).width() - jQuery('.form_window').width()) / 2;
        if (left < 0) left = 0;

        jQuery('.form_window').css('left', left);
        jQuery('.form_window').css('top', top);

         resizeBorder();
        jQuery('.form_frame').removeClass('isLoading');
        jQuery('.form_window').show();
//        debugger;
        jQuery('#data_form :input').bind("keypress", function(event){
            if (event.keyCode == 13) {
                 jQuery('#leads-form-submit-btn').click();                
            }
        });


    }, 'none', "json");
}

function loadContent(destinationId, sourceUrl, params, errorsId, clear, callback, loadingClass, dataType)
{

	if (typeof(loadingClass) == 'undefined') {
		loadingClass = 'isLoading';
	}

	if (typeof(dataType) == 'undefined') {
		dataType = "json";
	}

	jQuery('#' + destinationId).removeClass('ajax-response-errors');

	if (typeof(clear) != 'undefined' && clear)
		jQuery('#' + destinationId).empty();
//    debugger;
    jQuery('#' + destinationId).show();
	jQuery('#' + destinationId).addClass(loadingClass);
   //debugger;   
	if (typeof(errorsId) == 'undefined') errorsId = destinationId;

	jQuery.ajax({
		url: sourceUrl,
		global: false,
		type: "POST",
		data: params,//({'userid' : item.id}),
		dataType: dataType,
		success: function(response, textStatus)
		{            
			jQuery('#' + destinationId).removeClass(loadingClass);

			if (!response) {
				showErrors(destinationId, 'AJAX response error');
			}

            if (response.redirect) {
                window.location = response.redirect;
                exit;
            }

			if (!response.error && jQuery('#' + destinationId)[0]) {
				//debugger;
				//  debugger;
                if (dataType == "json")
				    jQuery('#' + destinationId).html(response.html).show();

                if (dataType == "html")
				    jQuery('#' + destinationId).html(response).show();
//                 debugger;
                if (dataType == "text")
				    jQuery('#' + destinationId)[0].innerHTML = response;


			} else {
				showErrors(destinationId, response.error);
			}


			if (callback) {

				callback(response);
			}
		},

		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			jQuery('#' + destinationId).removeClass(loadingClass);
			if (typeof(errorThrown) == 'undefined') errorThrown = 'AJAX error';

            showErrors(errorsId, errorThrown);

            if (callback) {

				callback();
			}

		}
	});
}

function showErrors(destinationId, text)
{

	jQuery('#' + destinationId).empty().addClass('ajax-response-errors');
	jQuery('#' + destinationId).html(text);
}

function submitAjaxForm(formId, errorsId, messagesId, callback, step)
{   //debugger;
	if (messagesId == undefined) {
		messagesId = errorsId;
	}

	if (messagesId.length && jQuery('#' + messagesId))
		jQuery('#' + messagesId).html('Form sending ...').fadeIn(500);
    resizeBorder();

	if (errorsId.length && jQuery('#' + errorsId))
		jQuery('#' + errorsId).fadeOut();

	var form = jQuery('#' + formId);
	//debugger;
	jQuery.post(jQuery('body')[0].baseURI + form.attr('action'), form.serialize(), function(data)
	{

		if (messagesId.length && jQuery('#' + messagesId))
			jQuery('#' + messagesId).html('');
		if (data.redirect) {
			window.location = data.redirect;
			exit;
		}
		if (data.error && errorsId.length && jQuery('#' + errorsId)) {
			jQuery('#' + errorsId).html(data.error).fadeIn();
            return;
		}

		if (data.message && messagesId.length && jQuery('#' + messagesId)) {
			jQuery('#' + messagesId).html(data.message).fadeIn();
		}
        resizeBorder();

		if (callback) {

			callback(data, step);
		}

		if (messagesId.length && jQuery('#' + messagesId)[0])
			jQuery('#' + messagesId).delay(3000).fadeOut(500);

	}, 'json');
	//return false;
}

function ajaxPost(url, data, callback)
{   //debugger;

	jQuery.post(url, data, function(data) {

        if (data && data.redirect) {
			window.location = data.redirect;
			return false;
		}

        if (data && data.error) {
            jQuery('body').append(data.error);
        }

		if (callback) {

			callback(data);
		}

	}, 'json');
}
