/**
 * jQuery Validator add-on medthods
 */

jQuery.validator.addMethod("notEqualDefaultValue", function(arg_value, arg_element, arg_params) {

    var reg_pattern = new RegExp( arg_params, "i");

    return this.optional(arg_element) || (reg_pattern.test(arg_value)==false);
}, "Please supply valid value");

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, "");
    return this.optional(element) || phone_number.length > 9 &&
        phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please supply a valid phone number");

/*----------------------------------------------------------------------------*/

/**
 * Load Form in Modalbox
 *
 * @param {string} arg_form_name
 */
function ev_loadform(arg_form_name) {
	var form_name = 'name='+arg_form_name;
	var request_timestamp = new Date().getTime();
   $.ajax({
		type: "POST",
		url: 'ajax/loadform.php?rt='+request_timestamp,//SITE_URL + 'ajax/loadform?rt=' + request_timestamp,
		async: false,
		data: form_name,
		 cache: false,
		dataType: 'json',
		success: function(json){
			$.fn.colorbox({html:'<div>'+json.payload+'</div>',open:true, close:'', opacity:0.3, overlayClose:false, width:500, height:500});
			 return false;
		},
	   error: function(xhr, ajaxOptions, thrownError) {
		   alert("There was an error. Please try again later.");
	   } 
	})
}

/**
 * Lead Form Processing
 *
 * @param {object} arg_form_obj
 */
function ev_leadGenProcess(arg_form_obj) {

    // Check required fields
    var required_result = $(arg_form_obj).valid();


    if( required_result == true ) {

        //display process indicator
        ev_showFormProcessIndicator(arg_form_obj);

        var affiliate_name    = ev_getLandingPageMetaTagValue('affiliate-name');
        var form_data         = $(arg_form_obj).serialize();
        var request_timestamp = new Date().getTime();

        // get affiliate meta value, if exist
        if( affiliate_name != null ) {
            form_data = form_data + '&affiliate_name=' + affiliate_name;
        }

        $.ajax({
           type: "POST",
           url: SITE_URL + 'ajax/leadprocess?rt=' + request_timestamp,
           data:  form_data,
           cache: false,
           dataType: "json",
           success: function(response) {
               if( response.success == true ) {

                   //hide process indicator
                   ev_hideFormProcessIndicator(arg_form_obj);

                   if( response.popup == true ) {
                       //load html structure into modalbox
                       $.fn.colorbox({html:response.payload, open:true, close:'', opacity:0.3});
                       return false;
                   } else {
                      //load html structure onto page
                      $(arg_form_obj).replaceWith(response.payload);
                   }

               } else {
                   alert(response.errors);
                   ev_hideFormProcessIndicator(arg_form_obj);
               }
           },
           error: function(xhr, ajaxOptions, thrownError) {
               alert("There was an error. Please try again later.");
               ev_hideFormProcessIndicator(arg_form_obj);
           }
        });

    } else {
        $.fn.colorbox.resize();
    }

}


/**
 * Hide process ajax indicator
 * @param {Object} arg_form_obj
 */
function ev_hideFormProcessIndicator(arg_form_obj) {

    //check if the element exist
    if( $("span.form_processing", arg_form_obj).length > 0 ) {
        $("span.form_processing", arg_form_obj).html("");
        $("span.form_processing", arg_form_obj).hide();
    }

}


/**
 * Show process ajax indicator
 * @param {Object} arg_form_obj
 */
function ev_showFormProcessIndicator(arg_form_obj) {

    //check if the element exist
    if( $("span.form_processing", arg_form_obj).length > 0 ) {
        $("span.form_processing", arg_form_obj).html("Please wait...");
        $("span.form_processing", arg_form_obj).show();
    }

}


/**
 * Set default or alert text for input type:text
 * @param {Object} obj
 * @param {string} text_on_blur
 */
function setInstructionText(obj, text_on_blur) {
  if ($(obj).val() == '') {
    $(obj).val(text_on_blur);
    $(obj).addClass('greyout');
  }
}


/**
 * Remove default or alert text from input type:text
 * @param {Object} obj
 * @param {string} text_on_blur
 */
function removeInstructionText(obj, text_on_blur) {
  if ($(obj).val() == text_on_blur) {
    $(obj).val('');
    $(obj).removeClass('greyout');
  }
}


/**
 * Event Tracking by GA Tracking API
 * @param {string} arg_event_category
 * @param {string} arg_event_action
 * @param {string} arg_event_label
 * ex. 'Signin', 'click', 'from top navigation'
 * ex. 'Join', 'click', 'from main menubar navigation'
 */
function ev_gaEventTracker(arg_event_category, arg_event_action, arg_event_label) {

    //simple check to make sure the google tracking function loaded
    if( pageTracker && pageTracker._trackEvent ) {
        pageTracker._trackEvent(arg_event_category, arg_event_action, arg_event_label);
    }
}


/**
 * Get value from landing page header meta tag.
 *
 * Example use#1: to in co-response with Google Analytic Funnel Tracking
 * <meta name="funnel-root-name" content="funnel root name HERE" />
 * ex. in GA Ananlytic we have /lp-1b-step1 as Goal ID, so the funnel-root-name
 * will be "1b".
 *
 *
 */
function ev_getLandingPageMetaTagValue(arg_meta_label) {

    var meta_value    = null;
    var meta_elements = document.getElementsByTagName('meta');

    for (i = 0; i < meta_elements.length; i++) {
        name_attribute = meta_elements[i].name.search(arg_meta_label);

        if (name_attribute != -1) {
            meta_value = meta_elements[i].content;
        }
    }

    return meta_value;
}

/**
 * This method will load image file onto page
 * The pixel will be placed at bottom of the page (last child of <body> tag) and
 * will also set to invisible.
 * @param {String} arg_pixel_url
 */
function ev_firePixel(arg_pixel_url) {
    load_pixel = '<img src="' + arg_pixel_url +'" border="0" style="display:none;" width="1" height="1" />';
    $("body").append(load_pixel);
}

