// +++ Menu +++
var timeout         = 500;
var closetimer		= 10;
var chat_boobbles_W = 400;
var dialogW = 0;
var dialogH = 0;
var chat_timeout = 3000;

ddmenuitem      = 0;
opened_dialogs = new Array();


function open_dialog( id, parameters, page_wide) {
	if (!opened_dialogs[id]) {
		$("#" + id).dialog(parameters);
		opened_dialogs[id] = true;
	} else {
		$("#" + id).dialog("open");
	}
	if (page_wide) {
		load_page (page_wide,page_wide,id); 
	}

}

function init_menu () {
	$("input, textarea").focus(
 		function() {
	   		this.select();
		}
	);
	
	$("#go2login_button").bind("click", function() { 
		$("#needlogin").html("<div class='spinner_big'>&nbsp;</div>");
		open_dialog("needlogin", {width:'610px',height:'auto'}, "login.php"); 
		return false; 
	});
	$("#go2register_button").click( function() { load_page ('register.php','register.php'); return false; });
	$("#logout_button").click( function() { logout_wide("home.php"); chat_event("SI SLOGGA", "SI SLOGGA"); return false; });
	$("#chat_button").click( function () { $.post('/ajax/chat.php', {action:"open_my_chats"}); return false; } );
	
	
	$('#header_menu > li').mouseover(header_menu_open);
	$('#header_menu > li').mouseleave( function() { header_menu_timer(); } );
	$(".voce_menu").click( function() {
		$("#cover").toggle();
		if (this.pathname != "/") {
			if (this.className == "external voce_menu") {
				return true;
			} else {
				if (this.pathname) {
					load_page ("/" + this.pathname + ".php",this.pathname + ".php");
					$("#cover").show();
				}
			}
		}
		return false;
	});
}

function load_page (page_wide,text, target) {
	var rand_no = Math.ceil(1000000000*Math.random())
	var the_page = "/templates/" + page_wide + "?rnd=" + rand_no;
	if (!target) target = "page_wide";

	chat_event(text, page_wide);
	if ($.browser.msie && page_wide != "login.php") {	
		var ob = page_wide.split(".");
		window.location= ob[0];
	} else {
		$("#" + target).load(the_page, null, function () { $("#cover").fadeOut(); } );
	}
}

function pair_columns() {
	if ( $(".left_content").height() > $(".right_content").height() ) {
		max_height = $(".left_content").height();
	} else {
		max_height = $(".right_content").height();			
	}
	$(".left_content").height(max_height);
	$(".right_content").height(max_height);
}

function confirm_register (temp_id, code) {
	$(".confirmcode").toggle();
	$.post('/ajax/account.php', { action:"confirm_register", "temp_id":temp_id, "code": code},
	function (result) {
		ob = result.split(":");
		if (ob[0] == "ok") {
			chat_event("SI REGISTRA", "SI REGISTRA");
			$("#insert_code").hide();
			alert(ob[1]); // Ho creato il tuo account e ti ho inviato i dettagli via email, puoi adesso creare il tuo sito!
			window.location="/";
			//load_page ("cart.php","cart.php");
		} else {
			$(".confirmcode").toggle();
			$("#insert_code_text").html(ob[1]);
			jAlert(ob[1], "Attenzione");
		}
	});
}

function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

function login_wide () {
	$(".toggle").toggle();
	$.post('/ajax/account.php', {action:"login", "username": $("#username_login").val(), "username_2": $("#username_login").val(), password: $("#password").val()}, 
		function (result) {
			ob = result.split(":");
			if (ob[0] == "ko") {
				jAlert(ob[1], "Attenzione", function() { $("#username_login").focus()} );
				 	
			}
			if (ob[0] == "ok" && ob[1] != 0) {
				chat_event("SI LOGGA COME " + $("#username_login").val(), "SI LOGGA COME " + $("#username_login").val());
				jAlert(ob[1], "Conferma");
				if ($("#redirect").val() != "" &&  $("#redirect").val() != "/login") {
					window.location = $("#redirect").val(); 
				} else if (self_page == "/answers/bb-login.php") {
					window.location = refer_page;
				} else {
					load_page ("control_panel.php", "control_panel.php");
				}
				// $("#header_box").load("/templates/header_box.php", function () { init_menu();} );
				$("#header_box").load("/templates/header_box.php");
				$("#needlogin").dialog("close");
				$("#login_wide").toggle();
			}
			$(".toggle").toggle();
		}
	);
}

function logout_wide(URL) {
	$.post('/ajax/account.php', {action:"logout"}, 
		function (result) {
			ob = result.split(":");
			if (ob[0] == "ko") {
				jAlert(ob[1], "Attenzione");
			}
			if (ob[0] == "ok" && ob[1] != 0) {
				jAlert(ob[1], "Conferma");
				load_page(URL, URL);
//				$("#header_box").html("ciao");
				$("#header_box").load("/templates/header_box.php?" + Math.random() );
			}
		}
	);
	return false;
}


function header_menu_open(){
	header_menu_canceltimer();
	header_menu_close();
	ddmenuitem = $(this).find('ul').eq(0).css('visibility', 'visible');
}

function header_menu_close()
{ if(ddmenuitem) { ddmenuitem.css('visibility', 'hidden'); } }

function header_menu_timer()
{	closetimer = window.setTimeout(header_menu_close, timeout);}

function header_menu_canceltimer()
{	if(closetimer)
	{	window.clearTimeout(closetimer);
		closetimer = null;
		}
}


// $.context
jQuery.extend(
{
  context: function (context)
  {
    var co = 
    {
      callback: function (method)
      {
        if (typeof method == 'string') method = context[method];
        var cb = function () { method.apply(context, arguments); }
        return cb;
      }
    };
    return co;
  }
});

document.onclick = header_menu_close;

function validate_email(email) {
	if (!email.match(/^[^\.\-_]([a-zA-Z0-9_\.\-])+[^\.\-_\@]\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/))
		return false;
	else
		return true;
}

function validate_ftp_account(email) {
	if (!email.match(/^[^\.\-_]([a-zA-Z0-9_\.\-])+[^\.\-_\@]$/))
		return false;
	else
		return true;
}


function inspect(obj, maxLevels, level)
{
  var str = '', type, msg;

    // Start Input Validations
    // Don't touch, we start iterating at level zero
    if(level == null)  level = 0;

    // At least you want to show the first level
    if(maxLevels == null) maxLevels = 1;
    if(maxLevels < 1)     
        return '<font color="red">Error: Levels number must be > 0</font>';

    // We start with a non null object
    if(obj == null)
    return '<font color="red">Error: Object <b>NULL</b></font>';
    // End Input Validations

    // Each Iteration must be indented
    str += '<ul>';

    // Start iterations for all objects in obj
    for(property in obj)
    {
      try
      {
          // Show "property" and "type property"
          type =  typeof(obj[property]);
          str += '<li>(' + type + ') ' + property + 
                 ( (obj[property]==null)?(': <b>null</b>'):('')) + '</li>';

          // We keep iterating if this property is an Object, non null
          // and we are inside the required number of levels
          if((type == 'object') && (obj[property] != null) && (level+1 < maxLevels))
          str += inspect(obj[property], maxLevels, level+1);
      }
      catch(err)
      {
        // Is there some properties in obj we can't access? Print it red.
        if(typeof(err) == 'string') msg = err;
        else if(err.message)        msg = err.message;
        else if(err.description)    msg = err.description;
        else                        msg = 'Unknown';

        str += '<li><font color="red">(Error) ' + property + ': ' + msg +'</font></li>';
      }
    }

      // Close indent
      str += '</ul>';

    return str;
}

function select_list (ajaxfile, target_id, parameters, var_name, id) {
	$.post(ajaxfile, parameters, 
	  function(data){
		if (!parameters.id) parameters.id = var_name;
	    var result = "<select name='" + var_name + "' id='" + parameters.id + "'>";
		if (parameters.first_row) result += "<option>" + parameters.first_row + "</option>";
		for (row in data) {
	    	result += "<option>" + eval("data[row]." + var_name) + "</option>";
		}
		result += "</select>";
		if (parameters.replace)
			$(target_id).html(result);
		else
			$(target_id).append(result);
		if (parameters.callback) {
			eval(parameters.callback + "(" + parameters.callback_parameters + ");");
		}
	}, "json");
}


// Chat

var window_open = 0;
var wideUserID = 0;
var old_counter=0;

function chat_button() {
	var data = new Array();
	var counter_html = "";
	$("#msg_counter").html("");
	var msg_counter_total = 0;
	var idle_close_flag = new Array();
	
		$.post("/ajax/chat.php", { action: "whos_online", chat_id : chat_id}, 
			function (data) {		
				output = "<ul>";
				var online_counter = 0;	
				for (row in data) {
					var print_flag = false;	
				
					if (data[row].counter_to > 0) {
						$("#msg_counter").html("<span class='chat_counter'><span class='chat_counter_p'>" + data[row].counter_to + "</span></span>");
						msg_counter_total += parseFloat(data[row].counter_to);
						if (window.old_counter != data[row].counter_to) {
							$.sound.play("/sounds/msg.swf");
							window.old_counter = data[row].counter_to;
						}
					}
					
					sessionID = data[row].chat_id;
					
					if (data[row].counter_to > 0) {
						counter_html = "<span class='chat_counter'><span class='chat_counter_p'>" + data[row].counter_to +  "</span></span>"; 
						print_flag = true;
					} else {
						counter_html = "";
					}
					
					if ( data[row].idle > 50) {
							if (idle_close_flag[sessionID] == null) {
								$("#chat_box_" + sessionID).dialog('option', 'title', "Offline");
							}
							default_msg = offline_message;
					} else {
						print_flag = true;
						online_counter += 1;
						$("#chat_box_" + sessionID).dialog('option', 'title', chat_with_string + " " +  data[row].username);

						if (data[row].chat_id == 1) {
							if (data[row].idle < 50) {
								//default_msg = online_message;
								default_msg = offline_message; 
							} else {
								default_msg = offline_message;
							}
						}
					}

					if (print_flag) { 
						if (data[row].username == "gabriele") {
							data[row].username = "<font color='green'>Gabriele (supporto)</font>";
						}
						output += "<li><a href='#' id='chat_" + sessionID + "' class='chat_to' title=\"" + data[row].username + "\">"  + data[row].username + counter_html + "</a></li>"; }
				
				}
				
				output += "</ul>";
				var msg_counter_total_string = "";
				if (wideUserID == 1) {
					msg_counter_total_string = " [" +  online_counter + "]";
				}
				if (msg_counter_total > 0) {
					msg_counter_total_string += "<span class='chat_counter'><span class='chat_counter_p'>" + msg_counter_total + "</span></span>";
				} 
				$("#msg_counter_total").html(msg_counter_total_string);
					
				$("#whos_online").html(output);
				$(".must_be_registered").click(
					function () {
						jAlert("Per contattarci devi prima registrarti o loggarti! La registrazione &egrave; gratuita!", "Wide");
						load_page ('register.php','register.php'); 
						return false;
					}
				);
				
				$(".chat_to").unbind("click");
							
				$(".chat_to").click(
					function () {
						ob = this.id.split("chat_");
						sessionID=ob[1];
						if (window.opened_chat[sessionID]) { 
							//alert("gia aperta " + sessionID);
							$("#chat_form_" + sessionID +" .chat_screen").html("");
							chat_open(sessionID, $("#chat_"+sessionID).html());
							chat_read(false, true, window.page_wide, sessionID);
						} else {
							//alert("mai aperta " + sessionID);
							chat_open(sessionID, $("#chat_"+sessionID).html());
							chat_read(false, true, window.page_wide, sessionID);
							if (default_msg && wideUserID != 1) $("#chat_form_" + sessionID +" .chat_screen").append("<div class='clear right'><img class='chat_avatar_thumb_other' src='/images/avatars/thumbs/1.png' title='Gabriele, Wide.it Webmaster'><span class='other_chat'><p>" + default_msg + "</p></span></div><div class='clear'></div>");
						}
						return false;
					}
				);
				
			}, 
		"json"); 
	//$("#chat_li").header_menu_open();
	//alert("button");
	setTimeout("chat_button()", 10000);
}


function chat_read(timeout_flag, history_flag, page_wide, msg_from) {

    $.post("/ajax/chat.php", { action: "read", history_flag: history_flag, browsing: page_wide, msg_from: msg_from }, 
		function(data){ 
			for (row in data) {
				sessionID = data[row].msg_from;
				//alert(data[row].event);
				if ( data[row].event == "command" ) {
					load_page (data[row].command + ".php",data[row].command + ".php");
				} else {
					if (data[row].window_open == "yes") {
//					if (window.opened_chat[sessionID] == "yes") {
						chat_open(sessionID, data[row].chattitle);
						if ( data[row].output ) {
							$.sound.play("/sounds/msg.swf");
							$("#chat_box_" + sessionID).dialog('option', 'title', data[row].chattitle);
						 	$("#chat_form_" + sessionID +" .chat_screen").append(data[row].output);
							$("#chat_form_" + sessionID +" .other_chat").css( "width", chat_boobbles_W );
							$("#chat_form_" + sessionID +" .me_chat").css( "width", chat_boobbles_W );			
							//$("#chat_form_" + sessionID +" .chat_post").focus(); 
							//chat_scroll_down (sessionID);
							setTimeout("chat_scroll_down (" + sessionID + ")", 400);
							chat_timeout = 3000;
						}
					} 
				} 
			}
		}, "json"
	);
	if (chat_timeout > 10000) chat_timeout = 10000; else chat_timeout = chat_timeout + 1000;
	if (timeout_flag) setTimeout("chat_read(true, false, window.page_wide)", chat_timeout);
}

function chat_resize() {
	dialogW = $("#chat_box_" + sessionID).dialog('option', 'width');
	dialogH = $("#chat_box_" + sessionID).dialog('option', 'height');

	chat_boobbles_W = (dialogW-160) + "px";
	if (dialogW > 60 && dialogH > 120) {
		$("#chat_form_" + sessionID +" .chat_screen").css( "width", dialogW-50 );
		$("#chat_form_" + sessionID +" .chat_screen").css( "height", dialogH-90 );
		$("#chat_form_" + sessionID +" .chat_post").css( "width", dialogW-60 );
		$("#chat_form_" + sessionID +" .other_chat").css( "width", chat_boobbles_W );
		$("#chat_form_" + sessionID +" .me_chat").css( "width", chat_boobbles_W );
		$("#chat_form_" + sessionID +" .chat_screen").each(function(){this.scrollTop = this.scrollHeight});
	}
}
 
function chat_open(sessionID, chattitle) {
	if (opened_chat[sessionID] == null) {
		//$.sound.play("/sounds/beep.swf");
		$("#chat_box").clone().attr('id','chat_box_' + sessionID).appendTo(".chats");
		$("#chat_box_" + sessionID + " .chat_form").attr('id','chat_form_' + sessionID);
		var window_width = Math.random() * $(window).width() / 2;
		var window_height = (Math.random() * $(window).height() / 2);		
		var chat_windows_position = new Array (window_width,window_height);
		$("#chat_box_" + sessionID).dialog({position: chat_windows_position, title:chattitle, resizable: true, width:'500px', minHeight:300, minWidth:300,
			resizeStop: function(){
				chat_resize() ;
			}, 
			close: function (){
				closed_chat[sessionID] = true;
				chat_event('chiude finestra chat');
				$.post("/ajax/chat.php", {action:"window_open", value: "no", chat_2_open:sessionID});
			}});
		

		$("#chat_form_" + sessionID).submit(
			function() {
				var message = $("#chat_form_" + sessionID +" .chat_post").val();
				if ( $("#chat_form_" + sessionID +" .chat_post").val() != "" ) { 
					$("#chat_form_" + sessionID +" .chat_post").val("");
					ob = this.id.split("chat_form_");
					sessionID=ob[1];
					$.post("/ajax/chat.php", { msg_to : sessionID, action: 'post', message: message}, 
						function(result) {
							if (wideUserID == null || wideUserID == false) wideUserID = 0;
							$("#chat_form_" + sessionID +" .chat_screen").append("<div class='clear left'><img class='chat_avatar_thumb_me' src='/images/avatars/thumbs/" + wideUserID + ".png'><span class='me_chat'><p>" + result + "</p></span></div><div class='clear'></div>");
							$("#chat_form_" + sessionID +" .me_chat").css( "width", chat_boobbles_W );
							$("#chat_form_" + sessionID +" .chat_post").focus(); 
							$("#chat_form_" + sessionID +" .chat_screen").each(function(){this.scrollTop = this.scrollHeight});
						}
					);
				}
				return false;
		   	}
		);
		
		$("#chat_box_" + sessionID + " .chat_screen").click( function () {
			$("#chat_form_" + sessionID +" .chat_post").focus(); 	
			chat_scroll_down(sessionID);
		});
		
		opened_chat[sessionID] = true;
	} else {
		if (closed_chat[sessionID]) {
			//$.sound.play("/sounds/beep.swf");
			$("#chat_box_" + sessionID).dialog("open");
		} 
	}
	$.post("/ajax/chat.php", {action:"window_open", value: "yes", chat_2_open:sessionID});
}

function chat_be_online() {
	$.post("/ajax/chat.php", {action: 'be_online'}, function (result){ chat_id = result['chat_id'];  wideUserID =  result['wideUserID']; chat_button(); }, "json");
}

function chat_event(text, page_wide) {
	$.post("/ajax/chat.php", {action: 'event', page: page_wide, text: text}, null, "json");
}

function chat_scroll_down (sessionID) {
	$("#chat_form_" + sessionID +" .chat_screen").scrollTo( '100%', 1);
}

jQuery.fn.maxlength = function(){
    $("textarea[maxlength]").keypress(function(event){
        var key = event.which;
 
        //all keys including return.
        if(key >= 33 || key == 13) {
            var maxLength = $(this).attr("maxlength");
            var length = this.value.length;
            if(length >= maxLength) {
                event.preventDefault();
            }
        }
    });
}

	
/**
 * Initialise input hints on all matched inputs.
 *
 * Usage examples:
 *
 * Add hints to all inputs with the 'title' attribute set:
 *   $('input[title],textarea[title]').inputHint();
    *
    * Add hints to all matched elements, grabbing the hint text from each element's
    * adjacent <kbd/> tag:
    *   $('input').inputHint({using: '+ kbd'});
 *
 * Options keys:
 *  using: jQuery selector locating element containing hint text, relative to
 *         the input currently being considered.
 *  hintAttr - tag attribute containing hint text. Default: 'title'
 *  hintClass - CSS class to apply to inputs with active hints. Default: 'hint'
 */
$.fn.inputHint = function(options) {
	
	options = $.extend({hintClass: 'blur', hintAttr: 'title'}, options || {});
	
	function hintFor(element) {
		var h;
		if (options.using && (h = $(options.using, element)).length > 0) {
			return h.text();
		} else {
			return $(element).attr(options.hintAttr) || '';
		}
	}

	function showHint() {
		if ($(this).val() == '') {
			$(this).addClass(options.hintClass).val(hintFor(this));
		}
	}

	function removeHint() {
		if ($(this).hasClass(options.hintClass)) $(this).removeClass(options.hintClass).val('');
	}
	
	this.filter(function() { return !!hintFor(this); })
		.focus(removeHint).blur(showHint).blur();

       this.each(function() {
           var self = this;
           $(this).parents('form').submit(function() { removeHint.apply(self); });
       });

	return this.end(); // undo filter

};

