var support_name = '';
var chat_started_once=false;

$("#bx_chat_form").live('submit', function(){
	msg=$(".bx_chat_input").val();
	msg=jQuery.trim(msg);
	if (msg=='') {
		return false;
	}

	bx_chat_update(msg);
	return false;
});

/**
 * Start chat ajax requests
 * Get chat messages periodically
 */
function bx_chat_start() {
	clearInterval(bx_chat_int);
	if (chat_started_once==false) {
		user_name=$('#user_name').val();
		var wel_message=$('#bx_chat_welcome_message').text();
		wel_message=wel_message.replace(/%%admin%%/gi,"<span class=\"bx_chat_admin_name\">"+support_name+"</span>");
		wel_message=wel_message.replace(/%%username%%/gi,""+user_name+"");
		$('#bx_chat_text').append("<p class=\"bx_chat_message\">"+wel_message+'</p>');
		chat_started_once=true;
		$(".bx_chat_input").tbHinter();
	}
	bx_chat_int = setInterval( function(){
		bx_chat_update(false);
	}, bx_chat_update_interval );
}

/**
 * Stop chat ajax requests
 */
function bx_chat_stop() {
	clearInterval(bx_chat_int);
}

/**
 * Set status Online
 */
function bx_chat_online() {
	bx_chat_is_online = true;
	$(".bx_chat_offline_text").hide();
	$("bx_chat_email").hide();
	$("bx_chat_email_msg").hide();
	$(".bx_chat_online_text").show();
	$(".bx_chat_title_offline").hide();
}


/**
 * Set status Offline
 */
function bx_chat_offline() {
	bx_chat_is_online = false;
	$(".bx_chat_online_text").hide();
	$(".bx_chat_offline_text").show();
	$(".bx_chat_title_offline").show();
}


/**
 * Check status Online/Offline periodically
 */
function bx_chat_check_online() {
	if (bx_chat_int) {
		clearInterval(bx_chat_int);
	}
	bx_chat_int = setInterval( function(){
		bx_chat_update('check_online');
	}, bx_chat_check_online_interval );
}

/**
* show the chat window
*/
function bx_show_chat_window(){
	$("#bx_chat_email").hide();
	$("#bx_chat_email_msg").hide();
	$("#bx_chat_text").show();
	$("#bx_chat_input").show();
	$("#bx_chat_container").show('slow');
	bx_chat_start();
}


$("#bx_chat_click_here").live('click', function(){
	if (bx_chat_is_online==false) {
		// chat not online
		$(this).hide();
		$("#bx_chat_text").hide();
		$("#bx_chat_input").hide();
		$("#bx_chat_email").show();
		$("#bx_chat_container").show('slow');
		$('.bx_chat_email_message').textLimit(250, function( length, limit ) {
			$('#email_message_count').text( limit - length );
		});
		return false;
	}
	$(this).hide();
	if (chat_started_once==false) {
		$("#user_name").val(user_name);
		$("#user_name").tbHinter({text:'Enter your name'});
		$("#bx_chat_username").show();
	}
	else{
		bx_show_chat_window();
	}
});

$("#uname_form").live('submit', function(){
	if($("#user_name").val()!='' && $("#user_name").val()!='Enter your name'){
		$("#err_uname").hide();
		$("#bx_chat_username").hide();
		bx_show_chat_window();
	}
	else{
		$("#err_uname span").show();
	}
	return false;
});


$("#bx_chat_minimize").live('click', function(){
	bx_chat_stop();
	$("#bx_chat_container").hide('slow', function(){
		$("#bx_chat_click_here").show();
	});
	bx_chat_check_online();
});


$("#bx_chat_input .bx_chat_input").live('keydown', function(event){
	// when ENTER pressed
	if (event.which==13) {
		event.preventDefault();
		$("#bx_chat_form").submit();
	}
});


/**
 * Update chat text
 */
bx_chat_update = function (msg) {

	if (msg===false) {
		data = "last_msg_id="+last_msg_id;
	}else if (msg=='check_online') {
		data = "check_online=1";
	}else {
		data = "&user_name="+user_name+"&last_msg_id="+last_msg_id+"&msg="+msg;
		disable_chat_button();
	}
    if (user_id) {
        data += "&user_id="+user_id;
    }
	if (support_name!='') {
		data += "&support_name="+support_name;
	}

	set_status = '';

	$.ajax({
		type: "POST",
		async: false, //true = wait for last request to be finished
		//~ url: 'chat_write.php',
		url: ((typeof(is_admin)!='undefined' && is_admin==true) ? '../chat_write.php' : 'chat_write.php'),
		data: data,
		success: function(data) {
			if (data!='') {
				data_obj=jQuery.parseJSON(data);
				if (data_obj) {
					for (i=0;i<data_obj.length;i++) {
						//~ if (data_obj[i].user == user_name) {
						// if (data_obj[i].user_id == user_id) {
							// classname = 'bx_chat_user_message';
						// }else {
							// classname = 'bx_chat_message';
						// }
						if (data_obj[i].user == user_name) {
							classname = 'bx_chat_user_message';
						}else {
							classname = 'bx_chat_message';
						}
						if (data_obj[i].user && data_obj[i].msg) {
							// update messages only if user and msg exists
							$('#bx_chat_text').append("<p class=\""+classname+"\"><span class=\"bx_chat_user_name\">"+data_obj[i].user+"</span>: "+data_obj[i].msg+"</p>");
						}

                        if (data_obj[i].msg_id!=undefined) {
						    last_msg_id = data_obj[i].msg_id;
                        }

						if (data_obj[i].set_status!=undefined) {
							set_status = data_obj[i].set_status;
						}
						if (data_obj[i].support_name!=undefined) {
							support_name = data_obj[i].support_name;
						}
						//~ last_msg_id = data_obj[i].msg_id;
					}
				}

			}
			if (msg!==false && msg!='check_online') {
				$(".bx_chat_input").val('');
			}
			if (set_status=='online') {
				bx_chat_online();
			}
			if (set_status=='offline') {
				bx_chat_offline();
			}
			//scroll down after updating messages
			$("#bx_chat_text").attr({ scrollTop: $("#bx_chat_text").attr("scrollHeight") });
			//set background-color for even lines
			$("#bx_chat_text p:even").css("background-color", bx_chat_msg_even_bg_color);

			enable_chat_button();
		},
		error: function() {
			enable_chat_button();
		}
	});
}

disable_chat_button = function() {
	$("#bx_chat_input .submit").attr("disabled","disabled");
}

enable_chat_button = function() {
	$("#bx_chat_input .submit").attr("disabled","");
}



/**
 * send chat email to admin
 */
$("#bx_chat_form_email").live('submit', function(){
	var name=$("input:[name=bx_chat_email_name]").val();
	var email=$("input:[name=bx_chat_email_address]").val();
	var msg=$(".bx_chat_email_message").val();
	msg=jQuery.trim(msg);
	var thecode=$(".bx_chat_thecode").val();
	if (email=='' || !isValidEmailAddress(email) || msg=='' || thecode == '') {
        alert($("input:[name=error_message_check_email_form]").val());
		return false;
	}

    //send email
    
    data = "";
    data += "bx_chat_email_name="+name;
    data += "&bx_chat_email_address="+email;
    data += "&bx_chat_email_message="+msg;
    data += "&bx_chat_thecode="+thecode;

	$.ajax({
		type: "POST",
		async: false, //true = wait for last request to be finished
		url: 'chat_write.php',
		data: data,
		success: function(data) {
			var data_obj=jQuery.parseJSON(data);
			if (data_obj.status=='sent') {
				$("#bx_chat_email").hide();
				$("#bx_chat_email_msg").html(data_obj.message);
				$("#bx_chat_email_msg").show();
			}
			else{
				$("#emsg_header").html('<span style="color: #F00; font-size: 11px;">'+data_obj.message+'</span>');
			}
			
        },
		error: function() {
            $("#bx_chat_email").show();
            alert($("input:[name=error_message_not_sent]").val());
		}
    });
    return false;
});

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

(function($){
	$.fn.tbHinter = function(options) {

	var defaults = {
		text: 'type your message here and press [enter] to send...',
   		classa: 'txthint'
	};
	
	var options = $.extend(defaults, options);

	return this.each(function(){
	
		$(this).focus(function(){
			if($(this).val() == options.text){
				$(this).val('');
				$(this).removeClass(options.classa);
			}
		});
		
		$(this).blur(function(){
			if($(this).val() == ''){
				$(this).val(options.text);
				$(this).addClass(options.classa);
			}
		});
		
		$(this).blur();
		
	});
};
})(jQuery);

(function($){
	$.fn.clearTextLimit = function() {
		return this.each(function() {
			this.onkeydown = this.onkeyup = null;
		});
	};
	$.fn.textLimit = function( limit , callback ) {
		if ( typeof callback !== 'function' ) var callback = function() {};
		return this.each(function() {
			this.limit = limit;
			this.callback = callback;
			this.onkeydown = this.onkeyup = function() {
				this.value = this.value.substr(0,this.limit);
				this.reached = this.limit - this.value.length;
				this.reached = ( this.reached == 0 ) ? true : false;
				return this.callback( this.value.length, this.limit, this.reached );
			}
		});
	};
})(jQuery);
