// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function textCounter(field,cntfield,maxlimit) {
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	else	// otherwise, update 'characters left' counter
		cntfield.innerHTML = maxlimit - field.value.length;
}

/* -------------------------------------------------------------------------------- */
/* DivsAdInfinitum:																	*/
/* Allows you to repeat a piece of HTML ad inifinitum based on a user action.		*/
/* It handles renaming the id and name attributes on form field children, though	*/
/* you must embed %d where the enumeration is to occur. 							*/
/*																					*/
/* FOR EXAMPLE:																		*/
/* <div id="div_to_repeat" style="display:none;"><input name="course[XXX]"></div>	*/
/*																					*/
/* var replicator = DivsAdInfinitum('div_to_repeat');								*/
/* replicator.addNew('id_of_container');											*/
/*																					*/
/* The result is that the LAST child of div#id_of_container will be					*/
/* div#div_to_repeat_0 whose input tag has a name attribute of course[0]. Calling	*/
/* it again will increment the value by 1. 											*/
/* -------------------------------------------------------------------------------- */
function DivsAdInfinitum(div) {
	return {
	div : $(div),
	counter : 1,
	
	/* Values param is optional. It is a hash the maps values to field names. 		*/
	/* If field name contains brackets, then last word in brackets is used. 		*/
	/* Example: activities[0][last_word]											*/
	addNew : function (container,values){
		container = $(container);
		var new_div = new Element('div', {
			id: (this.div.id + this.counter)
		});
		Element.insert(new_div, this.div.innerHTML);
		container.appendChild(new_div);
		Element.show(new_div);

		var form_fields = $$("#"+new_div.id+" input,#"+new_div.id+" select");
		for (i = 0; i < form_fields.length; i++) {
			form_fields[i].id = form_fields[i].id.replace(/XXX/g, this.counter);
			form_fields[i].name = form_fields[i].name.replace(/XXX/g, this.counter);
			
			var base_name = form_fields[i].name;
			base_name = base_name.gsub(']','');
			var parts = base_name.split('[');
			base_name = parts[parts.length-1];
			if (values) form_fields[i].value = values[base_name];
		}
		
		this.counter++;
	},
	setDiv : function (div) {
		this.div = $(div);
	}
	};
}

/* Used by user::show and airbeds::show */
function expand_sections() {
	$$('.expandable').invoke('setStyle','height:auto;')
	$$('.expand_link').invoke('hide')
}

function rollover(element,original_state_class,new_state_class) {
	Element.addClassName(element,new_state_class);
	Element.removeClassName(element,original_state_class);
}

/* Calendar Stuff */

function calendar_is_not_set_date(date_field) { return (!date_field.value || ('mm/dd/yyyy'==date_field.value)) }

function calendar_process_onfocus(field) {
	if (calendar_is_not_set_date(field)) field.onclick();
}

function process_checkin_onclick(checkout_field){
    $(checkout_field).onclick();
}

function calendar_helper_simple_today() {
	var dt = new Date();
	dt.setHours(0);
	dt.setMinutes(0);
	dt.setSeconds(0);
	dt.setMilliseconds(0);
	return dt;
}

function calendar_show_cal(field,position,checkout_field) {
    if(arguments.length < 3){
        checkout_field = 'checkout';
    }

	position = typeof(position) != 'undefined' ? position : 'absolute';
	
	var default_offset = 0;

    /* override for special offers */
    if(checkout_field == 'one_calendar_override'){
        return new CalendarDateSelect(field, {/*popup_by:$('lwlb_date_span_start'), */position:position,month_year:'label',buttons:true, clear_button:true,default_date_offset:default_offset, year_range:[new Date().getFullYear(),new Date().getFullYear()+1], valid_date_check:function (dt){ return(dt >= calendar_helper_simple_today()); } /*, onchange:function(){return true;} */ } );
    }else{
        return new CalendarDateSelect(field, {/*popup_by:$('lwlb_date_span_start'), */position:position,month_year:'label',buttons:true, clear_button:true,default_date_offset:default_offset, year_range:[new Date().getFullYear(),new Date().getFullYear()+1], valid_date_check:function (dt){ return(dt >= calendar_helper_simple_today()); }, onchange:function(){process_checkin_onclick(checkout_field);} } );
    }
}

function calendar_show_cal_checkout(field,checkin_field,position) {
	position = typeof(position) != 'undefined' ? position : 'absolute';

	var must_be_after_this_date = new Date();
	if (!calendar_is_not_set_date($(checkin_field))) {
		must_be_after_this_date = Date.parse($(checkin_field).value);
	}
	if (isNaN(must_be_after_this_date)) {
		must_be_after_this_date = new Date();
	}

	var default_offset = Math.ceil((must_be_after_this_date - new Date())/(24*60*60*1000)) + 1;
	return new CalendarDateSelect(field, {/*popup_by:$('lwlb_date_span_start'),*/ position:position,month_year:'label',buttons:true, clear_button:true, default_date_offset:default_offset, year_range:[new Date().getFullYear(),new Date().getFullYear()+1], valid_date_check:function (dt){ return(dt > must_be_after_this_date); } } );
}

/* Censoring */

var re_yijianfang = /yijianfang\.com/;


// Very simplified --- any of these things probably signifiy a website
var re_http = /(ftp|http|https):\/\//i;
var re_www = /www\.\w+/i;
var re_domain_ext = /\w+\.(com|net|org|biz|ws|name)/i;

//var re_phone_number = /[0-9 \-\(\)\.\+\\=]{9,100}\d/; // allow / since it commonly used in dates 1/1/2010
var re_phone_number = /([0-9]{3,9}[\- ]?){3,9}/; 

var re_phone_word = /((zero|one|two|three|four|five|six|seven|eight|nine)\W+){6,100}/i;

var re_email = /\w+(\.\w+){0,1}(@)[\w|\-]+(\.|\W{1,3}dot\W{1,3})\w+/;
var re_email_domain = /( aol|gmail|hotmail|msn|yahoo)(\.com){0,1}/i;

var censor_attempt_counter = 0;

function censor_validate_content(message,show_warning) {

    if (re_yijianfang.test(message)) {
      return(true); // if the message refers to yijianfang.cn, then we give it a free pass
    }

    var is_website = (re_http.test(message) || re_www.test(message) || re_domain_ext.test(message));
	var is_phone = (re_phone_number.test(message) || re_phone_word.test(message));
	var is_email = (re_email.test(message) || re_email_domain.test(message));
	
	if (is_website || is_phone || is_email) {
		censor_attempt_counter++;
		
		if ((censor_attempt_counter>3) && show_warning) {
			alert("Warning: It appears you trying to send contact information. 100% of scams begin with contact information being exchanged and ultimately exchanging money offline. If you follow the rules, you are 100% protected against scams. If you believe your message does not contain a website, phone number, or e-mail address, then e-mails us at contact@yijianfang.cn and we can help.");
		} else {
			alert('It appears as though you entered a website, phone number, or e-mail address. This information cannot be exchanged until after the booking is complete for your protection. Scams can only occur if you exchange money outside of the system. Please edit your message and try again.');
		}
		return(false);
	}

    // make sure there is a message
    //if ((message=="Type message here...") || (message==""))  {
    //    alert('Please enter a message to send.');
    //    return (false);
    //}

	return(true);
}


/* Lightweight lightbox */

function lwlb_show(id,options) {
    if (!options) options = {};
    
//	$('lwlb_overlay').style.display = 'block';
	$(id).style.display = 'block';
	if (!options.no_scroll) window.scroll(0,0);
}
function lwlb_hide(id) {
	$(id).hide();
	$('lwlb_overlay').hide();
}

function pluralize(count,word) {
	return(count+" "+word+((count==1) ? '' : 's'));			
}

/* Dashboard */

function show_options(thread_id){
    star_el = jQuery("div#thread_"+thread_id+"_starred");
    if(!star_el.hasClass('permashow')){
        star_el.fadeIn(50); 
    }
    hidden_el = jQuery("div#thread_"+thread_id+"_hidden")
    if(!hidden_el.hasClass('permashow')){
        hidden_el.fadeIn(50); 
    }

}
function hide_options(thread_id){
    hidden_el = jQuery("div#thread_"+thread_id+"_hidden")
    if(!hidden_el.hasClass('permashow')){
        hidden_el.fadeOut(50); 

        star_el = jQuery("div#thread_"+thread_id+"_starred");
        if(!star_el.hasClass('permashow')){
            star_el.fadeOut(50); 
        }
    }
}

/* Page 3 */
function select_tab(category, content_id, selected_li){
    jQuery('.' + category + '_link').removeClass('selected');
    selected_li.addClass('selected');
    jQuery('#' + content_id).show();
    jQuery('.' + category + '_content').hide();
    jQuery('#' + content_id).show();
}

var newWin = null;
function popup(strURL, strType, strHeight, strWidth) {  
    if (newWin != null && !newWin.closed) { 
        newWin.close();
        var strOptions=""; 
    }

    if (strType=="console"){ strOptions="resizable,height="+strHeight+",width="+strWidth;  }
    if (strType=="fixed") { strOptions="status,height="+  strHeight+",width="+strWidth;  }
    if (strType=="elastic"){ strOptions="toolbar,menubar,scrollbars,"+  "resizable,location,height="+  strHeight+",width="+strWidth; } 

    newWin = window.open(strURL, 'newWin', strOptions);  
    newWin.focus();  
}


/* after page load: */
jQuery(document).ready(function(){
    /* fadeaway any and all elements with class .fadeaway */
    setTimeout('jQuery(".fadeaway").fadeOut(4000)', 4000);
});

/* 
 * extend jQuery to support cookies
*/

var DEFAULT_COOKIE_OPTIONS = { path: '/', expires: 30 };

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function save_page3_view_to_cookie(hosting_id){
    add_data_to_cookie('viewed_page3_ids', hosting_id);
}

/* 
 * mark_viewed_page_links();
 *
 * 1) Grab each text link on the page that matches rooms/[0-9]+
 * 2) Add class='visited' to those links if the room ID is stored in 'viewed_page3_ids' cookie
*/

function mark_viewed_page_links(){
    page3_ids = get_viewed_page3_ids();

    if(page3_ids == false){
        return false;
    }

    $$('a').each(function(e){
        e.href.scan(/rooms\/([0-9]+)/, function(match){
            if((e.down() == null) || (e.down().tagName.toLowerCase() != 'img')){
                if(page3_ids.indexOf(match[1]) != -1){
                    e.addClassName('visited');
                    e.up().previous('a').addClassName('visited');
                }
            }
        });
    });
}

function get_viewed_page3_ids(){
    comma_separated_page3_ids = jQuery.cookie('viewed_page3_ids');

    if(comma_separated_page3_ids != null){
        array_of_page3_ids = comma_separated_page3_ids.split(',');
        array_of_page3_ids = array_of_page3_ids.uniq();

        return array_of_page3_ids;
    }

    return false;
}

//assumes cookie exists
function add_data_to_cookie(cookie_name, val){
    existing_data = jQuery.cookie(cookie_name);

    if(existing_data == null){
        new_data = val;
    }else{
        //Note: you can lose 1 piece of data when viewing your 75 place, if you view it twice in a row. Performance tradeoff.
        new_data = existing_data + ',' + val;
        new_data = new_data.split(',');

        while(new_data.length > 75){
            new_data.splice(0,1);
        }

        new_data = new_data.uniq();
        new_data = new_data.join(',');
    }

    jQuery.cookie(cookie_name, new_data, DEFAULT_COOKIE_OPTIONS);
}

function show_super_lightbox(lb_id){
    jQuery('#transparent_bg_overlay').fadeIn(40);
    jQuery('#'+lb_id).fadeIn(40);
    jQuery('#transparent_bg_overlay').click(function(){
        hide_super_lightbox(lb_id);
    });
}

function hide_super_lightbox(lb_id){
    jQuery('#'+lb_id).fadeOut(40);
    jQuery('#transparent_bg_overlay').fadeOut(40);
    jQuery('#transparent_bg_overlay').unbind('click');
}

//console log wrapper, will only log into firebug, preventing breakage in other browsers
function log(dataToLog){
    if (window.console && window.console.firebug) {
        console.log(dataToLog);
    }
}

Array.prototype.unique = function(){
    var vals = this;
    var uniques = [];
    for(var i=vals.length;i--;){
        var val = vals[i];  
        if(jQuery.inArray( val, uniques )===-1){
            uniques.unshift(val);
        }
    }
    return uniques;
} 

//left string pad only
jQuery.leftPad = function(input, totalStringLength, paddingChar) {
    var output = input.toString();
    if (!paddingChar) { paddingChar = '0'; }
    while (output.length < totalStringLength) {
        output = paddingChar + output;
    }
    return output;
};


function scrollToById(el_id){
    jQuery('html,body').animate({scrollTop: jQuery("#"+el_id).offset().top},'fast');
}



/* LazyLoad 2.0 http://wonko.com/post/lazyload-200-released */
LazyLoad=function(){var f=document,g,b={},e={css:[],js:[]},a;function j(l,k){var m=f.createElement(l),d;for(d in k){if(k.hasOwnProperty(d)){m.setAttribute(d,k[d])}}return m}function h(d){var l=b[d];if(!l){return}var m=l.callback,k=l.urls;k.shift();if(!k.length){if(m){m.call(l.scope||window,l.obj)}b[d]=null;if(e[d].length){i(d)}}}function c(){if(a){return}var k=navigator.userAgent,l=parseFloat,d;a={gecko:0,ie:0,opera:0,webkit:0};d=k.match(/AppleWebKit\/(\S*)/);if(d&&d[1]){a.webkit=l(d[1])}else{d=k.match(/MSIE\s([^;]*)/);if(d&&d[1]){a.ie=l(d[1])}else{if((/Gecko\/(\S*)/).test(k)){a.gecko=1;d=k.match(/rv:([^\s\)]*)/);if(d&&d[1]){a.gecko=l(d[1])}}else{if(d=k.match(/Opera\/(\S*)/)){a.opera=l(d[1])}}}}}function i(r,q,s,m,t){var n,o,l,k,d;c();if(q){q=q.constructor===Array?q:[q];if(r==="css"||a.gecko||a.opera){e[r].push({urls:[].concat(q),callback:s,obj:m,scope:t})}else{for(n=0,o=q.length;n<o;++n){e[r].push({urls:[q[n]],callback:n===o-1?s:null,obj:m,scope:t})}}}if(b[r]||!(k=b[r]=e[r].shift())){return}g=g||f.getElementsByTagName("head")[0];q=k.urls;for(n=0,o=q.length;n<o;++n){d=q[n];if(r==="css"){l=j("link",{href:d,rel:"stylesheet",type:"text/css"})}else{l=j("script",{src:d})}if(a.ie){l.onreadystatechange=function(){var p=this.readyState;if(p==="loaded"||p==="complete"){this.onreadystatechange=null;h(r)}}}else{if(r==="css"&&(a.gecko||a.webkit)){setTimeout(function(){h(r)},50*o)}else{l.onload=l.onerror=function(){h(r)}}}g.appendChild(l)}}return{css:function(l,m,k,d){i("css",l,m,k,d)},js:function(l,m,k,d){i("js",l,m,k,d)}}}();

jQuery(document).ready(function() {
   
   jQuery("#language_currency_display").toggle(function(){
      jQuery('#language_currency_selector_container').show();
       jQuery('#language_currency_display').addClass('selected');
   }, function(){
      jQuery('#language_currency_selector_container').hide();
       jQuery('#language_currency_display').removeClass('selected');

   });

   jQuery("#language_currency").mouseleave(function(ev) {
     
        if (jQuery('#language_currency_selector_container').is(':visible') && !(jQuery(ev.relatedTarget).parents().index(jQuery('#language_currency_selector_container')) >= 0) ) {
       jQuery('#language_currency_display').click();
        }
        });



    jQuery("#language_currency_selector li.language").click(function() {
        jQuery(this).effect('pulsate', {times:10}, 1000);
        jQuery("#language_currency_selector").css('cursor', 'progress');
      jQuery.post('/users/change_locale', {new_locale: jQuery(this).attr('name')}, function(response){
          window.location.reload(true);
      });
    });

    jQuery("#language_currency_selector li.currency").click(function() {
           jQuery(this).effect('pulsate', {times:10}, 1000);
        jQuery("#language_currency_selector").css('cursor', 'progress');
      jQuery.post('/users/change_currency', {new_currency: jQuery(this).attr('name')}, function(response){
          window.location.reload(true);
      });
    });
});

/* implement indexOf for ie7 */
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}




/* Migrate old and place new JS into this little guy */
var Yijianfang = {
		
init : function(options){
    Yijianfang.Utils.formatPhoneNumbers();

    Yijianfang.Utils.isUserLoggedIn = options == null || options['userLoggedIn'] == null || !options['userLoggedIn'] ? false : true;

    /* fadeaway any and all elements with class .fadeaway */
    setTimeout('jQuery(".fadeaway").fadeOut(4000)', 4000);
},
		
    /*
     * function Validator
     * returns true if your input passes validation, false if it does not
     *
     * type - a string identifying what you want to match, use CAPS
     * item - can be anything you please - The code you write defines it
     *
     * *note - passing undefined in either param will return false
     *
     * example usage: StringValidator.validate('email', 'smarkle@userinput.com')
     */
    StringValidator : {
        Regexes : {
            //email : /^[a-zA-Z0-9\.\+]{1,63}@[a-zA-Z0-9]{2,63}(\.[a-zA-Z]{2,4}){1,2}$/, //get a real email validator!!!
            email : /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
            date : /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/,
            //This checks to see if there are at 10 - 15 digits in the phone number field
            phone : /((.*)?\d(.*?)){10,15}/
        },

        validate : function(type, item){
            if(type === undefined || item === undefined || typeof item != 'string'){ // || typeof Regex[type] != Regex
                return false;
            }
            return(item.match(Yijianfang.StringValidator.Regexes[type]) !== null);

            return false;
        }
    },

    Utils : {
        usingIosDevice : function() {
            return !((navigator.userAgent.indexOf('iPhone') == -1) && (navigator.userAgent.indexOf('iPod') == -1) && (navigator.userAgent.indexOf('iPad') == -1));
        },

        keyPressEventName : jQuery.browser.mozilla ? 'keypress' : 'keydown',

        /* takes labels with .inner_text class and puts them inside the text field */
        setInnerText : function(fieldsToClearOnSubmit){
            jQuery.each(jQuery('.inner_text'), function(index, e){

                var inputField = jQuery(e).next('input');
                var userVal = inputField.val();

                inputField.attr('defaultValue', e.innerHTML);
                inputField.val(e.innerHTML);

                if(userVal.length === 0){
                    //inputField.defaultValue = e.innerHTML;
                } else {
                    inputField.val(userVal);
                    inputField.addClass('active');
                }

                inputField.bind('focus', function(){
                    if(jQuery(inputField).val() == inputField.attr('defaultValue')) {
                        jQuery(inputField).val('');
                        global_test_var = jQuery(inputField);
                        jQuery(inputField).addClass('active');
                    }

                    jQuery(inputField).removeClass('error');

                    return true;
                });

                inputField.bind('blur', function(){

                    if(jQuery(inputField).val() === '') {
                        jQuery(inputField).removeClass('active');
                        jQuery(inputField).val(inputField.attr('defaultValue'));
                    } else {
                        jQuery(inputField).removeClass('error');
                    }
                });

                if(fieldsToClearOnSubmit){
                    fieldsToClearOnSubmit.push(inputField);
                }

                jQuery(e).remove();
            });

        },

        // if too long...trim it!
        // otherwise, update 'characters left' counter
        textCounter : function(field,countField,maxlimit) {
            if (field.val().length > maxlimit){
                field.val(field.val().substring(0, maxlimit));
            } else {
                countField.html(maxlimit - field.val().length);
            }
        }

    }
};


//moved from jquery.validatephone.js to yijianfang.js
(function(jQuery) {

	jQuery.fn.validatePhone = (function(defaultCountry) {		
		
		if (!defaultCountry) 
			defaultCountry = 'CN'
			
		phone = jQuery(this);
		country = jQuery('#'+phone.attr('id')+'_country');
		countrySelector = jQuery('#'+phone.attr('id')+'_country_selector');
		feedback = jQuery('#'+phone.attr('id')+'_feedback');
		popup = jQuery('#'+phone.attr('id')+'_popup');
		
		if (!phone.is(":visible"))
			return;
		
		try {
		
			if (phone.attr('value') == '') {
				// TODO: Clear feedback
				country.attr('value', '');
				popup.css('display', 'none');
				return true;	
			}
	
			var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
		    var number = phoneUtil.parseAndKeepRawInput(phone.attr('value'), defaultCountry);
			var countryCode = phoneUtil.getRegionCodeForNumber(number);
			var formattedNumber = phoneUtil.format(number, i18n.phonenumbers.PhoneNumberFormat.E164);

			if (formattedNumber && countryCode) {
				phone.attr('value', formattedNumber);
				country.attr('value', countryCode);
				countrySelector.attr('value', countryCode);
				popup.css('display', 'none');
				return true;
			} else {		
				throw('');
			}
		
		} catch (e) {
			country.attr('value', '');
			feedbackBody = '';
			if (e != '')
				feedbackBody += "<p><b>"+e+".</b></p>";
			feedbackBody += "<p>Sorry, but we do not regconize your phone number. Please help us by selecting your country.</p><p>Ensure that you have provided your full phone number, including area code, and country code if you have it available.</p><p>If you are still unable to successfully enter your phone number, please contact <a href='mailto:support@yijianfang.cn'>support@yijianfang.cn</a>.</p>";
			feedback.html(feedbackBody);
			
			popup.css('top', phone.position().top+phone.outerHeight(true)+1).css('left', phone.position().left+((phone.outerWidth(true)-popup.outerWidth(true))/2));
			
			phone.closest('form').find('div.validated_phone_popup').css('display', 'none'); // hide all other popups
			popup.css('display', 'block');
			return false;
		}
	});

	jQuery.fn.validatedPhone = (function() {
		
		this.addClass('validated_phone_input');
		
		countryModal = jQuery("<div></div>");
		countryModal.attr('id', this.attr('id')+"_popup").attr('class', 'validated_phone_popup').css('display', 'none');
		this.after(countryModal);
		
		jQuery('#'+this.attr('id')+'_country_selector').css('display', 'inherit').appendTo(countryModal);
		jQuery("<div id='"+this.attr('id')+"_feedback'></div>").appendTo(countryModal);
		
		this.blur(function() {
			jQuery(this).validatePhone(jQuery('#'+jQuery(this).attr('id')+'_country_selector').attr('value'));
		});
		
		jQuery('#'+jQuery(this).attr('id')+'_country_selector').change(function() {
			jQuery('#'+jQuery(this).attr('id').replace('_country_selector', '')).validatePhone(jQuery(this).attr('value'));
		});
		
		// Only bind this function once, even if validatedPhone is called multiple times.
		this.closest('form').unbind('submit.validated_phone');
		this.closest('form').bind('submit.validated_phone', function() {
			validFields = jQuery(this).find('input.validated_phone_input').map(function() {
				if (!jQuery(this).validatePhone()) {
					jQuery(this).focus();
					return 'f';
				} else {
					return 't';
				}
			});
			return (jQuery.inArray('f', validFields) < 0);
		});
		
		this.validatePhone();
		
		return this;

	});
	
})(jQuery);

